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 Json schema decorator to openapi 3.1 #5386

Closed
Closed
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
4 changes: 4 additions & 0 deletions packages/openapi3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@
"peerDependenciesMeta": {
"@typespec/xml": {
"optional": true
},
"@typespec/json-schema": {
"optional": true
}
},
"devDependencies": {
Expand All @@ -84,6 +87,7 @@
"@typespec/tspd": "workspace:~",
"@typespec/versioning": "workspace:~",
"@typespec/xml": "workspace:~",
"@typespec/json-schema": "workspace:~",
"@vitest/coverage-v8": "^2.1.5",
"@vitest/ui": "^2.1.2",
"c8": "^10.1.2",
Expand Down
31 changes: 31 additions & 0 deletions packages/openapi3/src/json-schema-module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Program, Type } from "@typespec/compiler";
import { CommonOpenAPI3Schema } from "./types.js";

export interface JsonSchemaModule {
attachJsonSchemaObject(
applyConstraint: (fn: (p: Program, t: Type) => any, key: keyof CommonOpenAPI3Schema) => void,
): void;
}

export async function resolveJsonSchemaModule(): Promise<JsonSchemaModule | undefined> {
const jsonSchema = await tryImportJsonSchema();
if (jsonSchema === undefined) return undefined;

return {
attachJsonSchemaObject: (applyConstraint: any) => {
applyConstraint(jsonSchema.getContentEncoding, "contentEncoding");
applyConstraint(jsonSchema.getContentMediaType, "contentMediaType");
},
};

async function tryImportJsonSchema(): Promise<
typeof import("@typespec/json-schema") | undefined
> {
try {
const module = await import("@typespec/json-schema");
return module;
} catch {
return undefined;
}
}
}
2 changes: 2 additions & 0 deletions 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-module.js";
import { OpenAPI3EmitterOptions, OpenAPIVersion } from "./lib.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { createSchemaEmitter3_0 } from "./schema-emitter-3-0.js";
Expand All @@ -17,6 +18,7 @@ export type CreateSchemaEmitter = (props: {
visibilityUsage: VisibilityUsageTracker;
options: ResolvedOpenAPI3EmitterOptions;
xmlModule: XmlModule | undefined;
jsonSchemaModule: JsonSchemaModule | undefined;
}) => AssetEmitter<OpenAPI3Schema | OpenAPISchema3_1, OpenAPI3EmitterOptions>;

export interface OpenApiSpecSpecificProps {
Expand Down
13 changes: 12 additions & 1 deletion 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-module.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 @@ -312,6 +313,7 @@ function createOAPIEmitter(
allHttpAuthentications: HttpAuth[],
defaultAuth: AuthenticationReference,
xmlModule: XmlModule | undefined,
jsonSchemaModule: JsonSchemaModule | undefined,
version?: string,
) {
diagnostics = createDiagnosticCollector();
Expand All @@ -334,6 +336,7 @@ function createOAPIEmitter(
visibilityUsage,
options,
xmlModule,
jsonSchemaModule,
});

const securitySchemes = getOpenAPISecuritySchemes(allHttpAuthentications);
Expand Down Expand Up @@ -638,7 +641,15 @@ 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
2 changes: 1 addition & 1 deletion packages/openapi3/src/schema-emitter-3-0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ function createWrappedSchemaEmitterClass(
): 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, xmlModule, undefined);
}
};
}
Expand Down
15 changes: 13 additions & 2 deletions packages/openapi3/src/schema-emitter-3-1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ import {
import { MetadataInfo } from "@typespec/http";
import { shouldInline } from "@typespec/openapi";
import { getOneOf } from "./decorators.js";
import { JsonSchemaModule } from "./json-schema-module.js";
import { OpenAPI3EmitterOptions, reportDiagnostic } from "./lib.js";
import { CreateSchemaEmitter } from "./openapi-spec-mappings.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { Builders, OpenAPI3SchemaEmitterBase } from "./schema-emitter.js";
import { JsonType, OpenAPISchema3_1 } from "./types.js";
import { CommonOpenAPI3Schema, JsonType, OpenAPISchema3_1 } from "./types.js";
import { isBytesKeptRaw, isLiteralType, literalType } from "./util.js";
import { VisibilityUsageTracker } from "./visibility-usage.js";
import { XmlModule } from "./xml-module.js";
Expand All @@ -40,10 +41,11 @@ function createWrappedSchemaEmitterClass(
visibilityUsage: VisibilityUsageTracker,
options: ResolvedOpenAPI3EmitterOptions,
xmlModule: XmlModule | undefined,
jsonSchemaModule: JsonSchemaModule | undefined,
): 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, xmlModule, jsonSchemaModule);
}
};
}
Expand All @@ -56,6 +58,7 @@ export const createSchemaEmitter3_1: CreateSchemaEmitter = ({ program, context,
rest.visibilityUsage,
rest.options,
rest.xmlModule,
rest.jsonSchemaModule,
),
context,
);
Expand Down Expand Up @@ -254,4 +257,12 @@ export class OpenAPI31SchemaEmitter extends OpenAPI3SchemaEmitterBase<OpenAPISch
}
return values;
}

applyJsonSchemaConstraints(
applyConstraint: (fn: (p: Program, t: Type) => any, key: keyof CommonOpenAPI3Schema) => void,
) {
if (this._jsonSchemaModule) {
this._jsonSchemaModule.attachJsonSchemaObject(applyConstraint);
}
}
}
9 changes: 9 additions & 0 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-module.js";
import { OpenAPI3EmitterOptions, reportDiagnostic } from "./lib.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { getSchemaForStdScalars } from "./std-scalar-schemas.js";
Expand All @@ -89,18 +90,21 @@ export class OpenAPI3SchemaEmitterBase<
protected _visibilityUsage: VisibilityUsageTracker;
protected _options: ResolvedOpenAPI3EmitterOptions;
protected _xmlModule: XmlModule | undefined;
protected _jsonSchemaModule: JsonSchemaModule | undefined;
constructor(
emitter: AssetEmitter<Record<string, any>, OpenAPI3EmitterOptions>,
metadataInfo: MetadataInfo,
visibilityUsage: VisibilityUsageTracker,
options: ResolvedOpenAPI3EmitterOptions,
xmlModule: XmlModule | undefined,
jsonSchemaModule: JsonSchemaModule | undefined,
) {
super(emitter);
this._metadataInfo = metadataInfo;
this._visibilityUsage = visibilityUsage;
this._options = options;
this._xmlModule = xmlModule;
this._jsonSchemaModule = jsonSchemaModule;
}

modelDeclarationReferenceContext(model: Model, name: string): Context {
Expand Down Expand Up @@ -606,6 +610,10 @@ export class OpenAPI3SchemaEmitterBase<
refSchema?: Schema,
) {}

applyJsonSchemaConstraints(
applyConstraint: (fn: (p: Program, t: Type) => any, key: keyof CommonOpenAPI3Schema) => void,
) {}

applyConstraints(
type: Scalar | Model | ModelProperty | Union | Enum,
original: Schema,
Expand All @@ -628,6 +636,7 @@ export class OpenAPI3SchemaEmitterBase<
applyConstraint(getPattern, "pattern");
applyConstraint(getMinItems, "minItems");
applyConstraint(getMaxItems, "maxItems");
this.applyJsonSchemaConstraints(applyConstraint);

if (isSecret(program, type)) {
schema.format = "password";
Expand Down
18 changes: 17 additions & 1 deletion packages/openapi3/test/scalar-constraints.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,17 @@ worksFor(["3.1.0"], ({ oapiForModel }) => {
strictEqual(schema.maxLength, 2);
strictEqual(schema.pattern, "a|b");
strictEqual(schema.format, "ipv4");
strictEqual(schema.contentEncoding, "base64url");
strictEqual(schema.contentMediaType, "application/jwt");
}

const decorators = `
@minLength(1)
@maxLength(2)
@pattern("a|b")
@format("ipv4")`;
@format("ipv4")
@JsonSchema.contentEncoding("base64url")
@JsonSchema.contentMediaType("application/jwt")`;

it("on scalar declaration", async () => {
const schemas = await oapiForModel(
Expand All @@ -250,5 +254,17 @@ worksFor(["3.1.0"], ({ oapiForModel }) => {

assertStringConstraints(schemas.schemas.Test);
});

it("on property", async () => {
const schemas = await oapiForModel(
"Test",
`model Test {
${decorators}
prop: string;
}`,
);

assertStringConstraints(schemas.schemas.Test.properties.prop);
});
});
});
4 changes: 3 additions & 1 deletion packages/openapi3/test/test-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
resolveVirtualPath,
} from "@typespec/compiler/testing";
import { HttpTestLibrary } from "@typespec/http/testing";
import { JsonSchemaTestLibrary } from "@typespec/json-schema/testing";
import { OpenAPITestLibrary } from "@typespec/openapi/testing";
import { RestTestLibrary } from "@typespec/rest/testing";
import { VersioningTestLibrary } from "@typespec/versioning/testing";
Expand All @@ -22,6 +23,7 @@ export async function createOpenAPITestHost() {
RestTestLibrary,
VersioningTestLibrary,
XmlTestLibrary,
JsonSchemaTestLibrary,
OpenAPITestLibrary,
OpenAPI3TestLibrary,
],
Expand Down Expand Up @@ -94,7 +96,7 @@ export async function openApiFor(
const outPath = resolveVirtualPath("{version}.openapi.json");
host.addTypeSpecFile(
"./main.tsp",
`import "@typespec/http"; import "@typespec/rest"; import "@typespec/openapi"; import "@typespec/openapi3";import "@typespec/xml"; ${
`import "@typespec/http"; import "@typespec/rest"; import "@typespec/openapi"; import "@typespec/openapi3";import "@typespec/xml";import "@typespec/json-schema"; ${
versions ? `import "@typespec/versioning"; using TypeSpec.Versioning;` : ""
}using TypeSpec.Rest;using TypeSpec.Http;using TypeSpec.OpenAPI;using TypeSpec.Xml;${code}`,
);
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.