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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
changeKind: feature
packages:
- "@typespec/openapi3"
---

[converter] Import schema-level `examples` arrays as `@example` decorators, preserving values and order when round-tripping OpenAPI 3.1 and 3.2. Invalid non-array examples are ignored with a warning.

```tsp
@example(#{ name: "Spot" })
@example(#{ name: "Fluffy" })
model Pet {
name: string;
}
```
103 changes: 101 additions & 2 deletions packages/openapi3/src/cli/actions/convert/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export async function convertOpenAPI3Document(
document: SupportedOpenAPIDocuments,
{ disableExternalRefs, namespace }: ConvertOpenAPI3DocumentOptions = {},
) {
const conversionDocument = hoistInlineBodyExampleSchemas(document);
const dereferenceOptions = disableExternalRefs
? {
onDereference: (data: { schema: AnyObject; ref: string }): void => {
Expand All @@ -41,11 +42,14 @@ export async function convertOpenAPI3Document(
},
}
: {};
const { specification } = await dereference(document as unknown as AnyObject, dereferenceOptions);
const { specification } = await dereference(
conversionDocument as unknown as AnyObject,
dereferenceOptions,
);
if (!specification) {
throw new Error("Failed to dereference OpenAPI document");
}
const context = createContext(document, console, namespace);
const context = createContext(conversionDocument, console, namespace);
const program = transform(context);
const content = generateMain(program, context);
try {
Expand All @@ -57,3 +61,98 @@ export async function convertOpenAPI3Document(
return content;
}
}

function hoistInlineBodyExampleSchemas(
document: SupportedOpenAPIDocuments,
): SupportedOpenAPIDocuments {
const converted = structuredClone(document) as SupportedOpenAPIDocuments;
const mutableDocument = converted as any;
const components = (mutableDocument.components ??= {});
const schemas = (components.schemas ??= {});
let nextSchemaIndex = 0;

function hoistContentSchemas(content: Record<string, any> | undefined): void {
for (const mediaType of Object.values(content ?? {})) {
const schema = mediaType?.schema;
if (
!schema ||
typeof schema !== "object" ||
"$ref" in schema ||
!("examples" in schema) ||
(Array.isArray(schema.examples) && schema.examples.length === 0)
) {
continue;
}

let name: string;
do {
name = `__OpenAPIExampleBody${nextSchemaIndex++}`;
} while (name in schemas);

// A literal cannot be the base of a scalar, but can be a named union variant.
schemas[name] =
schema.const === undefined ? schema : { ...schema, anyOf: [{ const: schema.const }] };
mediaType.schema = { $ref: `#/components/schemas/${name}` };
}
}

function hoistRequestBody(requestBody: any): void {
if (requestBody && typeof requestBody === "object" && !("$ref" in requestBody)) {
hoistContentSchemas(requestBody.content);
}
}

function hoistResponses(responses: any): void {
if (!responses || typeof responses !== "object" || "$ref" in responses) {
return;
}

for (const response of Object.values(responses)) {
if (response && typeof response === "object" && !("$ref" in response)) {
hoistContentSchemas((response as any).content);
}
}
}

for (const requestBody of Object.values(components.requestBodies ?? {})) {
hoistRequestBody(requestBody);
}
for (const response of Object.values(components.responses ?? {})) {
if (response && typeof response === "object" && !("$ref" in response)) {
hoistContentSchemas((response as any).content);
}
}

function hoistOperation(operation: any): void {
if (!operation || typeof operation !== "object") {
return;
}

if ("requestBody" in operation || "responses" in operation) {
hoistRequestBody(operation.requestBody);
hoistResponses(operation.responses);
}
}

function visitPathItem(pathItem: any): void {
if (!pathItem || typeof pathItem !== "object") {
return;
}

hoistOperation(pathItem.query);
for (const operation of Object.values(pathItem.additionalOperations ?? {})) {
hoistOperation(operation);
}
for (const [key, operation] of Object.entries(pathItem)) {
if (key !== "query" && key !== "additionalOperations") {
hoistOperation(operation);
}
}
}

for (const pathItem of Object.values(mutableDocument.paths ?? {})) {
visitPathItem(pathItem);
}

return converted;
}
25 changes: 25 additions & 0 deletions packages/openapi3/src/cli/actions/convert/generators/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,28 @@ export function stringLiteral(value: string): string {
// Avoid double-escaping backslashes in the process
return `"${value.replaceAll(/(?:([^\\])"|^")/gi, '$1\\"').replaceAll(/(?:([^\\])\$\{|^\$\{)/gi, "$1\\${")}"`;
}
import type { SupportedOpenAPISchema } from "../../../../types.js";

export function getStringType(schema: SupportedOpenAPISchema): string {
if ("contentEncoding" in schema && schema.contentEncoding === "base64") {
return "bytes";
}

switch (schema.format) {
case "binary":
case "byte":
return "bytes";
case "date":
return "plainDate";
case "date-time":
return "utcDateTime";
case "time":
return "plainTime";
case "duration":
return "duration";
case "uri":
return "url";
default:
return "string";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,17 @@ export function generateDecorators(
decorators: TypeSpecDecorator[],
namesToExclude: string[] = [],
): string[] {
const uniqueDecorators = new Set<string>(
decorators.filter((d) => !namesToExclude.includes(d.name)).map(generateDecorator),
);
return Array.from(uniqueDecorators);
const seen = new Set<string>();
return decorators
.filter((d) => !namesToExclude.includes(d.name))
.flatMap((decorator) => {
const generated = generateDecorator(decorator);
if (decorator.name !== "example" && seen.has(generated)) {
return [];
}
seen.add(generated);
return [generated];
});
}

function isTSValue(value: unknown): value is TSValue {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -381,8 +381,14 @@ export function generateModelProperty(

// Decorators will be a combination of top-level (parameters) and
// schema-level decorators.
const hasExamples = prop.decorators.some((decorator) => decorator.name === "example");
const decorators = generateDecorators(
[...prop.decorators, ...getDecoratorsForSchema(prop.schema)],
[
...prop.decorators,
...getDecoratorsForSchema(prop.schema, context).filter(
(decorator) => decorator.name !== "example" || !hasExamples,
),
],
isModelReferencedAsMultipartRequestBody
? SchemaToExpressionGenerator.decoratorNamesToExcludeForParts
: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,14 @@ function generateResponseExpressions({
// Attempt to emit just the Body or an intersection of Body & MappedResponse
// if there aren't any custom headers.
const bodySchema = content.schema;
const referencedBody =
bodySchema && "$ref" in bodySchema ? context.getSchemaByRef(bodySchema.$ref) : undefined;
// Keep a hoisted literal union as the body; HTTP otherwise treats its variants as responses.
const isLiteralBody = referencedBody?.const !== undefined;
if (bodySchema && mediaType === "application/json" && !headers.length) {
// Scenario 3 - have a mapped status code and body schema is a ref using application/json - intersection!
// Example: CreatedResponse & Widget
if ("$ref" in bodySchema && statusCodeMetadata.httpLibModel) {
if ("$ref" in bodySchema && statusCodeMetadata.httpLibModel && !isLiteralBody) {
return `${statusCodeMetadata.httpLibModel} & ${context.generateTypeFromRefableSchema(
bodySchema,
operationScope,
Expand All @@ -260,7 +264,7 @@ function generateResponseExpressions({
// Example: Body<string>
if (statusCodeMetadata.literalStatusCode === 200) {
const body = context.generateTypeFromRefableSchema(bodySchema, operationScope);
if ("$ref" in bodySchema) {
if ("$ref" in bodySchema && !isLiteralBody) {
return body;
}
return `Body<${body}>`;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
normalizeObjectValueToTSValueExpression,
} from "../utils/decorators.js";
import { getScopeAndName } from "../utils/get-scope-and-name.js";
import { getStringType } from "./common.js";
import { generateDecorators } from "./generate-decorators.js";

export class SchemaToExpressionGenerator {
Expand Down Expand Up @@ -643,41 +644,6 @@ function getNumberType(schema: SupportedOpenAPISchema): string {
}
}

function getStringType(schema: SupportedOpenAPISchema): string {
const format = schema.format ?? "";

// Handle contentEncoding: base64 for OpenAPI 3.1+ (indicates binary data encoded as base64 string)
if ("contentEncoding" in schema && schema.contentEncoding === "base64") {
return "bytes";
}

let type = "string";
switch (format) {
case "binary":
case "byte":
type = "bytes";
break;
case "date":
type = "plainDate";
break;
case "date-time":
// Can be 'offsetDateTime' or 'utcDateTime' - needs FIXME or union?
type = "utcDateTime";
break;
case "time":
type = "plainTime";
break;
case "duration":
type = "duration";
break;
case "uri":
type = "url";
break;
}

return type;
}

function getEnum(schemaEnum: (string | number | boolean | null)[]): string {
return schemaEnum.map((e) => JSON.stringify(e)).join(" | ");
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData
kind: "enum",
...getScopeAndName(name),
directives: getDirectivesForSchema(schema),
decorators: getDecoratorsForSchema(schema, context),
decorators: getDecoratorsForSchema(
schema,
context,
context.getRefName(`#/components/schemas/${name}`, [context.rootNamespace]),
),
doc: schema.description,
schema,
};
Expand Down Expand Up @@ -152,7 +156,12 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData
// Extract description and decorators from meaningful union members
const unionMetadata = extractUnionMetadata(schema);

let decorators = [...getDecoratorsForSchema(schema, context), ...unionMetadata.decorators];
let decorators = [
...getDecoratorsForSchema(schema, context),
...unionMetadata.decorators.filter(
(decorator) => decorator.name !== "example" || !("examples" in schema),
),
Comment thread
baywet marked this conversation as resolved.
Resolved
];

// Check if this is an SSE event schema - if so, replace @oneOf with @events
const schemaRef = `#/components/schemas/${name}`;
Expand All @@ -176,7 +185,7 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData

/**
* Extracts meaningful description and decorators from union members.
* Handles anyOf/oneOf with null, and type arrays like ["string", "null"].
* Handles anyOf/oneOf with null.
*/
function extractUnionMetadata(schema: SupportedOpenAPISchema): {
description?: string;
Expand All @@ -202,19 +211,6 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData
}
}

// Handle type array scenarios like type: ["string", "null"]
if (Array.isArray(schema.type)) {
const nonNullTypes = schema.type.filter((t) => t !== "null");
// If we have exactly one non-null type, this is essentially a nullable version of that type
// The schema itself should contain the relevant constraints/description for the non-null type
if (nonNullTypes.length === 1) {
// Create a schema without the null type to extract decorators for the non-null part
const nonNullSchema = { ...schema, type: nonNullTypes[0] };
return { decorators: getDecoratorsForSchema(nonNullSchema, context) };
// The description should already be on the main schema, so we don't override it here
}
}

return { decorators: [] };
}

Expand All @@ -227,7 +223,11 @@ export function transformComponentSchemas(context: Context, models: TypeSpecData
kind: "scalar",
...getScopeAndName(name),
directives: getDirectivesForSchema(schema),
decorators: getDecoratorsForSchema(schema, context),
decorators: getDecoratorsForSchema(
schema,
context,
context.getRefName(`#/components/schemas/${name}`, [context.rootNamespace]),
),
doc: schema.description,
schema: "$ref" in schema ? {} : schema,
});
Expand Down Expand Up @@ -340,6 +340,9 @@ function unwrapSingleAnyOfOneOf(
...(schema as object),
...member,
description: member.description || schema.description,
...("examples" in schema && schema.examples !== undefined
? { examples: schema.examples }
: {}),
anyOf: undefined,
oneOf: undefined,
};
Expand Down
Loading
Loading