forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenapi.ts
More file actions
1585 lines (1409 loc) · 47.6 KB
/
openapi.ts
File metadata and controls
1585 lines (1409 loc) · 47.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 {
BooleanLiteral,
compilerAssert,
DiscriminatedUnion,
EmitContext,
emitFile,
Enum,
EnumMember,
getAllTags,
getAnyExtensionFromPath,
getDateFormat,
getDiscriminatedUnion,
getDiscriminator,
getDoc,
getFormat,
getKnownValues,
getMaxItems,
getMaxLength,
getMaxValue,
getMaxValueExclusive,
getMinItems,
getMinLength,
getMinValue,
getMinValueExclusive,
getNamespaceFullName,
getPattern,
getPropertyType,
getService,
getSummary,
ignoreDiagnostics,
IntrinsicScalarName,
IntrinsicType,
isDeprecated,
isErrorType,
isGlobalNamespace,
isNeverType,
isNullType,
isNumericType,
isSecret,
isStringType,
isTemplateDeclaration,
isTemplateDeclarationOrInstance,
listServices,
Model,
ModelIndexer,
ModelProperty,
Namespace,
navigateTypesInNamespace,
NewLine,
NumericLiteral,
Program,
ProjectionApplication,
projectProgram,
resolvePath,
Scalar,
Service,
StringLiteral,
TwoLevelMap,
Type,
TypeNameOptions,
Union,
UnionVariant,
} from "@typespec/compiler";
import * as http from "@typespec/http";
import {
createMetadataInfo,
getAuthentication,
getHttpService,
getRequestVisibility,
getStatusCodeDescription,
getVisibilitySuffix,
HttpAuth,
HttpOperation,
HttpOperationParameter,
HttpOperationParameters,
HttpOperationResponse,
isContentTypeHeader,
isOverloadSameEndpoint,
MetadataInfo,
reportIfNoRoutes,
ServiceAuthentication,
Visibility,
} from "@typespec/http";
import {
checkDuplicateTypeName,
getExtensions,
getExternalDocs,
getOpenAPITypeName,
getParameterKey,
isReadonlyProperty,
resolveOperationId,
shouldInline,
} from "@typespec/openapi";
import { buildVersionProjections } from "@typespec/versioning";
import yaml from "js-yaml";
import { getOneOf, getRef } from "./decorators.js";
import { FileType, OpenAPI3EmitterOptions, reportDiagnostic } from "./lib.js";
import {
OpenAPI3Discriminator,
OpenAPI3Document,
OpenAPI3Header,
OpenAPI3OAuthFlows,
OpenAPI3Operation,
OpenAPI3Parameter,
OpenAPI3ParameterBase,
OpenAPI3Schema,
OpenAPI3SchemaProperty,
OpenAPI3SecurityScheme,
OpenAPI3Server,
OpenAPI3ServerVariable,
} from "./types.js";
const defaultFileType: FileType = "yaml";
const defaultOptions = {
"new-line": "lf",
"omit-unreachable-types": false,
} as const;
export async function $onEmit(context: EmitContext<OpenAPI3EmitterOptions>) {
const options = resolveOptions(context);
const emitter = createOAPIEmitter(context.program, options);
await emitter.emitOpenAPI();
}
function findFileTypeFromFilename(filename: string | undefined): FileType {
if (filename === undefined) {
return defaultFileType;
}
switch (getAnyExtensionFromPath(filename)) {
case ".yaml":
case ".yml":
return "yaml";
case ".json":
return "json";
default:
return defaultFileType;
}
}
export function resolveOptions(
context: EmitContext<OpenAPI3EmitterOptions>
): ResolvedOpenAPI3EmitterOptions {
const resolvedOptions = { ...defaultOptions, ...context.options };
const fileType =
resolvedOptions["file-type"] ?? findFileTypeFromFilename(resolvedOptions["output-file"]);
const outputFile = resolvedOptions["output-file"] ?? `openapi.${fileType}`;
return {
fileType,
newLine: resolvedOptions["new-line"],
omitUnreachableTypes: resolvedOptions["omit-unreachable-types"],
outputFile: resolvePath(context.emitterOutputDir, outputFile),
};
}
export interface ResolvedOpenAPI3EmitterOptions {
fileType: FileType;
outputFile: string;
newLine: NewLine;
omitUnreachableTypes: boolean;
}
/**
* Represents a node that will hold a JSON reference. The value is computed
* at the end so that we can defer decisions about the name that is
* referenced.
*/
class Ref {
value?: string;
toJSON() {
compilerAssert(this.value, "Reference value never set.");
return this.value;
}
}
/**
* Represents a non-inlined schema that will be emitted as a definition.
* Computation of the OpenAPI schema object is deferred.
*/
interface PendingSchema {
/** The TYPESPEC type for the schema */
type: Type;
/** The visibility to apply when computing the schema */
visibility: Visibility;
/**
* The JSON reference to use to point to this schema.
*
* Note that its value will not be computed until all schemas have been
* computed as we will add a suffix to the name if more than one schema
* must be emitted for the type for different visibilities.
*/
ref: Ref;
}
/**
* Represents a schema that is ready to emit as its OpenAPI representation
* has been produced.
*/
interface ProcessedSchema extends PendingSchema {
schema: OpenAPI3Schema | undefined;
}
function createOAPIEmitter(program: Program, options: ResolvedOpenAPI3EmitterOptions) {
let root: OpenAPI3Document;
// Get the service namespace string for use in name shortening
let serviceNamespace: string | undefined;
let currentPath: any;
let currentEndpoint: OpenAPI3Operation;
let metadataInfo: MetadataInfo;
// Keep a map of all Types+Visibility combinations that were encountered
// that need schema definitions.
let pendingSchemas = new TwoLevelMap<Type, Visibility, PendingSchema>();
// Reuse a single ref object per Type+Visibility combination.
let refs = new TwoLevelMap<Type, Visibility, Ref>();
// Keep track of inline types still in the process of having their schema computed
// This is used to detect cycles in inline types, which is an
let inProgressInlineTypes = new Set<Type>();
// Map model properties that represent shared parameters to their parameter
// definition that will go in #/components/parameters. Inlined parameters do not go in
// this map.
let params: Map<ModelProperty, any>;
// Keep track of models that have had properties spread into parameters. We won't
// consider these unreferenced when emitting unreferenced types.
let paramModels: Set<Type>;
// De-dupe the per-endpoint tags that will be added into the #/tags
let tags: Set<string>;
const typeNameOptions: TypeNameOptions = {
// shorten type names by removing TypeSpec and service namespace
namespaceFilter(ns) {
const name = getNamespaceFullName(ns);
return name !== serviceNamespace;
},
};
return { emitOpenAPI };
function initializeEmitter(service: Service, version?: string) {
const auth = processAuth(service.type);
root = {
openapi: "3.0.0",
info: {
title: service.title ?? "(title)",
version: version ?? service.version ?? "0000-00-00",
description: getDoc(program, service.type),
},
externalDocs: getExternalDocs(program, service.type),
tags: [],
paths: {},
security: auth?.security,
components: {
parameters: {},
requestBodies: {},
responses: {},
schemas: {},
examples: {},
securitySchemes: auth?.securitySchemes ?? {},
},
};
const servers = http.getServers(program, service.type);
if (servers) {
root.servers = resolveServers(servers);
}
serviceNamespace = getNamespaceFullName(service.type);
currentPath = root.paths;
pendingSchemas = new TwoLevelMap();
refs = new TwoLevelMap();
metadataInfo = createMetadataInfo(program, {
canonicalVisibility: Visibility.Read,
canShareProperty: (p) => isReadonlyProperty(program, p),
});
inProgressInlineTypes = new Set();
params = new Map();
paramModels = new Set();
tags = new Set();
}
function isValidServerVariableType(program: Program, type: Type): boolean {
switch (type.kind) {
case "String":
case "Union":
case "Scalar":
return ignoreDiagnostics(
program.checker.isTypeAssignableTo(
type.projectionBase ?? type,
program.checker.getStdType("string"),
type
)
);
case "Enum":
for (const member of type.members.values()) {
if (member.value && typeof member.value !== "string") {
return false;
}
}
return true;
default:
return false;
}
}
function validateValidServerVariable(program: Program, prop: ModelProperty) {
const isValid = isValidServerVariableType(program, prop.type);
if (!isValid) {
reportDiagnostic(program, {
code: "invalid-server-variable",
format: { propName: prop.name },
target: prop,
});
}
return isValid;
}
function resolveServers(servers: http.HttpServer[]): OpenAPI3Server[] {
return servers.map((server) => {
const variables: Record<string, OpenAPI3ServerVariable> = {};
for (const [name, prop] of server.parameters) {
if (!validateValidServerVariable(program, prop)) {
continue;
}
const variable: OpenAPI3ServerVariable = {
default: prop.default ? getDefaultValue(prop.default) : "",
description: getDoc(program, prop),
};
if (prop.type.kind === "Enum") {
variable.enum = getSchemaForEnum(prop.type).enum;
} else if (prop.type.kind === "Union") {
variable.enum = getSchemaForUnion(prop.type, Visibility.Read).enum;
} else if (prop.type.kind === "String") {
variable.enum = [prop.type.value];
}
attachExtensions(program, prop, variable);
variables[name] = variable;
}
return {
url: server.url,
description: server.description,
variables,
};
});
}
async function emitOpenAPI() {
const services = listServices(program);
if (services.length === 0) {
services.push({ type: program.getGlobalNamespaceType() });
}
for (const service of services) {
const commonProjections: ProjectionApplication[] = [
{
projectionName: "target",
arguments: ["json"],
},
];
const originalProgram = program;
const versions = buildVersionProjections(program, service.type);
for (const record of versions) {
const projectedProgram = (program = projectProgram(originalProgram, [
...commonProjections,
...record.projections,
]));
const projectedServiceNs: Namespace = projectedProgram.projector.projectedTypes.get(
service.type
) as Namespace;
await emitOpenAPIFromVersion(
projectedServiceNs === projectedProgram.getGlobalNamespaceType()
? { type: projectedProgram.getGlobalNamespaceType() }
: getService(program, projectedServiceNs)!,
services.length > 1,
record.version
);
}
}
}
function resolveOutputFile(service: Service, multipleService: boolean, version?: string): string {
const suffix = [];
if (multipleService) {
suffix.push(getNamespaceFullName(service.type));
}
if (version) {
suffix.push(version);
}
if (suffix.length === 0) {
return options.outputFile;
}
const extension = getAnyExtensionFromPath(options.outputFile);
const filenameWithoutExtension = options.outputFile.slice(0, -extension.length);
return `${filenameWithoutExtension}.${suffix.join(".")}${extension}`;
}
async function emitOpenAPIFromVersion(
service: Service,
multipleService: boolean,
version?: string
) {
initializeEmitter(service, version);
try {
const httpService = ignoreDiagnostics(getHttpService(program, service.type));
reportIfNoRoutes(program, httpService.operations);
for (const operation of httpService.operations) {
if (operation.overloading !== undefined && isOverloadSameEndpoint(operation as any)) {
continue;
} else {
emitOperation(operation);
}
}
emitParameters();
emitSchemas(service.type);
emitTags();
// Clean up empty entries
if (root.components) {
for (const elem of Object.keys(root.components)) {
if (Object.keys(root.components[elem as any]).length === 0) {
delete root.components[elem as any];
}
}
}
if (!program.compilerOptions.noEmit && !program.hasError()) {
// Write out the OpenAPI document to the output path
await emitFile(program, {
path: resolveOutputFile(service, multipleService, version),
content: serializeDocument(root, options.fileType),
newLine: options.newLine,
});
}
} catch (err) {
if (err instanceof ErrorTypeFoundError) {
// Return early, there must be a parse error if an ErrorType was
// inserted into the TypeSpec output
return;
} else {
throw err;
}
}
}
function emitOperation(operation: HttpOperation): void {
const { path: fullPath, operation: op, verb, parameters } = operation;
// If path contains a query string, issue msg and don't emit this endpoint
if (fullPath.indexOf("?") > 0) {
reportDiagnostic(program, { code: "path-query", target: op });
return;
}
if (!root.paths[fullPath]) {
root.paths[fullPath] = {};
}
currentPath = root.paths[fullPath];
if (!currentPath[verb]) {
currentPath[verb] = {};
}
currentEndpoint = currentPath[verb];
const currentTags = getAllTags(program, op);
if (currentTags) {
currentEndpoint.tags = currentTags;
for (const tag of currentTags) {
// Add to root tags if not already there
tags.add(tag);
}
}
currentEndpoint.operationId = resolveOperationId(program, op);
applyExternalDocs(op, currentEndpoint);
// Set up basic endpoint fields
currentEndpoint.summary = getSummary(program, op);
currentEndpoint.description = getDoc(program, op);
currentEndpoint.parameters = [];
currentEndpoint.responses = {};
const visibility = getRequestVisibility(verb);
emitEndpointParameters(parameters.parameters, visibility);
emitRequestBody(parameters, visibility);
emitResponses(operation.responses);
if (isDeprecated(program, op)) {
currentEndpoint.deprecated = true;
}
attachExtensions(program, op, currentEndpoint);
}
function emitResponses(responses: HttpOperationResponse[]) {
for (const response of responses) {
emitResponseObject(response);
}
}
function isBinaryPayload(body: Type, contentType: string) {
return (
body.kind === "Scalar" &&
body.name === "bytes" &&
contentType !== "application/json" &&
contentType !== "text/plain"
);
}
function getOpenAPIStatuscode(response: HttpOperationResponse): string {
switch (response.statusCode) {
case "*":
return "default";
default:
return response.statusCode;
}
}
function emitResponseObject(response: Readonly<HttpOperationResponse>) {
const statusCode = getOpenAPIStatuscode(response);
const openapiResponse = currentEndpoint.responses[statusCode] ?? {
description: response.description ?? getResponseDescriptionForStatusCode(statusCode),
};
for (const data of response.responses) {
if (data.headers && Object.keys(data.headers).length > 0) {
openapiResponse.headers ??= {};
// OpenAPI can't represent different headers per content type.
// So we merge headers here, and report any duplicates.
// It may be possible in principle to not error for identically declared
// headers.
for (const [key, value] of Object.entries(data.headers)) {
if (openapiResponse.headers[key]) {
reportDiagnostic(program, {
code: "duplicate-header",
format: { header: key },
target: response.type,
});
continue;
}
openapiResponse.headers[key] = getResponseHeader(value);
}
}
if (data.body !== undefined) {
openapiResponse.content ??= {};
for (const contentType of data.body.contentTypes) {
const isBinary = isBinaryPayload(data.body.type, contentType);
const schema = isBinary
? { type: "string", format: "binary" }
: getSchemaOrRef(data.body.type, Visibility.Read);
openapiResponse.content[contentType] = { schema };
}
}
}
currentEndpoint.responses[statusCode] = openapiResponse;
}
function getResponseDescriptionForStatusCode(statusCode: string) {
if (statusCode === "default") {
return "An unexpected error response.";
}
return getStatusCodeDescription(statusCode) ?? "unknown";
}
function getResponseHeader(prop: ModelProperty): OpenAPI3Header | undefined {
return getOpenAPIParameterBase(prop, Visibility.Read);
}
function getSchemaOrRef(type: Type, visibility: Visibility): any {
const refUrl = getRef(program, type);
if (refUrl) {
return {
$ref: refUrl,
};
}
if (type.kind === "Scalar" && program.checker.isStdType(type)) {
return getSchemaForScalar(type);
}
if (type.kind === "String" || type.kind === "Number" || type.kind === "Boolean") {
// For literal types, we just want to emit them directly as well.
return mapTypeSpecTypeToOpenAPI(type, visibility);
}
if (type.kind === "Intrinsic" && type.name === "unknown") {
return getSchemaForIntrinsicType(type);
}
if (type.kind === "EnumMember") {
// Enum members are just the OA representation of their values.
if (typeof type.value === "number") {
return { type: "number", enum: [type.value] };
} else {
return { type: "string", enum: [type.value ?? type.name] };
}
}
if (type.kind === "ModelProperty") {
return resolveProperty(type, visibility);
}
type = metadataInfo.getEffectivePayloadType(type, visibility);
const name = getOpenAPITypeName(program, type, typeNameOptions);
if (shouldInline(program, type)) {
const schema = getSchemaForInlineType(type, visibility, name);
if (schema === undefined && isErrorType(type)) {
// Exit early so that syntax errors are exposed. This error will
// be caught and handled in emitOpenAPI.
throw new ErrorTypeFoundError();
}
// helps to read output and correlate to TypeSpec
if (schema) {
schema["x-typespec-name"] = name;
}
return schema;
} else {
// Use shared schema when type is not transformed by visibility from the canonical read visibility.
if (!metadataInfo.isTransformed(type, visibility)) {
visibility = Visibility.Read;
}
const pending = pendingSchemas.getOrAdd(type, visibility, () => ({
type,
visibility,
ref: refs.getOrAdd(type, visibility, () => new Ref()),
}));
return {
$ref: pending.ref,
};
}
}
function getSchemaForInlineType(type: Type, visibility: Visibility, name: string) {
if (inProgressInlineTypes.has(type)) {
reportDiagnostic(program, {
code: "inline-cycle",
format: { type: name },
target: type,
});
return {};
}
inProgressInlineTypes.add(type);
const schema = getSchemaForType(type, visibility);
inProgressInlineTypes.delete(type);
return schema;
}
function getParamPlaceholder(property: ModelProperty) {
let spreadParam = false;
if (property.sourceProperty) {
// chase our sources all the way back to the first place this property
// was defined.
spreadParam = true;
property = property.sourceProperty;
while (property.sourceProperty) {
property = property.sourceProperty;
}
}
const refUrl = getRef(program, property);
if (refUrl) {
return {
$ref: refUrl,
};
}
if (params.has(property)) {
return params.get(property);
}
const placeholder = {};
// only parameters inherited by spreading from non-inlined type are shared in #/components/parameters
if (spreadParam && property.model && !shouldInline(program, property.model)) {
params.set(property, placeholder);
paramModels.add(property.model);
}
return placeholder;
}
function emitEndpointParameters(parameters: HttpOperationParameter[], visibility: Visibility) {
for (const httpOpParam of parameters) {
if (params.has(httpOpParam.param)) {
currentEndpoint.parameters.push(params.get(httpOpParam.param));
continue;
}
if (httpOpParam.type === "header" && isContentTypeHeader(program, httpOpParam.param)) {
continue;
}
emitParameter(httpOpParam, visibility);
}
}
function emitRequestBody(parameters: HttpOperationParameters, visibility: Visibility) {
const body = parameters.body;
if (body === undefined) {
return;
}
const requestBody: any = {
description: body.parameter ? getDoc(program, body.parameter) : undefined,
content: {},
};
const contentTypes = body.contentTypes.length > 0 ? body.contentTypes : ["application/json"];
for (const contentType of contentTypes) {
const isBinary = isBinaryPayload(body.type, contentType);
const bodySchema = isBinary
? { type: "string", format: "binary" }
: getSchemaOrRef(body.type, visibility);
const contentEntry: any = {
schema: bodySchema,
};
requestBody.content[contentType] = contentEntry;
}
currentEndpoint.requestBody = requestBody;
}
function emitParameter(parameter: HttpOperationParameter, visibility: Visibility) {
if (isNeverType(parameter.param.type)) {
return;
}
const ph = getParamPlaceholder(parameter.param);
currentEndpoint.parameters.push(ph);
// If the parameter already has a $ref, don't bother populating it
if (!("$ref" in ph)) {
populateParameter(ph, parameter, visibility);
}
}
function getOpenAPIParameterBase(
param: ModelProperty,
visibility: Visibility
): OpenAPI3ParameterBase | undefined {
const typeSchema = getSchemaForType(param.type, visibility);
if (!typeSchema) {
return undefined;
}
const schema = applyIntrinsicDecorators(param, typeSchema);
if (param.default) {
schema.default = getDefaultValue(param.default);
}
// Description is already provided in the parameter itself.
delete schema.description;
const oaiParam: OpenAPI3ParameterBase = {
required: !param.optional,
description: getDoc(program, param),
schema,
};
attachExtensions(program, param, oaiParam);
return oaiParam;
}
function populateParameter(
ph: OpenAPI3Parameter,
parameter: HttpOperationParameter,
visibility: Visibility
) {
ph.name = parameter.name;
ph.in = parameter.type;
if (parameter.type === "query") {
if (parameter.format === "csv") {
ph.style = "simple";
} else if (parameter.format === "multi") {
ph.style = "form";
ph.explode = true;
}
} else if (parameter.type === "header") {
if (parameter.format === "csv") {
ph.style = "simple";
}
}
Object.assign(ph, getOpenAPIParameterBase(parameter.param, visibility));
}
function emitParameters() {
for (const [property, param] of params) {
const key = getParameterKey(
program,
property,
param,
root.components!.parameters!,
typeNameOptions
);
root.components!.parameters![key] = { ...param };
for (const key of Object.keys(param)) {
delete param[key];
}
param.$ref = "#/components/parameters/" + encodeURIComponent(key);
}
}
function emitSchemas(serviceNamespace: Namespace) {
const processedSchemas = new TwoLevelMap<Type, Visibility, ProcessedSchema>();
processSchemas();
if (!options.omitUnreachableTypes) {
processUnreferencedSchemas();
}
// Emit the processed schemas. Only now can we compute the names as it
// depends on whether we have produced multiple schemas for a single
// TYPESPEC type.
for (const group of processedSchemas.values()) {
for (const [visibility, processed] of group) {
let name = getOpenAPITypeName(program, processed.type, typeNameOptions);
if (group.size > 1) {
name += getVisibilitySuffix(visibility, Visibility.Read);
}
checkDuplicateTypeName(program, processed.type, name, root.components!.schemas);
processed.ref.value = "#/components/schemas/" + encodeURIComponent(name);
if (processed.schema) {
root.components!.schemas![name] = processed.schema;
}
}
}
function processSchemas() {
// Process pending schemas. Note that getSchemaForType may pull in new
// pending schemas so we iterate until there are no pending schemas
// remaining.
while (pendingSchemas.size > 0) {
for (const [type, group] of pendingSchemas) {
for (const [visibility, pending] of group) {
processedSchemas.getOrAdd(type, visibility, () => ({
...pending,
schema: getSchemaForType(type, visibility),
}));
}
pendingSchemas.delete(type);
}
}
}
function processUnreferencedSchemas() {
const addSchema = (type: Type) => {
if (!processedSchemas.has(type) && !paramModels.has(type) && !shouldInline(program, type)) {
getSchemaOrRef(type, Visibility.Read);
}
};
const skipSubNamespaces = isGlobalNamespace(program, serviceNamespace);
navigateTypesInNamespace(
serviceNamespace,
{
model: addSchema,
scalar: addSchema,
enum: addSchema,
union: addSchema,
},
{ skipSubNamespaces }
);
processSchemas();
}
}
function emitTags() {
for (const tag of tags) {
root.tags!.push({ name: tag });
}
}
function getSchemaForType(type: Type, visibility: Visibility): OpenAPI3Schema | undefined {
const builtinType = mapTypeSpecTypeToOpenAPI(type, visibility);
if (builtinType !== undefined) return builtinType;
switch (type.kind) {
case "Intrinsic":
return getSchemaForIntrinsicType(type);
case "Model":
return getSchemaForModel(type, visibility);
case "ModelProperty":
return getSchemaForType(type.type, visibility);
case "Scalar":
return getSchemaForScalar(type);
case "Union":
return getSchemaForUnion(type, visibility);
case "UnionVariant":
return getSchemaForUnionVariant(type, visibility);
case "Enum":
return getSchemaForEnum(type);
case "Tuple":
return { type: "array", items: {} };
case "TemplateParameter":
// Note: This should never happen if it does there is a bug in the compiler.
reportDiagnostic(program, {
code: "invalid-schema",
format: { type: `${type.node.id.sv} (template parameter)` },
target: type,
});
return undefined;
}
reportDiagnostic(program, {
code: "invalid-schema",
format: { type: type.kind },
target: type,
});
return undefined;
}
function getSchemaForIntrinsicType(type: IntrinsicType): OpenAPI3Schema {
switch (type.name) {
case "unknown":
return {};
}
reportDiagnostic(program, {
code: "invalid-schema",
format: { type: type.name },
target: type,
});
return {};
}
function getSchemaForEnum(e: Enum) {
const values = [];
if (e.members.size === 0) {
reportUnsupportedUnion("empty");
return undefined;
}
const type = enumMemberType(e.members.values().next().value);
for (const option of e.members.values()) {
if (type !== enumMemberType(option)) {
reportUnsupportedUnion();
continue;
}
values.push(option.value ?? option.name);
}
const schema: any = { type, description: getDoc(program, e) };
if (values.length > 0) {
schema.enum = values;
}
return schema;
function enumMemberType(member: EnumMember) {
if (typeof member.value === "number") {
return "number";
}
return "string";
}
function reportUnsupportedUnion(messageId: "default" | "empty" = "default") {
reportDiagnostic(program, { code: "union-unsupported", messageId, target: e });
}
}
/**
* A TypeSpec union maps to a variety of OA3 structures according to the following rules:
*
* * A union containing `null` makes a `nullable` schema comprised of the remaining
* union variants.
* * A union containing literal types are converted to OA3 enums. All literals of the
* same type are combined into single enums.
* * A union that contains multiple items (after removing null and combining like-typed
* literals into enums) is an `anyOf` union unless `oneOf` is applied to the union
* declaration.
*/
function getSchemaForUnion(union: Union, visibility: Visibility) {
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 discriminator = getDiscriminator(program, union);
for (const variant of variants) {
if (isNullType(variant.type)) {
nullable = true;
continue;
}