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

Updating OpenAPI3 emitter to sort response header in Lexicographic order #3015

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


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

Update OpenAPI3 emitter to emit response headers in lexicographic order
21 changes: 21 additions & 0 deletions packages/openapi3/.scripts/schema-json-to-js.js
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wondering if we should not making this a reusable package as we need this for 3 packages now

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// @ts-check

import { readFile, writeFile } from "fs/promises";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));

const jsonFilename = resolve(__dirname, "../schema/dist/schema.json");
const jsFilename = resolve(__dirname, "../schema/dist/schema.js");
console.log("Reading json schema at:", jsonFilename);
const content = await readFile(jsonFilename);

const json = JSON.parse(content.toString());

const jsContent = `
const schema = ${JSON.stringify(json)};
export default schema;
`;
console.log("Writing json schema in js file:", jsonFilename);
await writeFile(jsFilename, jsContent);
6 changes: 4 additions & 2 deletions packages/openapi3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
},
"scripts": {
"clean": "rimraf ./dist ./temp",
"build": "tsc -p . && npm run lint-typespec-library",
"build": "npm run regen-openapi-schema && tsc -p . && npm run lint-typespec-library",
"watch": "tsc -p . --watch",
"lint-typespec-library": "tsp compile . --warn-as-error --import @typespec/library-linter --no-emit",
"test": "vitest run",
Expand All @@ -43,7 +43,8 @@
"test-official": "vitest run --coverage --reporter=junit --reporter=default --no-file-parallelism",
"lint": "eslint . --ext .ts --max-warnings=0",
"lint:fix": "eslint . --fix --ext .ts",
"regen-docs": "tspd doc . --enable-experimental --output-dir ../../docs/libraries/openapi3/reference"
"regen-docs": "tspd doc . --enable-experimental --output-dir ../../docs/libraries/openapi3/reference",
"regen-openapi-schema": "tsp compile ./schema/openapi-schema-3.0.tsp --warn-as-error && node ./.scripts/schema-json-to-js.js"
},
"files": [
"lib/*.tsp",
Expand All @@ -65,6 +66,7 @@
"@typespec/eslint-config-typespec": "workspace:~",
"@typespec/eslint-plugin": "workspace:~",
"@typespec/http": "workspace:~",
"@typespec/json-schema": "workspace:~",
"@typespec/library-linter": "workspace:~",
"@typespec/openapi": "workspace:~",
"@typespec/rest": "workspace:~",
Expand Down
1 change: 1 addition & 0 deletions packages/openapi3/schema/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
out/
235 changes: 235 additions & 0 deletions packages/openapi3/schema/openapi-schema-3.0.tsp
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
/**
* This document is used to specify the order of properties in the output Open API.
* The order defined in the TypeSpec will be respected in the generated swagger.
*/
import "@typespec/json-schema";
import "@typespec/http";

using TypeSpec.Http;
using TypeSpec.JsonSchema;

namespace OpenAPISchema;

/** https://spec.openapis.org/oas/v3.0.3#openapi-object */
@jsonSchema
model OpenAPI_3_0_Schema {
openapi: "3.0.0";

/**
* https://spec.openapis.org/oas/v3.0.3#info-object
*/
info: Info;

/** https://spec.openapis.org/oas/v3.0.3#server-object */
servers?: Server[];

/** https://spec.openapis.org/oas/v3.0.3#paths-object */
paths: Record<PathItem>;

/** https://spec.openapis.org/oas/v3.0.3#components-object */
components?: Components;

/** https://spec.openapis.org/oas/v3.0.3#security-requirement-object */
security?: Record<string[]>[];

/** https://spec.openapis.org/oas/v3.0.3#tag-object */
tags: Tag[];
}

// ===== Shared
model Reference {
$ref: string;
}

alias Refable<T> = Reference | T;

// ===== Info model
model Info {
title: string;
description?: string;
termsOfService?: string;
contact?: Contact;
license?: License;
version: string;
}

model Contact {
name?: string;
url?: string;
email?: string;
}

model License {
name: string;
url?: string;
}

// ===== Server model
model Server {
url: string;
description?: string;
variables?: Record<ServerVariable>;
}

model ServerVariable {
`enum`?: string[];
default: string;
description?: string;
}

// ===== Paths model
model PathItem {
$ref?: string;
summary?: string;
description?: string;
get?: Operation;
put?: Operation;
post?: Operation;
patch?: Operation;
delete?: Operation;
options?: Operation;
head?: Operation;
trace?: Operation;
servers?: Server[];
parameters?: Refable<Parameter[]>;
}

model Operation {
tags?: string[];
summary?: string;
description?: string;
externalDocs?: ExternalDocs;
operationId?: string;
parameters?: Parameter[];
requestBody?: Refable<RequestBody>;
responses: Record<Response>;

/** Not implemented */
callbacks?: unknown;

deprecated?: boolean;
security?: Record<string[]>[];
servers: Server[];
}

model RequestBody {
description?: string;
content: Record<MediaType>;
required?: boolean;
}

model MediaType {
schema?: Refable<Schema>;
example?: unknown;
examples?: Record<Refable<Example>>;
encoding?: Record<Encoding>;
}

model Example {
summary?: string;
description?: string;
value?: unknown;
externalValue?: string;
}

model Encoding {
contentType?: string;
headers?: Record<Refable<Header>>;
style?: string;
explode?: boolean;
allowReserved?: boolean;
}

model Link {
operationRef?: string;
operationId?: string;
parameters?: Record<unknown>;
requestBody?: Record<unknown>;
description?: string;
server?: Server;
}

model Header {
in: "header";
description?: string;
required?: boolean;
deprecated?: boolean;
allowEmptyValue?: boolean;
}

model Schema {}

union StatusCode {
string,
"1XX",
"2XX",
"3XX",
"4XX",
"5XX",
"default",
}

model Response {
description: string;
headers?: Record<Refable<Header>>;
content?: Record<MediaType>;
links?: Record<Refable<Link>>;
}

model Parameter {
name: string;
in: "query" | "header" | "path" | "cookie";
description?: string;
required?: boolean;
deprecated?: boolean;
allowEmptyValue?: boolean;
}

model ExternalDocs {
description?: string;
url: string;
}

// ===== Components
model Components {
schemas?: Record<Schema>;
headers?: Record<Header>;
responses?: Record<Response>;
parameters?: Record<Parameter>;
examples?: Record<Example>;
requestBodies?: Record<RequestBody>;
securitySchemes?: Record<SecurityScheme>;
links?: Record<Link>;
}

model SecurityScheme {
type: string;
description?: string;
name: string;
in: string;
scheme: string;
bearerFormat?: string;
flows: OAuthFlows;
openIdConnectUrl: string;
}

model OAuthFlows {
implicit: OAuthFlow;
password: OAuthFlow;
clientCredentials: OAuthFlow;
authorizationCode: OAuthFlow;
}

model OAuthFlow {
authorizationUrl: string;
tokenUrl: string;
refreshUrl?: string;
scopes: Record<string>;
}

// ===== Tag
model Tag {
name: string;
description?: string;
externalDocs?: ExternalDocs;
}
8 changes: 8 additions & 0 deletions packages/openapi3/schema/tspconfig.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
emit:
- "@typespec/json-schema"

options:
"@typespec/json-schema":
emitter-output-dir: "{project-root}/dist"
file-type: json
bundleId: schema.json
40 changes: 40 additions & 0 deletions packages/openapi3/test/response-headers-order.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { strictEqual } from "assert";
import { describe, it } from "vitest";
import { openApiFor } from "./test-host.js";

describe("openapi3: response headers order", () => {
const headerDefinitions = `
model A_Header { @header a : string };
model B_Header { @header b : string };
model C_Header { @header c : string };
`;
it("header already in lexical order", async () => {
const res = await openApiFor(
`
${headerDefinitions}
model Headers { ...A_Header, ...B_Header, ...C_Header };

op read(): {@statusCode _: 200, content: string, headers: Headers};
`
);
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers).length, 3);
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers)[0], "a");
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers)[1], "b");
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers)[2], "c");
});

it("header not in lexical order", async () => {
const res = await openApiFor(
`
${headerDefinitions}
model Headers { ...C_Header, ...A_Header, ...B_Header };

op read(): {@statusCode _: 200, content: string, headers: Headers};
`
);
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers).length, 3);
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers)[0], "a");
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers)[1], "b");
strictEqual(Object.keys(res.paths["/"].get.responses["200"].headers)[2], "c");
});
});
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.