Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for json-schema decorators in open api emitter #5407

Open
wants to merge 3 commits into
base: feature/openapi3.1
Choose a base branch
from
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,7 @@
---
changeKind: feature
packages:
- "@typespec/openapi3"
---

Adds support for @typespec/json-schema decorators with Open API 3.0 and 3.1 emitters.
5 changes: 5 additions & 0 deletions packages/openapi3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,14 @@
"peerDependencies": {
"@typespec/compiler": "workspace:~",
"@typespec/http": "workspace:~",
"@typespec/json-schema": "workspace:~",
"@typespec/openapi": "workspace:~",
"@typespec/versioning": "workspace:~"
},
"peerDependenciesMeta": {
"@typespec/json-schema": {
"optional": true
},
"@typespec/xml": {
"optional": true
}
Expand All @@ -78,6 +82,7 @@
"@types/yargs": "~17.0.33",
"@typespec/compiler": "workspace:~",
"@typespec/http": "workspace:~",
"@typespec/json-schema": "workspace:~",
"@typespec/library-linter": "workspace:~",
"@typespec/openapi": "workspace:~",
"@typespec/rest": "workspace:~",
Expand Down
9 changes: 9 additions & 0 deletions packages/openapi3/src/json-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export type JsonSchemaModule = typeof import("@typespec/json-schema");

export async function resolveJsonSchemaModule(): Promise<JsonSchemaModule | undefined> {
try {
return await import("@typespec/json-schema");
} catch {
return undefined;
}
}
3 changes: 2 additions & 1 deletion packages/openapi3/src/openapi-spec-mappings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { EmitContext, Namespace, Program } from "@typespec/compiler";
import { AssetEmitter } from "@typespec/compiler/emitter-framework";
import { MetadataInfo } from "@typespec/http";
import { getExternalDocs, resolveInfo } from "@typespec/openapi";
import { JsonSchemaModule } from "./json-schema.js";
import { OpenAPI3EmitterOptions, OpenAPIVersion } from "./lib.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { createSchemaEmitter3_0 } from "./schema-emitter-3-0.js";
Expand All @@ -16,7 +17,7 @@ export type CreateSchemaEmitter = (props: {
metadataInfo: MetadataInfo;
visibilityUsage: VisibilityUsageTracker;
options: ResolvedOpenAPI3EmitterOptions;
xmlModule: XmlModule | undefined;
optionalDependencies: { jsonSchemaModule?: JsonSchemaModule; xmlModule?: XmlModule };
}) => AssetEmitter<OpenAPI3Schema | OpenAPISchema3_1, OpenAPI3EmitterOptions>;

export interface OpenApiSpecSpecificProps {
Expand Down
14 changes: 11 additions & 3 deletions packages/openapi3/src/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ import { stringify } from "yaml";
import { getRef } from "./decorators.js";
import { applyEncoding } from "./encoding.js";
import { getExampleOrExamples, OperationExamples, resolveOperationExamples } from "./examples.js";
import { JsonSchemaModule, resolveJsonSchemaModule } from "./json-schema.js";
import { createDiagnostic, FileType, OpenAPI3EmitterOptions, OpenAPIVersion } from "./lib.js";
import { getOpenApiSpecProps } from "./openapi-spec-mappings.js";
import { getOpenAPI3StatusCodes } from "./status-codes.js";
Expand Down Expand Up @@ -311,7 +312,7 @@ function createOAPIEmitter(
service: Service,
allHttpAuthentications: HttpAuth[],
defaultAuth: AuthenticationReference,
xmlModule: XmlModule | undefined,
optionalDependencies: { jsonSchemaModule?: JsonSchemaModule; xmlModule?: XmlModule },
version?: string,
) {
diagnostics = createDiagnosticCollector();
Expand All @@ -333,7 +334,7 @@ function createOAPIEmitter(
metadataInfo,
visibilityUsage,
options,
xmlModule,
optionalDependencies,
});

const securitySchemes = getOpenAPISecuritySchemes(allHttpAuthentications);
Expand Down Expand Up @@ -638,7 +639,14 @@ function createOAPIEmitter(
const auth = (serviceAuth = resolveAuthentication(httpService));

const xmlModule = await resolveXmlModule();
initializeEmitter(service, auth.schemes, auth.defaultAuth, xmlModule, version);
const jsonSchemaModule = await resolveJsonSchemaModule();
initializeEmitter(
service,
auth.schemes,
auth.defaultAuth,
{ xmlModule, jsonSchemaModule },
version,
);
reportIfNoRoutes(program, httpService.operations);

for (const op of resolveOperations(httpService.operations)) {
Expand Down
7 changes: 4 additions & 3 deletions packages/openapi3/src/schema-emitter-3-0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
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 { CreateSchemaEmitter } from "./openapi-spec-mappings.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
Expand All @@ -37,11 +38,11 @@ function createWrappedSchemaEmitterClass(
metadataInfo: MetadataInfo,
visibilityUsage: VisibilityUsageTracker,
options: ResolvedOpenAPI3EmitterOptions,
xmlModule: XmlModule | undefined,
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, xmlModule);
super(emitter, metadataInfo, visibilityUsage, options, optionalDependencies);
}
};
}
Expand All @@ -53,7 +54,7 @@ export const createSchemaEmitter3_0: CreateSchemaEmitter = ({ program, context,
rest.metadataInfo,
rest.visibilityUsage,
rest.options,
rest.xmlModule,
rest.optionalDependencies,
),
context,
);
Expand Down
43 changes: 40 additions & 3 deletions packages/openapi3/src/schema-emitter-3-1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
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 { CreateSchemaEmitter } from "./openapi-spec-mappings.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
Expand All @@ -39,11 +40,11 @@ function createWrappedSchemaEmitterClass(
metadataInfo: MetadataInfo,
visibilityUsage: VisibilityUsageTracker,
options: ResolvedOpenAPI3EmitterOptions,
xmlModule: XmlModule | undefined,
optionalDependencies: { jsonSchemaModule?: JsonSchemaModule; xmlModule?: XmlModule },
): typeof TypeEmitter<Record<string, any>, OpenAPI3EmitterOptions> {
return class extends OpenAPI31SchemaEmitter {
constructor(emitter: AssetEmitter<Record<string, any>, OpenAPI3EmitterOptions>) {
super(emitter, metadataInfo, visibilityUsage, options, xmlModule);
super(emitter, metadataInfo, visibilityUsage, options, optionalDependencies);
}
};
}
Expand All @@ -55,7 +56,7 @@ export const createSchemaEmitter3_1: CreateSchemaEmitter = ({ program, context,
rest.metadataInfo,
rest.visibilityUsage,
rest.options,
rest.xmlModule,
rest.optionalDependencies,
),
context,
);
Expand Down Expand Up @@ -84,6 +85,22 @@ export class OpenAPI31SchemaEmitter extends OpenAPI3SchemaEmitterBase<OpenAPISch
target: ObjectBuilder<OpenAPISchema3_1>,
refSchema?: OpenAPISchema3_1,
) {
const applyConstraint = (fn: (p: Program, t: Type) => any, key: keyof OpenAPISchema3_1) => {
const value = fn(program, type);
if (value !== undefined) {
target[key] = value;
}
};

const applyTypeConstraint = (fn: (p: Program, t: Type) => Type | undefined, key: string) => {
const constraintType = fn(this.emitter.getProgram(), type);
if (constraintType) {
const ref = this.emitter.emitTypeReference(constraintType);
compilerAssert(ref.kind === "code", "Unexpected non-code result from emit reference");
target.set(key, ref.value);
}
};

const program = this.emitter.getProgram();

const minValueExclusive = getMinValueExclusive(program, type);
Expand All @@ -98,6 +115,26 @@ export class OpenAPI31SchemaEmitter extends OpenAPI3SchemaEmitterBase<OpenAPISch
target.exclusiveMaximum = maxValueExclusive;
}

// apply json schema decorators
const jsonSchemaModule = this._jsonSchemaModule;
if (jsonSchemaModule) {
applyTypeConstraint(jsonSchemaModule.getContains, "contains");
applyConstraint(jsonSchemaModule.getMinContains, "minContains");
applyConstraint(jsonSchemaModule.getMaxContains, "maxContains");
applyConstraint(jsonSchemaModule.getContentEncoding, "contentEncoding");
applyConstraint(jsonSchemaModule.getContentMediaType, "contentMediaType");
applyTypeConstraint(jsonSchemaModule.getContentSchema, "contentSchema");

const prefixItems = jsonSchemaModule.getPrefixItems(program, type);
if (prefixItems) {
const prefixItemsSchema = new ArrayBuilder<Record<string, unknown>>();
for (const item of prefixItems.values) {
prefixItemsSchema.push(this.emitter.emitTypeReference(item));
}
target.set("prefixItems", prefixItemsSchema as any);
}
}

this.#applySchemaExamples(program, type, target);
}

Expand Down
17 changes: 15 additions & 2 deletions packages/openapi3/src/schema-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
import { attachExtensions } from "./attach-extensions.js";
import { getOneOf, getRef } from "./decorators.js";
import { applyEncoding } from "./encoding.js";
import { JsonSchemaModule } from "./json-schema.js";
import { OpenAPI3EmitterOptions, reportDiagnostic } from "./lib.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { getSchemaForStdScalars } from "./std-scalar-schemas.js";
Expand All @@ -88,19 +89,22 @@ export class OpenAPI3SchemaEmitterBase<
protected _metadataInfo: MetadataInfo;
protected _visibilityUsage: VisibilityUsageTracker;
protected _options: ResolvedOpenAPI3EmitterOptions;
protected _jsonSchemaModule: JsonSchemaModule | undefined;
protected _xmlModule: XmlModule | undefined;

constructor(
emitter: AssetEmitter<Record<string, any>, OpenAPI3EmitterOptions>,
metadataInfo: MetadataInfo,
visibilityUsage: VisibilityUsageTracker,
options: ResolvedOpenAPI3EmitterOptions,
xmlModule: XmlModule | undefined,
optionalDependencies: { jsonSchemaModule?: JsonSchemaModule; xmlModule?: XmlModule },
) {
super(emitter);
this._metadataInfo = metadataInfo;
this._visibilityUsage = visibilityUsage;
this._options = options;
this._xmlModule = xmlModule;
this._jsonSchemaModule = optionalDependencies.jsonSchemaModule;
this._xmlModule = optionalDependencies.xmlModule;
}

modelDeclarationReferenceContext(model: Model, name: string): Context {
Expand Down Expand Up @@ -629,6 +633,15 @@ export class OpenAPI3SchemaEmitterBase<
applyConstraint(getMinItems, "minItems");
applyConstraint(getMaxItems, "maxItems");

// apply json schema decorators
const jsonSchemaModule = this._jsonSchemaModule;
if (jsonSchemaModule) {
applyConstraint(jsonSchemaModule.getMultipleOf, "multipleOf");
applyConstraint(jsonSchemaModule.getUniqueItems, "uniqueItems");
applyConstraint(jsonSchemaModule.getMinProperties, "minProperties");
applyConstraint(jsonSchemaModule.getMaxProperties, "maxProperties");
}

if (isSecret(program, type)) {
schema.format = "password";
}
Expand Down
27 changes: 27 additions & 0 deletions packages/openapi3/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,33 @@ export type JsonSchema<AdditionalVocabularies extends {} = {}> = AdditionalVocab
*/
required?: Array<string>;

/**
* Must be a string.
* If the schema instance is a string, this property defines that the string SHOULD be
* interpreted as encoded binary data and decoded using the encoding named by this property.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-contentencoding
*/
contentEncoding?: string;

/**
* If the schema instance is a string and "contentMediaType" is present, this property
* contains a schema which describes the structure of the string.
* This should be ignored if "contentMediaType" is not present.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-contentschema
*/
contentSchema?: Refable<JsonSchema<AdditionalVocabularies>>;

/**
* Must be a string.
* If the schema instance is a string, this property indicates the media type of the contents of the string.
* If "contentEncoding" is present, this property describes the decoded string.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-contentmediatype
*/
contentMediaType?: string;

/**
* This attribute is a string that provides a short description of the instance property.
*
Expand Down
Loading