From 7ed460c67b319156c27832f35df2a5af2748c3fb Mon Sep 17 00:00:00 2001 From: Romain Lenzotti Date: Sat, 10 Oct 2020 11:50:10 +0200 Subject: [PATCH 1/5] feat(core): Add HashOf and improve deepExtends interface --- packages/core/src/interfaces/HashOf.ts | 1 + packages/core/src/interfaces/index.ts | 1 + packages/core/src/utils/deepExtends.ts | 9 ++++++--- 3 files changed, 8 insertions(+), 3 deletions(-) create mode 100644 packages/core/src/interfaces/HashOf.ts diff --git a/packages/core/src/interfaces/HashOf.ts b/packages/core/src/interfaces/HashOf.ts new file mode 100644 index 00000000000..1955996fdae --- /dev/null +++ b/packages/core/src/interfaces/HashOf.ts @@ -0,0 +1 @@ +export type HashOf = {[key: string]: T}; diff --git a/packages/core/src/interfaces/index.ts b/packages/core/src/interfaces/index.ts index 12bcc4ddd00..be72a8aa3cf 100644 --- a/packages/core/src/interfaces/index.ts +++ b/packages/core/src/interfaces/index.ts @@ -3,3 +3,4 @@ export * from "./Env"; export * from "./DecoratorParameters"; export * from "./MetadataTypes"; export * from "./ValueOf"; +export * from "./HashOf"; diff --git a/packages/core/src/utils/deepExtends.ts b/packages/core/src/utils/deepExtends.ts index 8ea34fd4065..f24c002e76f 100644 --- a/packages/core/src/utils/deepExtends.ts +++ b/packages/core/src/utils/deepExtends.ts @@ -1,13 +1,16 @@ +import {HashOf} from "../interfaces/HashOf"; import {classOf, isArrayOrArrayClass, isPrimitive, isPrimitiveOrPrimitiveClass} from "./ObjectUtils"; +export type DeepExtendsReducers = HashOf<(collection: any[], value: any) => any>; + /** - * + * Deep extends a model with another one. * @param out * @param obj - * @param {{[p: string]: (collection: any[], value: any) => any}} reducers + * @param reducers * @returns {any} */ -export function deepExtends(out: any, obj: any, reducers: {[key: string]: (collection: any[], value: any) => any} = {}): any { +export function deepExtends(out: any, obj: any, reducers: DeepExtendsReducers = {}): any { if (obj === undefined || obj === null) { return out; } From 59def1ddf2985c0bc5f4509d4deaad8a6606402f Mon Sep 17 00:00:00 2001 From: Romain Lenzotti Date: Thu, 8 Oct 2020 20:45:17 +0200 Subject: [PATCH 2/5] feat(openspec): Add @tsed/openspec package --- packages/openspec/.npmignore | 4 + packages/openspec/package.json | 24 + packages/openspec/readme.md | 60 + .../src/common/OpenSpecExternalDocs.ts | 10 + packages/openspec/src/common/OpenSpecHash.ts | 1 + packages/openspec/src/common/OpenSpecInfo.ts | 52 + .../openspec/src/common/OpenSpecJsonSchema.ts | 153 + packages/openspec/src/common/OpenSpecPath.ts | 10 + packages/openspec/src/common/OpenSpecRef.ts | 3 + .../openspec/src/common/OpenSpecSecurity.ts | 3 + packages/openspec/src/common/OpenSpecTag.ts | 7 + packages/openspec/src/common/OpenSpecTypes.ts | 1 + .../openspec/src/common/OpenSpecVersions.ts | 3 + packages/openspec/src/common/OpenSpecXML.ts | 22 + packages/openspec/src/common/index.ts | 11 + packages/openspec/src/index.ts | 3 + packages/openspec/src/openspec2/OS2Header.ts | 8 + .../openspec/src/openspec2/OS2Operation.ts | 65 + .../openspec/src/openspec2/OS2Parameter.ts | 66 + packages/openspec/src/openspec2/OS2Paths.ts | 8 + .../openspec/src/openspec2/OS2Response.ts | 22 + packages/openspec/src/openspec2/OS2Schema.ts | 39 + .../openspec/src/openspec2/OS2Security.ts | 58 + packages/openspec/src/openspec2/OpenSpec2.ts | 72 + packages/openspec/src/openspec2/index.ts | 8 + .../openspec/src/openspec3/OS3Callbacks.ts | 5 + .../openspec/src/openspec3/OS3Components.ts | 49 + .../openspec/src/openspec3/OS3Encoding.ts | 25 + packages/openspec/src/openspec3/OS3Example.ts | 19 + packages/openspec/src/openspec3/OS3Flows.ts | 49 + packages/openspec/src/openspec3/OS3Header.ts | 17 + packages/openspec/src/openspec3/OS3Link.ts | 25 + .../openspec/src/openspec3/OS3MediaType.ts | 24 + .../openspec/src/openspec3/OS3Operation.ts | 70 + .../openspec/src/openspec3/OS3Parameter.ts | 80 + packages/openspec/src/openspec3/OS3Paths.ts | 28 + .../openspec/src/openspec3/OS3RequestBody.ts | 18 + .../openspec/src/openspec3/OS3Response.ts | 25 + packages/openspec/src/openspec3/OS3Schema.ts | 49 + .../openspec/src/openspec3/OS3Security.ts | 60 + packages/openspec/src/openspec3/OS3Server.ts | 31 + packages/openspec/src/openspec3/OpenSpec3.ts | 44 + packages/openspec/src/openspec3/index.ts | 16 + packages/openspec/tsconfig.compile.json | 13 + packages/schema/package.json | 1 + .../schema/src/decorators/operations/tags.ts | 6 +- packages/schema/src/domain/JsonOperation.ts | 25 +- packages/schema/src/domain/JsonParameter.ts | 13 +- packages/schema/src/domain/JsonRequestBody.ts | 12 +- packages/schema/src/domain/JsonResponse.ts | 16 +- packages/schema/src/domain/JsonSchema.ts | 20 +- .../schema/src/interfaces/JsonOpenSpec.ts | 66 +- reports/eslint/test-results-eslint.xml | 2832 +++++++++ reports/mocha/test-results-unit.xml | 5221 +++++++++++++++++ 54 files changed, 9453 insertions(+), 119 deletions(-) create mode 100644 packages/openspec/.npmignore create mode 100644 packages/openspec/package.json create mode 100644 packages/openspec/readme.md create mode 100644 packages/openspec/src/common/OpenSpecExternalDocs.ts create mode 100644 packages/openspec/src/common/OpenSpecHash.ts create mode 100644 packages/openspec/src/common/OpenSpecInfo.ts create mode 100644 packages/openspec/src/common/OpenSpecJsonSchema.ts create mode 100644 packages/openspec/src/common/OpenSpecPath.ts create mode 100644 packages/openspec/src/common/OpenSpecRef.ts create mode 100644 packages/openspec/src/common/OpenSpecSecurity.ts create mode 100644 packages/openspec/src/common/OpenSpecTag.ts create mode 100644 packages/openspec/src/common/OpenSpecTypes.ts create mode 100644 packages/openspec/src/common/OpenSpecVersions.ts create mode 100644 packages/openspec/src/common/OpenSpecXML.ts create mode 100644 packages/openspec/src/common/index.ts create mode 100644 packages/openspec/src/index.ts create mode 100644 packages/openspec/src/openspec2/OS2Header.ts create mode 100644 packages/openspec/src/openspec2/OS2Operation.ts create mode 100644 packages/openspec/src/openspec2/OS2Parameter.ts create mode 100644 packages/openspec/src/openspec2/OS2Paths.ts create mode 100644 packages/openspec/src/openspec2/OS2Response.ts create mode 100644 packages/openspec/src/openspec2/OS2Schema.ts create mode 100644 packages/openspec/src/openspec2/OS2Security.ts create mode 100644 packages/openspec/src/openspec2/OpenSpec2.ts create mode 100644 packages/openspec/src/openspec2/index.ts create mode 100644 packages/openspec/src/openspec3/OS3Callbacks.ts create mode 100644 packages/openspec/src/openspec3/OS3Components.ts create mode 100644 packages/openspec/src/openspec3/OS3Encoding.ts create mode 100644 packages/openspec/src/openspec3/OS3Example.ts create mode 100644 packages/openspec/src/openspec3/OS3Flows.ts create mode 100644 packages/openspec/src/openspec3/OS3Header.ts create mode 100644 packages/openspec/src/openspec3/OS3Link.ts create mode 100644 packages/openspec/src/openspec3/OS3MediaType.ts create mode 100644 packages/openspec/src/openspec3/OS3Operation.ts create mode 100644 packages/openspec/src/openspec3/OS3Parameter.ts create mode 100644 packages/openspec/src/openspec3/OS3Paths.ts create mode 100644 packages/openspec/src/openspec3/OS3RequestBody.ts create mode 100644 packages/openspec/src/openspec3/OS3Response.ts create mode 100644 packages/openspec/src/openspec3/OS3Schema.ts create mode 100644 packages/openspec/src/openspec3/OS3Security.ts create mode 100644 packages/openspec/src/openspec3/OS3Server.ts create mode 100644 packages/openspec/src/openspec3/OpenSpec3.ts create mode 100644 packages/openspec/src/openspec3/index.ts create mode 100644 packages/openspec/tsconfig.compile.json create mode 100644 reports/eslint/test-results-eslint.xml create mode 100644 reports/mocha/test-results-unit.xml diff --git a/packages/openspec/.npmignore b/packages/openspec/.npmignore new file mode 100644 index 00000000000..7f50c0fb80c --- /dev/null +++ b/packages/openspec/.npmignore @@ -0,0 +1,4 @@ +src +test +tsconfig.compile.json +tsconfig.json diff --git a/packages/openspec/package.json b/packages/openspec/package.json new file mode 100644 index 00000000000..9486a50324c --- /dev/null +++ b/packages/openspec/package.json @@ -0,0 +1,24 @@ +{ + "name": "@tsed/openspec", + "version": "6.0.0-beta.13", + "description": "OpenSpec2 and OpenSpec3 interfaces declarations for TypeScript application", + "main": "./lib/index.js", + "typings": "./lib/index.d.ts", + "keywords": [ + "TypeScript", + "interfaces", + "OpenSpec", + "open-spec", + "swagger", + "OAS3", + "OAS2", + "JsonSchema" + ], + "dependencies": {}, + "scripts": { + "build": "tsc --build tsconfig.compile.json" + }, + "private": false, + "devDependencies": {}, + "peerDependencies": {} +} \ No newline at end of file diff --git a/packages/openspec/readme.md b/packages/openspec/readme.md new file mode 100644 index 00000000000..9699490dce1 --- /dev/null +++ b/packages/openspec/readme.md @@ -0,0 +1,60 @@ +# @tsed/openspec + +[![Build Status](https://travis-ci.org/TypedProject/tsed.svg?branch=master)](https://travis-ci.org/TypedProject/tsed) +[![Coverage Status](https://coveralls.io/repos/github/TypedProject/tsed/badge.svg?branch=production)](https://coveralls.io/github/TypedProject/tsed?branch=production) +[![Known Vulnerabilities](https://snyk.io/test/github/TypedProject/tsed/badge.svg)](https://snyk.io/test/github/TypedProject/tsed) +[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) +[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) +[![backers](https://opencollective.com/tsed/tiers/badge.svg)](https://opencollective.com/tsed) + +> A package of Ts.ED framework. See website: https://tsed.io/ + +OpenSpec2 and OpenSpec3 interfaces declarations for TypeScript application. + +## Documentation + +Documentation is available on [https://tsed.io](https://tsed.io/tutorials/swagger.html) + +## Installation + +You can get the latest release and the type definitions using npm: + +```bash +npm install --save @tsed/openspec +``` + +## Usage + +```typescript +import {OpenSpec3, OpenSpec2} from "@tsed/openspec"; + +const spec3: OpenSpec3 = { openapi: '3.0.1', paths: {}}; +const spec2: OpenSpec2 = { swagger: '2.0', paths: {}}; +``` + +## Contributors +Please read [contributing guidelines here](https://tsed.io/CONTRIBUTING.html) + + + +## Backers + +Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/tsed#backer)] + + + +## Sponsors + +Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/tsed#sponsor)] + +## License + +The MIT License (MIT) + +Copyright (c) 2016 - 2018 Romain Lenzotti + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/openspec/src/common/OpenSpecExternalDocs.ts b/packages/openspec/src/common/OpenSpecExternalDocs.ts new file mode 100644 index 00000000000..870f2e33598 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecExternalDocs.ts @@ -0,0 +1,10 @@ +export interface OpenSpecExternalDocs { + /** + * The URL for the target documentation. Value MUST be in the format of a URL. + */ + url: string; + /** + * A short description of the target documentation. [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. + */ + description?: string; +} diff --git a/packages/openspec/src/common/OpenSpecHash.ts b/packages/openspec/src/common/OpenSpecHash.ts new file mode 100644 index 00000000000..270c4ead348 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecHash.ts @@ -0,0 +1 @@ +export type OpenSpecHash = {[key: string]: T}; diff --git a/packages/openspec/src/common/OpenSpecInfo.ts b/packages/openspec/src/common/OpenSpecInfo.ts new file mode 100644 index 00000000000..fd92f7079a8 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecInfo.ts @@ -0,0 +1,52 @@ +export interface OpenSpecContact { + /** + * The identifying name of the contact person/organization. + */ + name?: string; + /** + * The email address of the contact person/organization. MUST be in the format of an email address. + */ + email?: string; + /** + * The URL pointing to the contact information. MUST be in the format of a URL. + */ + url?: string; +} + +export interface OpenSpecLicense { + /** + * The license name used for the API. + */ + name: string; + /** + * A URL to the license used for the API. MUST be in the format of a URL. + */ + url?: string; +} + +export interface OpenSpecInfo { + /** + * The title of the application. + */ + title: string; + /** + * The version of the OpenAPI document (which is distinct from the [OpenAPI Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oasVersion) version or the API implementation version). + */ + version: string; + /** + * A short description of the application. [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. + */ + description?: string; + /** + * A URL to the Terms of Service for the API. MUST be in the format of a URL. + */ + termsOfService?: string; + /** + * The contact information for the exposed API. + */ + contact?: OpenSpecContact; + /** + * The license information for the exposed API. + */ + license?: OpenSpecLicense; +} diff --git a/packages/openspec/src/common/OpenSpecJsonSchema.ts b/packages/openspec/src/common/OpenSpecJsonSchema.ts new file mode 100644 index 00000000000..a23815c6615 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecJsonSchema.ts @@ -0,0 +1,153 @@ +import {OpenSpecHash} from "./OpenSpecHash"; +import {OpenSpecRef} from "./OpenSpecRef"; +import {OpenSpecTypes} from "./OpenSpecTypes"; + +export interface OpenSpecBaseJsonSchema { + $ref?: string; + /** + * This attribute is a string that provides a short description of the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + title?: string; + /** + * Must be strictly greater than 0. + * A numeric instance is valid only if division by this keyword's value results in an integer. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1 + */ + multipleOf?: number; + /** + * Representing an inclusive upper limit for a numeric instance. + * This keyword validates only if the instance is less than or exactly equal to "maximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2 + */ + maximum?: number; + /** + * Representing an exclusive upper limit for a numeric instance. + * This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3 + */ + exclusiveMaximum?: boolean; + /** + * Representing an inclusive lower limit for a numeric instance. + * This keyword validates only if the instance is greater than or exactly equal to "minimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4 + */ + minimum?: number; + /** + * Representing an exclusive lower limit for a numeric instance. + * This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum". + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5 + */ + exclusiveMinimum?: boolean; + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6 + */ + maxLength?: number; + /** + * Must be a non-negative integer. + * A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7 + */ + minLength?: number; + /** + * Should be a valid regular expression, according to the ECMA 262 regular expression dialect. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8 + */ + pattern?: string; + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11 + */ + maxItems?: number; + /** + * Must be a non-negative integer. + * An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12 + */ + minItems?: number; + /** + * If this keyword has boolean value false, the instance validates successfully. + * If it has boolean value true, the instance validates successfully if all of its elements are unique. + * Omitting this keyword has the same behavior as a value of false. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13 + */ + uniqueItems?: boolean; + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15 + */ + maxProperties?: number; + /** + * Must be a non-negative integer. + * An object instance is valid against "maxProperties" if its number of properties is greater than, + * or equal to, the value of this keyword. + * Omitting this keyword has the same behavior as a value of 0. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16 + */ + minProperties?: number; + /** + * This provides an enumeration of all possible values that are valid + * for the instance property. This MUST be an array, and each item in + * the array represents a possible value for the instance value. If + * this attribute is defined, the instance value MUST be one of the + * values in the array in order for the schema to be valid. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23 + */ + enum?: any[]; + /** + * This attribute is a string that provides a full description of the of purpose the instance property. + * + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2 + */ + description?: string; + /** + * This keyword can be used to supply a default JSON value associated with a particular schema. + * It is RECOMMENDED that a default value be valid against the associated schema. + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3 + */ + default?: any; + /** + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-8 + */ + format?: string; + /** + * A single type, or a union of simple types + * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25 + */ + type?: OpenSpecTypes; +} + +export interface OpenSpecJsonSchema extends OpenSpecBaseJsonSchema { + /** + * Required if type is "array". Describes the type of items in the array. + */ + items?: Schema | OpenSpecRef; + /** + * A free-form property to include an example of an instance for this schema. + */ + required?: string[]; + /** + * Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema. + */ + additionalProperties?: Schema | boolean; + /** + * Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced). + */ + properties?: OpenSpecHash; + /** + * Inline or referenced schema MUST be of a [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject) and not a standard JSON Schema. + */ + allOf?: (Schema | OpenSpecRef)[]; + /** + * Additional external documentation for this schema. + */ + example?: any; +} diff --git a/packages/openspec/src/common/OpenSpecPath.ts b/packages/openspec/src/common/OpenSpecPath.ts new file mode 100644 index 00000000000..cdd91b750b7 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecPath.ts @@ -0,0 +1,10 @@ +export interface OpenSpecPath { + $ref?: string; + get?: Operation; + put?: Operation; + post?: Operation; + delete?: Operation; + options?: Operation; + head?: Operation; + patch?: Operation; +} diff --git a/packages/openspec/src/common/OpenSpecRef.ts b/packages/openspec/src/common/OpenSpecRef.ts new file mode 100644 index 00000000000..d0b40d0200a --- /dev/null +++ b/packages/openspec/src/common/OpenSpecRef.ts @@ -0,0 +1,3 @@ +export interface OpenSpecRef { + $ref: string; +} diff --git a/packages/openspec/src/common/OpenSpecSecurity.ts b/packages/openspec/src/common/OpenSpecSecurity.ts new file mode 100644 index 00000000000..eac1a3ccdfe --- /dev/null +++ b/packages/openspec/src/common/OpenSpecSecurity.ts @@ -0,0 +1,3 @@ +import {OpenSpecHash} from "./OpenSpecHash"; + +export type OpenSpecSecurity = OpenSpecHash[]; diff --git a/packages/openspec/src/common/OpenSpecTag.ts b/packages/openspec/src/common/OpenSpecTag.ts new file mode 100644 index 00000000000..f8ede58fe77 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecTag.ts @@ -0,0 +1,7 @@ +import {OpenSpecExternalDocs} from "./OpenSpecExternalDocs"; + +export interface OpenSpecTag { + name: string; + description?: string; + externalDocs?: OpenSpecExternalDocs; +} diff --git a/packages/openspec/src/common/OpenSpecTypes.ts b/packages/openspec/src/common/OpenSpecTypes.ts new file mode 100644 index 00000000000..a769b62291b --- /dev/null +++ b/packages/openspec/src/common/OpenSpecTypes.ts @@ -0,0 +1 @@ +export type OpenSpecTypes = "string" | "number" | "integer" | "boolean" | "array" | "object" | "file"; diff --git a/packages/openspec/src/common/OpenSpecVersions.ts b/packages/openspec/src/common/OpenSpecVersions.ts new file mode 100644 index 00000000000..3ceb4ea2ac6 --- /dev/null +++ b/packages/openspec/src/common/OpenSpecVersions.ts @@ -0,0 +1,3 @@ +export type OS2Versions = "2.0"; +export type OS3Versions = "3.0.1" | "3.0.2" | "3.0.3" | "3.1.0"; +export type OpenSpecVersions = OS2Versions | OS3Versions; diff --git a/packages/openspec/src/common/OpenSpecXML.ts b/packages/openspec/src/common/OpenSpecXML.ts new file mode 100644 index 00000000000..3e7c342360b --- /dev/null +++ b/packages/openspec/src/common/OpenSpecXML.ts @@ -0,0 +1,22 @@ +export interface OpenSpecXML { + /** + * Replaces the name of the element/attribute used for the described schema property. When defined within items, it will affect the name of the individual XML elements within the list. When defined alongside type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it will be ignored. + */ + name?: string; + /** + * The URI of the namespace definition. Value MUST be in the form of an absolute URI. + */ + namespace?: string; + /** + * The prefix to be used for the [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#xmlName). + */ + prefix?: string; + /** + * Declares whether the property definition translates to an attribute instead of an element. Default value is false. + */ + attribute?: boolean; + /** + * MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ) or unwrapped (). Default value is false. The definition takes effect only when defined alongside type being array (outside the items). + */ + wrapped?: boolean; +} diff --git a/packages/openspec/src/common/index.ts b/packages/openspec/src/common/index.ts new file mode 100644 index 00000000000..cb8abbc48df --- /dev/null +++ b/packages/openspec/src/common/index.ts @@ -0,0 +1,11 @@ +export * from "./OpenSpecExternalDocs"; +export * from "./OpenSpecHash"; +export * from "./OpenSpecInfo"; +export * from "./OpenSpecJsonSchema"; +export * from "./OpenSpecPath"; +export * from "./OpenSpecRef"; +export * from "./OpenSpecTag"; +export * from "./OpenSpecTypes"; +export * from "./OpenSpecVersions"; +export * from "./OpenSpecXML"; +export * from "./OpenSpecSecurity"; diff --git a/packages/openspec/src/index.ts b/packages/openspec/src/index.ts new file mode 100644 index 00000000000..38d9c9b7a93 --- /dev/null +++ b/packages/openspec/src/index.ts @@ -0,0 +1,3 @@ +export * from "./common"; +export * from "./openspec2"; +export * from "./openspec3"; diff --git a/packages/openspec/src/openspec2/OS2Header.ts b/packages/openspec/src/openspec2/OS2Header.ts new file mode 100644 index 00000000000..61642d19672 --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Header.ts @@ -0,0 +1,8 @@ +import {OS2BaseSchema} from "./OS2Schema"; + +export interface OS2Header extends OS2BaseSchema { + /** + * The type of the object. The value MUST be one of `string`, `number`, `integer`, `boolean`, or `array`. + */ + type: "string" | "number" | "integer" | "boolean" | "array"; +} diff --git a/packages/openspec/src/openspec2/OS2Operation.ts b/packages/openspec/src/openspec2/OS2Operation.ts new file mode 100644 index 00000000000..2ad9a1a9d18 --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Operation.ts @@ -0,0 +1,65 @@ +import {OpenSpecExternalDocs} from "../common/OpenSpecExternalDocs"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OpenSpecRef} from "../common/OpenSpecRef"; +import {OpenSpecSecurity} from "../common/OpenSpecSecurity"; +import {OS2Parameter} from "./OS2Parameter"; +import {OS2Response} from "./OS2Response"; + +export interface OS2Operation { + /** + * A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. + */ + tags?: string[]; + /** + * A short summary of what the operation does. For maximum readability in the swagger-ui, this field SHOULD be less than 120 characters. + */ + summary?: string; + /** + * A verbose explanation of the operation behavior. GFM syntax can be used for rich text representation. + */ + description?: string; + /** + * Additional external documentation for this operation. + */ + externalDocs?: OpenSpecExternalDocs; + /** + * Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is recommended to follow common programming naming conventions. + */ + operationId?: string; + /** + * A list of MIME types the operation can consume. This overrides the consumes definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under [Mime Types](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#mimeTypes). + */ + consumes?: string[]; + /** + * A list of MIME types the operation can produce. This overrides the produces definition at the Swagger Object. An empty value MAY be used to clear the global definition. Value MUST be as described under [Mime Types](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#mimeTypes). + */ + produces?: string[]; + /** + * A list of parameters that are applicable for this operation. + * If a parameter is already defined at the [Path Item](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathItemParameters), + * the new definition will override it, but can never remove it. The list MUST NOT include duplicated parameters. + * A unique parameter is defined by a combination of a [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterName) and (location)[https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterIn]. + * The list can use the [Reference Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#referenceObject) to link to parameters that are defined at the [Swagger Object's parameters](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerParameters). + * There can be one "body" parameter at most. + */ + parameters?: (OS2Parameter | OpenSpecRef)[]; + /** + * The list of possible responses as they are returned from executing this operation. + */ + responses: OpenSpecHash; + /** + * The transfer protocol of the API. Values MUST be from the list: `http`, `https`, `ws`, `wss`. If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself. + */ + schemes?: string[]; + /** + * Declares this operation to be deprecated. Usage of the declared operation should be refrained. Default value is false. + */ + deprecated?: boolean; + /** + * A declaration of which security schemes are applied for this operation. + * The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). + * This definition overrides any declared top-level [security](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerSecurity). + * To remove a top-level security declaration, an empty array can be used. + */ + security?: OpenSpecSecurity; +} diff --git a/packages/openspec/src/openspec2/OS2Parameter.ts b/packages/openspec/src/openspec2/OS2Parameter.ts new file mode 100644 index 00000000000..fede3dd6fb4 --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Parameter.ts @@ -0,0 +1,66 @@ +import {OpenSpecTypes} from "../common/OpenSpecTypes"; +import {OS2BaseSchema, OS2Schema} from "./OS2Schema"; + +export type OS2BaseParameter = { + name: string; + in: "body" | "query" | "path" | "header" | "formData"; + required?: boolean; + description?: string; +}; + +export type OS2BodyParameter = OS2BaseParameter & { + in: "body"; + schema?: OS2Schema; +}; + +export type OS2GenericFormat = { + type?: OpenSpecTypes; + format?: string; +}; + +export type OS2IntegerFormat = { + type: "integer"; + format?: "int32" | "int64"; +}; + +export type OS2NumberFormat = { + type: "number"; + format?: "float" | "double"; +}; + +export type OS2StringFormat = { + type: "string"; + format?: "" | "byte" | "binary" | "date" | "date-time" | "password"; +}; + +export type OS2SchemaFormatConstraints = OS2GenericFormat | OS2IntegerFormat | OS2NumberFormat | OS2StringFormat; +export type OS2BaseFormatContrainedParameter = OS2BaseParameter & OS2SchemaFormatConstraints; +export type ParameterCollectionFormat = "csv" | "ssv" | "tsv" | "pipes" | "multi"; + +export type OS2QueryParameter = OS2BaseFormatContrainedParameter & + OS2BaseSchema & { + in: "query"; + allowEmptyValue?: boolean; + collectionFormat?: ParameterCollectionFormat; + }; + +export type OS2PathParameter = OS2BaseFormatContrainedParameter & + OS2BaseSchema & { + in: "path"; + required: true; + }; + +export type OS2HeaderParameter = OS2BaseFormatContrainedParameter & + OS2BaseSchema & { + in: "header"; + }; + +export type OS2FormDataParameter = OS2BaseFormatContrainedParameter & + OS2BaseSchema & { + in: "formData"; + type: OpenSpecTypes; + allowEmptyValue?: boolean; + collectionFormat?: ParameterCollectionFormat; + }; + +export type OS2Parameter = OS2BodyParameter | OS2FormDataParameter | OS2QueryParameter | OS2PathParameter | OS2HeaderParameter; diff --git a/packages/openspec/src/openspec2/OS2Paths.ts b/packages/openspec/src/openspec2/OS2Paths.ts new file mode 100644 index 00000000000..d5ab807ddab --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Paths.ts @@ -0,0 +1,8 @@ +import {OpenSpecPath} from "../common/OpenSpecPath"; +import {OpenSpecRef} from "../common/OpenSpecRef"; +import {OS2Operation} from "./OS2Operation"; +import {OS2Parameter} from "./OS2Parameter"; + +export interface OS2Paths extends OpenSpecPath { + parameters?: (OS2Parameter | OpenSpecRef)[]; +} diff --git a/packages/openspec/src/openspec2/OS2Response.ts b/packages/openspec/src/openspec2/OS2Response.ts new file mode 100644 index 00000000000..33b9764469a --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Response.ts @@ -0,0 +1,22 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS2Header} from "./OS2Header"; +import {OS2Schema} from "./OS2Schema"; + +export interface OS2Response { + /** + * A short description of the response. GFM syntax can be used for rich text representation. + */ + description: string; + /** + * A definition of the response structure. It can be a primitive, an array or an object. If this field does not exist, it means no content is returned as part of the response. As an extension to the Schema Object, its root type value may also be "file". This SHOULD be accompanied by a relevant produces mime-type. + */ + schema?: OS2Schema; + /** + * A list of headers that are sent with the response. + */ + headers?: OpenSpecHash; + /** + * An example of the response message. + */ + examples?: OpenSpecHash<{}>; +} diff --git a/packages/openspec/src/openspec2/OS2Schema.ts b/packages/openspec/src/openspec2/OS2Schema.ts new file mode 100644 index 00000000000..9a984f3dd66 --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Schema.ts @@ -0,0 +1,39 @@ +import {OpenSpecExternalDocs} from "../common/OpenSpecExternalDocs"; +import {OpenSpecBaseJsonSchema, OpenSpecJsonSchema} from "../common/OpenSpecJsonSchema"; +import {OpenSpecRef} from "../common/OpenSpecRef"; +import {OpenSpecXML} from "../common/OpenSpecXML"; + +export interface OS2XML { + name?: string; + namespace?: string; + prefix?: string; + attribute?: boolean; + wrapped?: boolean; +} + +export interface OS2BaseSchema extends OpenSpecBaseJsonSchema { + /** + * Required if type is "array". Describes the type of items in the array. + */ + items?: OS2Schema | OpenSpecRef; +} + +export interface OS2Schema extends OpenSpecJsonSchema { + /** + * Adds support for polymorphism. + * The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the required property list. When used, the value MUST be the name of this schema or any schema that inherits it. + */ + discriminator?: string; + /** + * Relevant only for Schema "properties" definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request. Properties marked as readOnly being true SHOULD NOT be in the required list of the defined schema. Default value is false. + */ + readOnly?: boolean; + /** + * This MAY be used only on properties schemas. It has no effect on root schemas. Adds Additional metadata to describe the XML representation format of this property. + */ + xml?: OpenSpecXML; + /** + * Additional external documentation for this schema. + */ + externalDocs?: OpenSpecExternalDocs; +} diff --git a/packages/openspec/src/openspec2/OS2Security.ts b/packages/openspec/src/openspec2/OS2Security.ts new file mode 100644 index 00000000000..a51f33575d8 --- /dev/null +++ b/packages/openspec/src/openspec2/OS2Security.ts @@ -0,0 +1,58 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; + +export interface OS2SecurityBase { + /** + * The type of the security scheme + */ + type: "basic" | "apiKey" | "oauth2"; + /** + * + */ + description?: string; +} + +export interface OS2SecurityBasic extends OS2SecurityBase { + type: "basic"; +} + +export interface OS2SecurityApiKey extends OS2SecurityBase { + type: "apiKey"; + name: string; + in: "query" | "header"; +} + +export interface OS2SecurityOAuth extends OS2SecurityBase { + type: "oauth2"; + flow: "accessCode" | "application" | "implicit" | "password"; + /** + * The available scopes for the OAuth2 security scheme. + */ + scopes: OpenSpecHash; +} + +export interface OS2FlowImplicit extends OS2SecurityOAuth { + type: "oauth2"; + flow: "implicit"; + authorizationUrl: string; +} + +export interface OS2FlowPassword extends OS2SecurityOAuth { + type: "oauth2"; + flow: "password"; + tokenUrl: string; +} + +export interface OS2FlowApplication extends OS2SecurityOAuth { + type: "oauth2"; + flow: "application"; + tokenUrl: string; +} + +export interface OS2FlowAccessCode extends OS2SecurityOAuth { + type: "oauth2"; + flow: "accessCode"; + tokenUrl: string; + authorizationUrl: string; +} + +export type OS2Security = OS2SecurityBasic | OS2FlowAccessCode | OS2FlowApplication | OS2FlowImplicit | OS2FlowPassword | OS2SecurityApiKey; diff --git a/packages/openspec/src/openspec2/OpenSpec2.ts b/packages/openspec/src/openspec2/OpenSpec2.ts new file mode 100644 index 00000000000..e95399d3e10 --- /dev/null +++ b/packages/openspec/src/openspec2/OpenSpec2.ts @@ -0,0 +1,72 @@ +import {OpenSpecExternalDocs} from "../common/OpenSpecExternalDocs"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OpenSpecInfo} from "../common/OpenSpecInfo"; +import {OpenSpecSecurity} from "../common/OpenSpecSecurity"; +import {OpenSpecTag} from "../common/OpenSpecTag"; +import {OS2BodyParameter, OS2QueryParameter} from "./OS2Parameter"; +import {OS2Paths} from "./OS2Paths"; +import {OS2Schema} from "./OS2Schema"; +import {OS2Security} from "./OS2Security"; + +export interface OpenSpec2 { + /** + * Specifies the Swagger Specification version being used. It can be used by the Swagger UI and other clients to interpret the API listing. The value MUST be "2.0". + */ + swagger: string; + /** + * Provides metadata about the API. The metadata can be used by the clients if needed. + */ + info?: OpenSpecInfo; + /** + * The host (name or ip) serving the API. This MUST be the host only and does not include the scheme nor sub-paths. It MAY include a port. If the host is not included, the host serving the documentation is to be used (including the port). The host does not support [path templating](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathTemplating). + */ + host?: string; + /** + * The base path on which the API is served, which is relative to the host. If it is not included, the API is served directly under the host. The value MUST start with a leading slash (/). The basePath does not support path [path templating](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathTemplating). + */ + basePath?: string; + /** + * The transfer protocol of the API. Values MUST be from the list: `http`, `https`, `ws`, `wss`. If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself. + */ + schemes?: ("http" | "https" | "ws" | "wss")[]; + /** + * A list of MIME types the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under [Mime Types](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#mimeTypes). + */ + consumes?: string[]; + /** + * A list of MIME types the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under [Mime Types](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#mimeTypes). + */ + produces?: string[]; + /** + * The available paths and operations for the API. + */ + paths?: OpenSpecHash; + /** + * An object to hold data types produced and consumed by operations. + */ + definitions?: OpenSpecHash; + /** + * An object to hold parameters that can be used across operations. This property does not define global parameters for all operations. + */ + parameters?: OpenSpecHash; + /** + * An object to hold responses that can be used across operations. This property does not define global responses for all operations. + */ + responses?: OpenSpecHash; + /** + * A declaration of which security schemes are applied for the API as a whole. The list of values describes alternative security schemes that can be used (that is, there is a logical OR between the security requirements). Individual operations can override this definition. + */ + security?: OpenSpecSecurity; + /** + * Security scheme definitions that can be used across the specification. + */ + securityDefinitions?: OpenSpecHash; + /** + * A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared may be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. + */ + tags?: OpenSpecTag[]; + /** + * Additional external documentation. + */ + externalDocs?: OpenSpecExternalDocs; +} diff --git a/packages/openspec/src/openspec2/index.ts b/packages/openspec/src/openspec2/index.ts new file mode 100644 index 00000000000..6ba494b55fc --- /dev/null +++ b/packages/openspec/src/openspec2/index.ts @@ -0,0 +1,8 @@ +export * from "./OpenSpec2"; +export * from "./OS2Header"; +export * from "./OS2Operation"; +export * from "./OS2Parameter"; +export * from "./OS2Paths"; +export * from "./OS2Response"; +export * from "./OS2Schema"; +export * from "./OS2Security"; diff --git a/packages/openspec/src/openspec3/OS3Callbacks.ts b/packages/openspec/src/openspec3/OS3Callbacks.ts new file mode 100644 index 00000000000..cd75c9bb219 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Callbacks.ts @@ -0,0 +1,5 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS3Paths} from "./OS3Paths"; +import {OS3Schema} from "./OS3Schema"; + +export type OS3Callbacks = OpenSpecHash>>; diff --git a/packages/openspec/src/openspec3/OS3Components.ts b/packages/openspec/src/openspec3/OS3Components.ts new file mode 100644 index 00000000000..b1ad92b8f8e --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Components.ts @@ -0,0 +1,49 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS3Callbacks} from "./OS3Callbacks"; +import {OS3Example} from "./OS3Example"; +import {OS3Header} from "./OS3Header"; +import {OS3Link} from "./OS3Link"; +import {OS3Parameter} from "./OS3Parameter"; +import {OS3RequestBody} from "./OS3RequestBody"; +import {OS3Response} from "./OS3Response"; +import {OS3Schema} from "./OS3Schema"; +import {OS3Security} from "./OS3Security"; + +export interface OS3Components { + /** + * An object to hold reusable [Schema Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject). + */ + schemas?: OpenSpecHash; + /** + * An object to hold reusable [Response Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#responseObject). + */ + responses?: OpenSpecHash>; + /** + * An object to hold reusable [Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterObject). + */ + parameters?: OpenSpecHash>; + /** + * An object to hold reusable [Example Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#exampleObject). + */ + examples?: OpenSpecHash; + /** + * An object to hold reusable [Request Body Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#requestBodyObject). + */ + requestBodies?: OpenSpecHash>; + /** + * An object to hold reusable [Header Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#headerObject). + */ + headers?: OpenSpecHash>; + /** + * An object to hold reusable [Security Scheme Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#securitySchemeObject). + */ + securitySchemes?: OpenSpecHash; + /** + * An object to hold reusable [Link Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#linkObject). + */ + links?: OpenSpecHash; + /** + * An object to hold reusable [Callback Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#callbackObject). + */ + callbacks?: OS3Callbacks; +} diff --git a/packages/openspec/src/openspec3/OS3Encoding.ts b/packages/openspec/src/openspec3/OS3Encoding.ts new file mode 100644 index 00000000000..810efca8396 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Encoding.ts @@ -0,0 +1,25 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS3Header} from "./OS3Header"; + +export interface OS3Encoding { + /** + * The `Content-Type` for encoding a specific property. Default value depends on the property type: for `string` with `format` being `binary` – `application/octet-stream`; for other primitive types – `text/plain`; for `object` - application/json; for `array` – the default is defined based on the inner type. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. + */ + contentType?: string; + /** + * A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a multipart. + */ + headers?: OpenSpecHash; + /** + * Describes how a specific property value will be serialized depending on its type. See [Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterObject) for details on the `[style](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterStyle)` property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. + */ + style?: string; + /** + * When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When `[style](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterStyle)` is `form`, the default value is true. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. + */ + explode?: boolean; + /** + * Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. + */ + allowReserved?: boolean; +} diff --git a/packages/openspec/src/openspec3/OS3Example.ts b/packages/openspec/src/openspec3/OS3Example.ts new file mode 100644 index 00000000000..53d685bda6d --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Example.ts @@ -0,0 +1,19 @@ +export interface OS3Example { + /** + * Short description for the example. + */ + summary?: string; + /** + * Long description for the example. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. + */ + value?: any; + /** + * A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. + * The `value` field and `externalValue` field are mutually exclusive. + */ + externalValue?: string; +} diff --git a/packages/openspec/src/openspec3/OS3Flows.ts b/packages/openspec/src/openspec3/OS3Flows.ts new file mode 100644 index 00000000000..9bec23f0fa5 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Flows.ts @@ -0,0 +1,49 @@ +export interface OS3Flow { + /** + * The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. + */ + refreshUrl?: string; + /** + * The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. + */ + scopes: {[key: string]: string}; +} + +export interface OS3FlowImplicit extends OS3Flow { + /** + * The authorization URL to be used for this flow. This MUST be in the form of a URL. + */ + authorizationUrl: string; +} + +export interface OS3FlowPassword extends OS3Flow { + /** + * The token URL to be used for this flow. This MUST be in the form of a URL. + */ + tokenUrl: string; +} + +export interface OS3FlowClientCredentials { + /** + * The token URL to be used for this flow. This MUST be in the form of a URL. + */ + tokenUrl: string; +} + +export interface OS3FlowAuthorizationCode { + /** + * The authorization URL to be used for this flow. This MUST be in the form of a URL. + */ + authorizationUrl: string; + /** + * The token URL to be used for this flow. This MUST be in the form of a URL. + */ + tokenUrl: string; +} + +export interface OS3Flows { + implicit?: OS3FlowImplicit; + password?: OS3FlowPassword; + clientCredentials?: OS3FlowClientCredentials; + authorizationCode?: OS3FlowAuthorizationCode; +} diff --git a/packages/openspec/src/openspec3/OS3Header.ts b/packages/openspec/src/openspec3/OS3Header.ts new file mode 100644 index 00000000000..f098282f76a --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Header.ts @@ -0,0 +1,17 @@ +import {OpenSpecExternalDocs, OpenSpecRef} from "../common"; +import {OS3Schema} from "./OS3Schema"; + +export interface OS3Header { + /** + * A description of the header. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * The schema defining the type used for the header. + */ + schema?: Schema | OpenSpecRef; + /** + * Additional external documentation for this tag. + */ + externalDocs?: OpenSpecExternalDocs; +} diff --git a/packages/openspec/src/openspec3/OS3Link.ts b/packages/openspec/src/openspec3/OS3Link.ts new file mode 100644 index 00000000000..9596f80c807 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Link.ts @@ -0,0 +1,25 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS3Server} from "./OS3Server"; + +export interface OS3Link { + /** + * A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation Object in the OpenAPI definition. + */ + operationRef?: string; + /** + * The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually exclusive of the operationRef field. + */ + operationId?: string; + /** + * A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter location [{in}.]{name} for operations that use the same [parameter name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn) in different locations (e.g. path.id). + */ + parameters?: OpenSpecHash; + /** + * A description of the link. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * A server object to be used by the target operation. + */ + server?: OS3Server; +} diff --git a/packages/openspec/src/openspec3/OS3MediaType.ts b/packages/openspec/src/openspec3/OS3MediaType.ts new file mode 100644 index 00000000000..7ae76194876 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3MediaType.ts @@ -0,0 +1,24 @@ +import {OS3Schema} from "./OS3Schema"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OpenSpecRef} from "../common/OpenSpecRef"; +import {OS3Encoding} from "./OS3Encoding"; +import {OS3Example} from "./OS3Example"; + +export interface OS3MediaType { + /** + * The schema defining the type used for the request body. + */ + schema?: Schema | OpenSpecRef; + /** + * Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema which contains an example, the example value SHALL override the example provided by the schema. + */ + example?: any; + /** + * Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema which contains an example, the examples value SHALL override the example provided by the schema. + */ + examples?: OpenSpecHash; + /** + * A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to requestBody objects when the media type is `multipart` or `application/x-www-form-urlencoded`. + */ + encoding?: OpenSpecHash; +} diff --git a/packages/openspec/src/openspec3/OS3Operation.ts b/packages/openspec/src/openspec3/OS3Operation.ts new file mode 100644 index 00000000000..54c92aa1df3 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Operation.ts @@ -0,0 +1,70 @@ +import {OpenSpecExternalDocs} from "../common/OpenSpecExternalDocs"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OpenSpecSecurity} from "../common/OpenSpecSecurity"; +import {OS3Callbacks} from "./OS3Callbacks"; +import {OS3Parameter} from "./OS3Parameter"; +import {OS3RequestBody} from "./OS3RequestBody"; +import {OS3Response} from "./OS3Response"; +import {OS3Schema} from "./OS3Schema"; +import {OS3Server} from "./OS3Server"; + +export interface OS3Operation, Response = OpenSpecHash>> { + /** + * Unique string used to identify the operation. The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. + */ + operationId: string; + /** + * A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * A short summary of what the operation does. + */ + summary?: string; + /** + * A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. + */ + tags?: string[]; + /** + * Additional external documentation for this operation. + */ + externalDocs?: OpenSpecExternalDocs; + /** + * A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#pathItemParameters), + * the new definition will override it but can never remove it. + * The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterName) and (location)[https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn]. + * The list can use the [Reference Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#componentsParameters). + */ + parameters?: Parameter[]; + /** + * The request body applicable for this operation. + * The requestBody is only supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. + * In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers. + */ + requestBody?: OS3RequestBody; + /** + * The list of possible responses as they are returned from executing this operation. + */ + responses: Response; + /** + * Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is false. + */ + deprecated?: boolean; + /** + * A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. + * Only one of the security requirement objects need to be satisfied to authorize a request. + * This definition overrides any declared top-level [security](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oasSecurity). To remove a top-level security declaration, an empty array can be used. + */ + security?: OpenSpecSecurity; + /** + * An alternative server array to service this operation. If an alternative server object is specified at the Path Item Object or Root level, it will be overridden by this value. + */ + servers?: OS3Server[]; + /** + * A map of possible out-of band callbacks related to the parent operation. + * The key is a unique identifier for the [Callback Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#callbackObject). + * Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. + * The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + */ + callbacks?: OS3Callbacks; +} diff --git a/packages/openspec/src/openspec3/OS3Parameter.ts b/packages/openspec/src/openspec3/OS3Parameter.ts new file mode 100644 index 00000000000..4c045ddd7ad --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Parameter.ts @@ -0,0 +1,80 @@ +import {OpenSpecHash, OpenSpecRef} from "../common"; +import {OS3Example} from "./OS3Example"; +import {OS3MediaType} from "./OS3MediaType"; +import {OS3Schema} from "./OS3Schema"; + +export interface OS3Parameter { + /** + *The name of the parameter. Parameter names are case sensitive. + * + * - If [`in`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn) is `"path"`, the `name` field MUST correspond to the associated [path](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#pathsPath) segment from the path field in the [Paths Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#pathsObject). See [Path Templating](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#pathTemplating) for further information. + * - If [`in`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored. + * - For all other cases, the `name` corresponds to the parameter name used by the [`in`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn) property. + */ + name: string; + /** + * The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. + */ + in: "path" | "query" | "header" | "cookie"; + /** + * Determines whether this parameter is mandatory. If the [parameter location](Determines whether this parameter is mandatory. + * If the parameter location is `"path"`, this property is **REQUIRED** and its value MUST be `true`. + * Otherwise, the property MAY be included and its default value is false.) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. + * Otherwise, the property MAY be included and its default value is `false`. + */ + required: boolean; + /** + * A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. + */ + deprecated?: boolean; + /** + * Sets the ability to pass empty-valued parameters. + * This is valid only for query parameters and allows sending a parameter with an empty value. + * Default value is `false`. + * If style is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. + */ + allowEmptyValue?: boolean; + /** + * The schema defining the type used for the parameter. + */ + schema?: OS3Schema | OpenSpecRef; + /** + * Describes how the parameter value will be serialized depending on the type of the parameter value. + * Default values (based on value of in): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. + * See [style values](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#style-values). + */ + style?: "matrix" | "label" | "form" | "simple" | "spaceDelimited" | "pipeDelimited" | "deepObject"; + /** + * When this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map. + * For other types of parameters this property has no effect. When style is form, the default value is true. For all other styles, the default value is false. + */ + explode?: boolean; + /** + * Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. + * This property only applies to parameters with an `in` value of `query`. The default value is `false`. + */ + allowReserved?: boolean; + /** + * Example of the media type. + * The `example` SHOULD match the specified schema and encoding properties if present. + * The `example` field is mutually exclusive of the `examples` field. + * Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL override the example provided by the schema. + * To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. + */ + example?: any; + /** + * Examples of the media type. + * Each example SHOULD contain a value in the correct format as specified in the parameter encoding. + * The `examples` field is mutually exclusive of the `example` field. + * Furthermore, if referencing a `schema` which contains an example, the examples value SHALL override the example provided by the schema. + */ + examples?: OpenSpecHash; + /*** + * A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. + */ + content?: OpenSpecHash; +} diff --git a/packages/openspec/src/openspec3/OS3Paths.ts b/packages/openspec/src/openspec3/OS3Paths.ts new file mode 100644 index 00000000000..99b173b8905 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Paths.ts @@ -0,0 +1,28 @@ +import {OpenSpecPath, OpenSpecRef} from "../common"; +import {OS3Operation} from "./OS3Operation"; +import {OS3Parameter} from "./OS3Parameter"; +import {OS3Schema} from "./OS3Schema"; +import {OS3Server} from "./OS3Server"; + +export interface OS3Paths extends OpenSpecPath> { + /** + * An optional, string summary, intended to apply to all operations in this path. + */ + summary?: string; + /** + * An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * A definition of a TRACE operation on this path. + */ + trace?: OS3Operation; + /** + * An alternative server array to service all operations in this path. + */ + servers?: OS3Server[]; + /** + * A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. + */ + parameters?: (OS3Parameter | OpenSpecRef)[]; +} diff --git a/packages/openspec/src/openspec3/OS3RequestBody.ts b/packages/openspec/src/openspec3/OS3RequestBody.ts new file mode 100644 index 00000000000..27aa1cdff88 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3RequestBody.ts @@ -0,0 +1,18 @@ +import {OS3Schema} from "./OS3Schema"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS3MediaType} from "./OS3MediaType"; + +export interface OS3RequestBody { + /** + * A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; + /** + * A map containing descriptions of potential request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* + */ + content?: OpenSpecHash>; + /** + * Determines if the request body is required in the request. Defaults to false. + */ + required?: boolean; +} diff --git a/packages/openspec/src/openspec3/OS3Response.ts b/packages/openspec/src/openspec3/OS3Response.ts new file mode 100644 index 00000000000..aa1fcd85676 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Response.ts @@ -0,0 +1,25 @@ +import {OS3Schema} from "./OS3Schema"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OpenSpecRef} from "../common/OpenSpecRef"; +import {OS3Header} from "./OS3Header"; +import {OS3Link} from "./OS3Link"; +import {OS3MediaType} from "./OS3MediaType"; + +export interface OS3Response> { + /** + * A short description of the response. CommonMark syntax MAY be used for rich text representation. + */ + description: string; + /** + * Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name "Content-Type", it SHALL be ignored. + */ + headers?: OpenSpecHash
; + /** + * A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* + */ + content?: OpenSpecHash>; + /** + * A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#componentsObject). + */ + links?: OpenSpecHash; +} diff --git a/packages/openspec/src/openspec3/OS3Schema.ts b/packages/openspec/src/openspec3/OS3Schema.ts new file mode 100644 index 00000000000..540c26f9393 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Schema.ts @@ -0,0 +1,49 @@ +import {OpenSpecExternalDocs, OpenSpecRef, OpenSpecXML} from "../common"; +import {OpenSpecBaseJsonSchema, OpenSpecJsonSchema} from "../common/OpenSpecJsonSchema"; + +export interface OS3BaseSchema extends OpenSpecBaseJsonSchema { + /** + * Required if type is "array". Describes the type of items in the array. + */ + items?: OS3Schema | OpenSpecRef; +} + +export interface OS3Schema extends OpenSpecJsonSchema { + /** + * Inline or referenced schema MUST be of a [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject) and not a standard JSON Schema. + */ + oneOf?: (OS3Schema | OpenSpecRef)[]; + /** + * Inline or referenced schema MUST be of a [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject) and not a standard JSON Schema. + */ + anyOf?: (OS3Schema | OpenSpecRef)[]; + /** + * Inline or referenced schema MUST be of a [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject) and not a standard JSON Schema. + */ + not?: OS3Schema | OpenSpecRef; + /** + * Allows sending a null value for the defined schema. Default value is false. + */ + nullable?: boolean; + /** + * Adds support for polymorphism. + * The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the required property list. When used, the value MUST be the name of this schema or any schema that inherits it. + */ + discriminator?: string; + /** + * Relevant only for Schema "properties" definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but MUST NOT be sent as part of the request. Properties marked as readOnly being true SHOULD NOT be in the required list of the defined schema. Default value is false. + */ + readOnly?: boolean; + /** + * Relevant only for Schema "properties" definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as writeOnly being true and is in the required list, the required will take effect on the request only. A property MUST NOT be marked as both readOnly and writeOnly being true. Default value is false. + */ + writeOnly?: boolean; + /** + * This MAY be used only on properties schemas. It has no effect on root schemas. Adds Additional metadata to describe the XML representation format of this property. + */ + xml?: OpenSpecXML; + /** + * Additional external documentation for this schema. + */ + externalDocs?: OpenSpecExternalDocs; +} diff --git a/packages/openspec/src/openspec3/OS3Security.ts b/packages/openspec/src/openspec3/OS3Security.ts new file mode 100644 index 00000000000..9606aabed85 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Security.ts @@ -0,0 +1,60 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OS3Flows} from "./OS3Flows"; + +export interface OS3SecurityBase { + /** + * The type of the security scheme + */ + type: "apiKey" | "oauth2" | "http"; + /** + * + */ + description?: string; +} + +export interface OS3SecurityApiKey extends OS3SecurityBase { + /** + * The type of the security scheme + */ + type: "apiKey"; + /** + * The name of the header, query or cookie parameter to be used. + */ + name: string; + /** + * The location of the API key. Valid values are `query`, `header` or `cookie`. + */ + in: "query" | "header" | "cookie"; +} + +export interface OS3SecurityOAuth2 extends OS3SecurityBase { + /** + * The type of the security scheme + */ + type: "oauth2"; + /** + * An object containing configuration information for the flow types supported. + */ + flows: OS3Flows; + /** + * The available scopes for the OAuth2 security scheme. + */ + scopes: OpenSpecHash; +} + +export interface OS3SecurityHTTP extends OS3SecurityBase { + /** + * The type of the security scheme + */ + type: "http"; + /** + * The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). + */ + scheme: string; + /** + * A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. + */ + bearerFormat: string; +} + +export type OS3Security = OS3SecurityApiKey | OS3SecurityHTTP | OS3SecurityOAuth2; diff --git a/packages/openspec/src/openspec3/OS3Server.ts b/packages/openspec/src/openspec3/OS3Server.ts new file mode 100644 index 00000000000..90823868b54 --- /dev/null +++ b/packages/openspec/src/openspec3/OS3Server.ts @@ -0,0 +1,31 @@ +import {OpenSpecHash} from "../common/OpenSpecHash"; + +export interface OpenSpecServerVariable { + /** + * An enumeration of string values to be used if the substitution options are from a limited set. + */ + enum?: string; + /** + * The default value to use for substitution, and to send, if an alternate value is not supplied. Unlike the Schema Object's default, this value MUST be provided by the consumer. + */ + default: string; + /** + * An optional description for the server variable. CommonMark syntax MAY be used for rich text representation. + */ + description?: string; +} + +export interface OS3Server { + /** + * A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{brackets}`. + */ + url: string; + /** + * An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation. + */ + description: string; + /** + * A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + variables?: OpenSpecHash; +} diff --git a/packages/openspec/src/openspec3/OpenSpec3.ts b/packages/openspec/src/openspec3/OpenSpec3.ts new file mode 100644 index 00000000000..3e0ad57b50e --- /dev/null +++ b/packages/openspec/src/openspec3/OpenSpec3.ts @@ -0,0 +1,44 @@ +import {OS3Schema} from "./OS3Schema"; +import {OpenSpecExternalDocs} from "../common/OpenSpecExternalDocs"; +import {OpenSpecHash} from "../common/OpenSpecHash"; +import {OpenSpecInfo} from "../common/OpenSpecInfo"; +import {OpenSpecSecurity} from "../common/OpenSpecSecurity"; +import {OpenSpecTag} from "../common/OpenSpecTag"; +import {OS3Components} from "./OS3Components"; +import {OS3Paths} from "./OS3Paths"; +import {OS3Server} from "./OS3Server"; + +export interface OpenSpec3 { + /** + * This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses. The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is not related to the API info.version string. + */ + openapi: string; + /** + * Provides metadata about the API. The metadata MAY be used by tooling as required. + */ + info: OpenSpecInfo; + /** + * An array of Server Objects, which provide connectivity information to a target server. If the servers property is not provided, or is an empty array, the default value would be a Server Object with a url value of /. + */ + servers?: OS3Server[]; + /** + * The available paths and operations for the API. + */ + paths: OpenSpecHash>; + /** + * An element to hold various schemas for the specification. + */ + components?: OS3Components; + /** + * A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. + */ + security?: OpenSpecSecurity; + /** + * A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. + */ + tags?: OpenSpecTag[]; + /** + * Additional external documentation. + */ + externalDocs: OpenSpecExternalDocs; +} diff --git a/packages/openspec/src/openspec3/index.ts b/packages/openspec/src/openspec3/index.ts new file mode 100644 index 00000000000..ab063da0a8f --- /dev/null +++ b/packages/openspec/src/openspec3/index.ts @@ -0,0 +1,16 @@ +export * from "./OpenSpec3"; +export * from "./OS3Callbacks"; +export * from "./OS3Components"; +export * from "./OS3Encoding"; +export * from "./OS3Flows"; +export * from "./OS3Header"; +export * from "./OS3Link"; +export * from "./OS3MediaType"; +export * from "./OS3Operation"; +export * from "./OS3Parameter"; +export * from "./OS3Paths"; +export * from "./OS3RequestBody"; +export * from "./OS3Response"; +export * from "./OS3Schema"; +export * from "./OS3Security"; +export * from "./OS3Server"; diff --git a/packages/openspec/tsconfig.compile.json b/packages/openspec/tsconfig.compile.json new file mode 100644 index 00000000000..2cfb26f0dde --- /dev/null +++ b/packages/openspec/tsconfig.compile.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.compile.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib" + }, + "exclude": [ + "node_modules", + "test", + "lib", + "**/*.spec.ts" + ] +} diff --git a/packages/schema/package.json b/packages/schema/package.json index 8d3965baa4f..c629fb821df 100644 --- a/packages/schema/package.json +++ b/packages/schema/package.json @@ -16,6 +16,7 @@ ], "dependencies": { "@tsed/core": "6.0.0-beta.13", + "@tsed/openspec": "6.0.0-beta.13", "change-case": "4.1.1", "tslib": "2.0.1" }, diff --git a/packages/schema/src/decorators/operations/tags.ts b/packages/schema/src/decorators/operations/tags.ts index 3a59f7739f8..80a9f00139e 100644 --- a/packages/schema/src/decorators/operations/tags.ts +++ b/packages/schema/src/decorators/operations/tags.ts @@ -1,8 +1,8 @@ import {decorateMethodsOf, DecoratorTypes, UnsupportedDecoratorType} from "@tsed/core"; -import {JsonTag} from "../../interfaces/JsonOpenSpec"; +import {OpenSpecTag} from "@tsed/openspec"; import {JsonEntityFn} from "../common/jsonEntityFn"; -function mapTags(tags: (string | JsonTag)[]) { +function mapTags(tags: (string | OpenSpecTag)[]) { return tags.map((tag) => { if (typeof tag === "string") { return { @@ -35,7 +35,7 @@ function mapTags(tags: (string | JsonTag)[]) { * @classDecorator * @operation */ -export function Tags(...tags: (string | JsonTag)[]) { +export function Tags(...tags: (string | OpenSpecTag)[]) { return JsonEntityFn((store, args) => { switch (store.decoratorType) { case DecoratorTypes.METHOD: diff --git a/packages/schema/src/domain/JsonOperation.ts b/packages/schema/src/domain/JsonOperation.ts index d39cacff46c..30d51c8b103 100644 --- a/packages/schema/src/domain/JsonOperation.ts +++ b/packages/schema/src/domain/JsonOperation.ts @@ -1,6 +1,8 @@ import {deepExtends, uniq, uniqBy} from "@tsed/core"; +import {OpenSpecTag, OS3Operation} from "@tsed/openspec"; +import {OpenSpecSecurity} from "../../../openspec/src/common/OpenSpecSecurity"; import {HTTP_STATUS_MESSAGES} from "../constants/httpStatusMessages"; -import {JsonExternalDocumentation, JsonHeader, JsonSchemaOptions, JsonSecurityRequirement, JsonTag} from "../interfaces"; +import {JsonHeader, JsonSchemaOptions} from "../interfaces"; import {isSuccessStatus} from "../utils/isSuccessStatus"; import {JsonMap} from "./JsonMap"; import {JsonParameter} from "./JsonParameter"; @@ -17,20 +19,9 @@ export interface JsonMethodPath { [key: string]: any; } -export interface JsonOperationOptions { - tags: string[]; - summary: string; - description: string; +export interface JsonOperationOptions extends OS3Operation> { consumes: string[]; produces: string[]; - operationId: string; - parameters: JsonParameter[]; - deprecated: boolean; - security?: JsonSecurityRequirement[]; - responses: any; - externalDocs: JsonExternalDocumentation; - // callbacks?: {[callback: string]: ReferenceObject | CallbackObject}; - // servers?: ServerObject[]; } export class JsonOperation extends JsonMap { @@ -49,13 +40,13 @@ export class JsonOperation extends JsonMap { return this._status; } - tags(tags: JsonTag[]): this { + tags(tags: OpenSpecTag[]): this { super.set("tags", tags); return this; } - addTags(tags: JsonTag[]) { + addTags(tags: OpenSpecTag[]) { tags = uniqBy([...(this.get("tags") || []), ...tags], "name"); return this.tags(tags); @@ -120,7 +111,7 @@ export class JsonOperation extends JsonMap { return (status === "default" ? this.response : this.getResponses().get(String(status))) || new JsonResponse(); } - getHeadersOf(status: number): {[key: string]: JsonHeader} { + getHeadersOf(status: number): { [key: string]: JsonHeader } { return this.getResponseOf(status).get("headers") || {}; } @@ -128,7 +119,7 @@ export class JsonOperation extends JsonMap { return [...this.getResponseOf(status).get("content").keys()][0]; } - security(security: JsonSecurityRequirement): this { + security(security: OpenSpecSecurity): this { this.set("security", security); return this; diff --git a/packages/schema/src/domain/JsonParameter.ts b/packages/schema/src/domain/JsonParameter.ts index ce447c48f48..f19ecd3a7ab 100644 --- a/packages/schema/src/domain/JsonParameter.ts +++ b/packages/schema/src/domain/JsonParameter.ts @@ -1,21 +1,14 @@ import {Type} from "@tsed/core"; +import {OS3Parameter} from "@tsed/openspec"; import {JsonSchemaOptions} from "../interfaces"; import {NestedGenerics, popGenerics} from "../utils/generics"; import {serializeItem} from "../utils/serializeJsonSchema"; import {JsonMap} from "./JsonMap"; -import {isParameterType, JsonParameterTypes} from "./JsonParameterTypes"; +import {isParameterType} from "./JsonParameterTypes"; import {JsonSchema} from "./JsonSchema"; import {SpecTypes} from "./SpecTypes"; -export class JsonParameterOptions { - name: string; - description: string; - in: JsonParameterTypes | string; - required: boolean; - schema: JsonSchema; -} - -export class JsonParameter extends JsonMap implements NestedGenerics { +export class JsonParameter extends JsonMap> implements NestedGenerics { nestedGenerics: Type[][] = []; $schema: JsonSchema; diff --git a/packages/schema/src/domain/JsonRequestBody.ts b/packages/schema/src/domain/JsonRequestBody.ts index 8c6c982a045..3f5ef24c9a9 100644 --- a/packages/schema/src/domain/JsonRequestBody.ts +++ b/packages/schema/src/domain/JsonRequestBody.ts @@ -1,15 +1,9 @@ -import {JsonMediaType} from "../interfaces"; +import {OpenSpecHash, OS3MediaType, OS3RequestBody} from "@tsed/openspec"; import {toJsonMapCollection} from "../utils/toJsonMapCollection"; import {JsonMap} from "./JsonMap"; import {JsonSchema} from "./JsonSchema"; -export interface JsonRequestBodyOptions { - description: string; - content: { - [media: string]: JsonSchema; - }; - required: boolean; -} +export type JsonRequestBodyOptions = OS3RequestBody export class JsonRequestBody extends JsonMap { constructor(obj: Partial = {}) { @@ -24,7 +18,7 @@ export class JsonRequestBody extends JsonMap { return this; } - content(content: {[media: string]: JsonMediaType}) { + content(content: OpenSpecHash>) { this.set("content", toJsonMapCollection(content)); return this; diff --git a/packages/schema/src/domain/JsonResponse.ts b/packages/schema/src/domain/JsonResponse.ts index 41e9f202bde..741cb701065 100644 --- a/packages/schema/src/domain/JsonResponse.ts +++ b/packages/schema/src/domain/JsonResponse.ts @@ -1,4 +1,5 @@ -import {JsonHeader, JsonMediaType, JsonSchemaOptions} from "../interfaces"; +import {OpenSpecHash, OS3MediaType, OS3Response} from "@tsed/openspec"; +import {JsonHeader, JsonSchemaOptions} from "../interfaces"; import {mapHeaders} from "../utils/mapHeaders"; import {serializeItem} from "../utils/serializeJsonSchema"; import {toJsonMapCollection} from "../utils/toJsonMapCollection"; @@ -6,14 +7,7 @@ import {JsonMap} from "./JsonMap"; import {JsonSchema} from "./JsonSchema"; import {SpecTypes} from "./SpecTypes"; -export interface JsonResponseOptions { - description: string; - headers: {[header: string]: JsonHeader}; - content: { - [media: string]: JsonSchema; - }; - links: {[link: string]: any}; -} +export type JsonResponseOptions = OS3Response; export class JsonResponse extends JsonMap { $schema: JsonSchema; @@ -30,13 +24,13 @@ export class JsonResponse extends JsonMap { return this; } - headers(headers: {[header: string]: string | JsonHeader}): this { + headers(headers: OpenSpecHash): this { this.set("headers", mapHeaders(headers)); return this; } - content(content: {[media: string]: JsonMediaType}) { + content(content: OpenSpecHash>) { this.set("content", toJsonMapCollection(content)); return this; diff --git a/packages/schema/src/domain/JsonSchema.ts b/packages/schema/src/domain/JsonSchema.ts index 33f7771710b..8881547ef10 100644 --- a/packages/schema/src/domain/JsonSchema.ts +++ b/packages/schema/src/domain/JsonSchema.ts @@ -1,5 +1,11 @@ -import {classOf, Hooks, isArray, isClass, isFunction, MetadataTypes, nameOf, Type, uniq, ValueOf} from "@tsed/core"; -import {JSONSchema6, JSONSchema6Definition, JSONSchema6Type, JSONSchema6TypeName, JSONSchema6Version} from "json-schema"; +import {classOf, Hooks, isArray, isClass, isFunction, nameOf, Type, uniq, ValueOf} from "@tsed/core"; +import { + JSONSchema6, + JSONSchema6Definition, + JSONSchema6Type, + JSONSchema6TypeName, + JSONSchema6Version +} from "json-schema"; import {JsonSchemaOptions} from "../interfaces"; import {IgnoreCallback} from "../interfaces/IgnoreCallback"; import {NestedGenerics} from "../utils/generics"; @@ -29,7 +35,7 @@ function mapToJsonSchema(item: any): any { return item instanceof JsonSchema ? item : JsonSchema.from(item as any); } -function mapProperties(properties: {[p: string]: any}) { +function mapProperties(properties: { [p: string]: any }) { return Object.entries(properties).reduce((properties, [key, schema]) => { properties[toJsonRegex(key)] = isArray(schema) ? schema.map(mapToJsonSchema) : mapToJsonSchema(schema); @@ -349,7 +355,7 @@ export class JsonSchema extends Map implements NestedGenerics { * Omitting this keyword has the same behavior as an empty object. * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 */ - properties(properties: JsonSchema | {[key: string]: JsonSchemaObject}) { + properties(properties: JsonSchema | { [key: string]: JsonSchemaObject }) { super.set("properties", properties instanceof JsonSchema ? properties : mapProperties(properties)); return this; @@ -371,7 +377,7 @@ export class JsonSchema extends Map implements NestedGenerics { * Omitting this keyword has the same behavior as an empty object. * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 */ - patternProperties(patternProperties: {[p: string]: JsonSchemaObject | JsonSchema}) { + patternProperties(patternProperties: { [p: string]: JsonSchemaObject | JsonSchema }) { super.set("patternProperties", mapProperties(patternProperties)); return this; @@ -397,7 +403,7 @@ export class JsonSchema extends Map implements NestedGenerics { * Omitting this keyword has the same behavior as an empty object. * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 */ - dependencies(dependencies: {[p: string]: JSONSchema6Definition | JsonSchema | string[]}) { + dependencies(dependencies: { [p: string]: JSONSchema6Definition | JsonSchema | string[] }) { super.set("dependencies", mapProperties(dependencies)); return this; @@ -433,7 +439,7 @@ export class JsonSchema extends Map implements NestedGenerics { /** * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 */ - definitions(definitions: {[p: string]: JsonSchemaObject | JsonSchema}) { + definitions(definitions: { [p: string]: JsonSchemaObject | JsonSchema }) { super.set("definitions", mapProperties(definitions)); return this; diff --git a/packages/schema/src/interfaces/JsonOpenSpec.ts b/packages/schema/src/interfaces/JsonOpenSpec.ts index 6e4e5ce0a0a..7464b1fd96c 100644 --- a/packages/schema/src/interfaces/JsonOpenSpec.ts +++ b/packages/schema/src/interfaces/JsonOpenSpec.ts @@ -1,66 +1,8 @@ -import {JsonSchema} from "../domain"; +import {OS3Header} from "@tsed/openspec"; -export interface JsonHeader extends JsonParameterBase {} - -export interface JsonHeaders { - [key: string]: number | string | (JsonHeader & {value?: string | number}); -} - -export interface JsonExternalDocumentation { - description?: string; - url: string; -} - -export interface JsonSecurityRequirement { - [key: string]: string[]; -} - -export interface JsonParameterBase { - description?: string; - required?: boolean; - deprecated?: boolean; - allowEmptyValue?: boolean; - style?: string; - explode?: boolean; - allowReserved?: boolean; - schema?: JsonSchema; - example?: any; - examples?: { - [name: string]: JsonExample; - }; - content?: { - [media: string]: JsonMediaType; - }; +export interface JsonHeader extends OS3Header { } -export interface JsonExample { - summary?: string; - description?: string; - value?: any; - externalValue?: string; -} - -export interface JsonEncoding { - contentType?: string; - headers?: { - [header: string]: JsonHeader; - }; - style?: string; - explode?: boolean; - allowReserved?: boolean; -} - -export interface JsonMediaType { - schema?: JsonSchema; - example?: any; - examples?: { - [media: string]: JsonExample; - }; - encoding?: {[media: string]: JsonEncoding}; -} - -export interface JsonTag { - name: string; - description?: string; - externalDocs?: JsonExternalDocumentation; +export interface JsonHeaders { + [key: string]: number | string | (JsonHeader & { value?: string | number }); } diff --git a/reports/eslint/test-results-eslint.xml b/reports/eslint/test-results-eslint.xml new file mode 100644 index 00000000000..d3168bf51cf --- /dev/null +++ b/reports/eslint/test-results-eslint.xml @@ -0,0 +1,2832 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/reports/mocha/test-results-unit.xml b/reports/mocha/test-results-unit.xml new file mode 100644 index 00000000000..68a567d79ec --- /dev/null +++ b/reports/mocha/test-results-unit.xml @@ -0,0 +1,5221 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From bd05accf846ec3d94a5117bcc9a6ac052fffc3bd Mon Sep 17 00:00:00 2001 From: Romain Lenzotti Date: Sat, 10 Oct 2020 10:28:34 +0200 Subject: [PATCH 3/5] chore(schema): Update @tsed/schema with new OpenSpec interfaces --- .../src/decorators/common/description.spec.ts | 4 +- .../decorators/operations/consumes.spec.ts | 2 +- .../decorators/operations/deprecated.spec.ts | 2 +- .../src/decorators/operations/in.spec.ts | 4 +- .../decorators/operations/produces.spec.ts | 2 +- .../src/decorators/operations/returns.spec.ts | 16 +- packages/schema/src/domain/JsonOperation.ts | 9 +- packages/schema/src/domain/JsonParameter.ts | 8 +- packages/schema/src/domain/JsonRequestBody.ts | 2 +- packages/schema/src/domain/JsonResponse.ts | 9 +- packages/schema/src/domain/JsonSchema.ts | 18 +- packages/schema/src/index.ts | 1 + .../schema/src/interfaces/JsonOpenSpec.ts | 5 +- .../src/interfaces/JsonSchemaOptions.ts | 19 +- packages/schema/src/utils/getJsonSchema.ts | 2 +- packages/schema/src/utils/getSpec.spec.ts | 58 +++--- packages/schema/src/utils/getSpec.ts | 60 ++++-- packages/schema/src/utils/mergeOperation.ts | 20 +- packages/schema/src/utils/mergeSpec.spec.ts | 175 ++++++++++++++++++ packages/schema/src/utils/mergeSpec.ts | 81 ++++++++ .../schema/src/utils/operationIdFormatter.ts | 3 + .../schema/src/utils/serializeJsonSchema.ts | 4 +- 22 files changed, 408 insertions(+), 96 deletions(-) create mode 100644 packages/schema/src/utils/mergeSpec.spec.ts create mode 100644 packages/schema/src/utils/mergeSpec.ts diff --git a/packages/schema/src/decorators/common/description.spec.ts b/packages/schema/src/decorators/common/description.spec.ts index 91a1375eeb5..b420a7a5a49 100644 --- a/packages/schema/src/decorators/common/description.spec.ts +++ b/packages/schema/src/decorators/common/description.spec.ts @@ -169,8 +169,10 @@ describe("@Description", () => { method(@In("body") @Description("Description") payload: MyModel) {} } + const spec = getSpec(MyController, {specType: SpecTypes.OPENAPI}); + // THEN - expect(getSpec(MyController, {spec: SpecTypes.OPENAPI})).to.deep.equal({ + expect(spec).to.deep.equal({ components: { schemas: { MyModel: { diff --git a/packages/schema/src/decorators/operations/consumes.spec.ts b/packages/schema/src/decorators/operations/consumes.spec.ts index 8e2485a64d8..bd600c691f0 100644 --- a/packages/schema/src/decorators/operations/consumes.spec.ts +++ b/packages/schema/src/decorators/operations/consumes.spec.ts @@ -39,7 +39,7 @@ describe("Consumes", () => { get() {} } - expect(getSpec(MyController, {spec: SpecTypes.OPENAPI})).to.deep.eq({ + expect(getSpec(MyController, {specType: SpecTypes.OPENAPI})).to.deep.eq({ tags: [ { name: "MyController" diff --git a/packages/schema/src/decorators/operations/deprecated.spec.ts b/packages/schema/src/decorators/operations/deprecated.spec.ts index 503da897a45..99a9a8a2d49 100644 --- a/packages/schema/src/decorators/operations/deprecated.spec.ts +++ b/packages/schema/src/decorators/operations/deprecated.spec.ts @@ -39,7 +39,7 @@ describe("Deprecated", () => { get() {} } - expect(getSpec(MyController, {spec: SpecTypes.OPENAPI})).to.deep.eq({ + expect(getSpec(MyController, {specType: SpecTypes.OPENAPI})).to.deep.eq({ tags: [ { name: "MyController" diff --git a/packages/schema/src/decorators/operations/in.spec.ts b/packages/schema/src/decorators/operations/in.spec.ts index 1bd94852b0d..85a84faac26 100644 --- a/packages/schema/src/decorators/operations/in.spec.ts +++ b/packages/schema/src/decorators/operations/in.spec.ts @@ -10,7 +10,7 @@ describe("In", () => { // THEN getSpec(Controller, { - spec: SpecTypes.SWAGGER + specType: SpecTypes.SWAGGER }); const paramSchema = JsonEntityStore.from(Controller, "method", 0); @@ -42,7 +42,7 @@ describe("In", () => { // THEN getSpec(Controller, { - spec: SpecTypes.SWAGGER + specType: SpecTypes.SWAGGER }); const paramSchema = JsonEntityStore.from(Controller, "method", 0); diff --git a/packages/schema/src/decorators/operations/produces.spec.ts b/packages/schema/src/decorators/operations/produces.spec.ts index a2b3c2b9d6f..2398751d0ec 100644 --- a/packages/schema/src/decorators/operations/produces.spec.ts +++ b/packages/schema/src/decorators/operations/produces.spec.ts @@ -39,7 +39,7 @@ describe("Produces", () => { get() {} } - expect(getSpec(MyController, {spec: SpecTypes.OPENAPI})).to.deep.eq({ + expect(getSpec(MyController, {specType: SpecTypes.OPENAPI})).to.deep.eq({ tags: [ { name: "MyController" diff --git a/packages/schema/src/decorators/operations/returns.spec.ts b/packages/schema/src/decorators/operations/returns.spec.ts index 592ecc5053b..be92d1d8b33 100644 --- a/packages/schema/src/decorators/operations/returns.spec.ts +++ b/packages/schema/src/decorators/operations/returns.spec.ts @@ -12,7 +12,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -48,7 +48,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -93,7 +93,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -141,7 +141,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ tags: [ @@ -184,7 +184,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -276,7 +276,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -321,7 +321,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { @@ -396,7 +396,7 @@ describe("@Returns", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { diff --git a/packages/schema/src/domain/JsonOperation.ts b/packages/schema/src/domain/JsonOperation.ts index 30d51c8b103..ee5ce23505d 100644 --- a/packages/schema/src/domain/JsonOperation.ts +++ b/packages/schema/src/domain/JsonOperation.ts @@ -1,6 +1,5 @@ import {deepExtends, uniq, uniqBy} from "@tsed/core"; -import {OpenSpecTag, OS3Operation} from "@tsed/openspec"; -import {OpenSpecSecurity} from "../../../openspec/src/common/OpenSpecSecurity"; +import {OpenSpecSecurity, OpenSpecTag, OS3Operation} from "@tsed/openspec"; import {HTTP_STATUS_MESSAGES} from "../constants/httpStatusMessages"; import {JsonHeader, JsonSchemaOptions} from "../interfaces"; import {isSuccessStatus} from "../utils/isSuccessStatus"; @@ -111,7 +110,7 @@ export class JsonOperation extends JsonMap { return (status === "default" ? this.response : this.getResponses().get(String(status))) || new JsonResponse(); } - getHeadersOf(status: number): { [key: string]: JsonHeader } { + getHeadersOf(status: number): {[key: string]: JsonHeader} { return this.getResponseOf(status).get("headers") || {}; } @@ -214,14 +213,14 @@ export class JsonOperation extends JsonMap { if (bodyParameters.length) { const parameter = buildSchemaFromBodyParameters(bodyParameters); - if (options.spec === SpecTypes.OPENAPI) { + if (options.specType === SpecTypes.OPENAPI) { operation.requestBody = toRequestBody(this, parameter).toJSON(options); } else { operation.parameters.push(toJsonParameter(parameter).toJSON(options)); } } - if (options.spec === SpecTypes.OPENAPI) { + if (options.specType === SpecTypes.OPENAPI) { delete operation.consumes; delete operation.produces; } diff --git a/packages/schema/src/domain/JsonParameter.ts b/packages/schema/src/domain/JsonParameter.ts index f19ecd3a7ab..8595b4992fd 100644 --- a/packages/schema/src/domain/JsonParameter.ts +++ b/packages/schema/src/domain/JsonParameter.ts @@ -59,7 +59,7 @@ export class JsonParameter extends JsonMap> implements if (!jsonSchema.$ref && (this.get("in") === "path" || Object.keys(jsonSchema).length === 1)) { parameter.type = jsonSchema.type; - } else if (options.spec === SpecTypes.SWAGGER && this.get("in") === "query") { + } else if (options.specType === SpecTypes.SWAGGER && this.get("in") === "query") { if (jsonSchema.$ref) { return this.refToParameters(parameter, options, schemas); } @@ -87,10 +87,10 @@ export class JsonParameter extends JsonMap> implements } private refToParameters(parameter: any, options: JsonSchemaOptions, schemas: any) { - const schema = options.schemas[this.$schema.getName()]; + const schema = options.schemas![this.$schema.getName()]; - if (options.schemas[this.$schema.getName()] && !schemas[this.$schema.getName()]) { - delete options.schemas[this.$schema.getName()]; + if (options.schemas![this.$schema.getName()] && !schemas[this.$schema.getName()]) { + delete options.schemas![this.$schema.getName()]; } return Object.entries(schema.properties || {}).reduce((params, [key, prop]: [string, any]) => { diff --git a/packages/schema/src/domain/JsonRequestBody.ts b/packages/schema/src/domain/JsonRequestBody.ts index 3f5ef24c9a9..a3a317b0b03 100644 --- a/packages/schema/src/domain/JsonRequestBody.ts +++ b/packages/schema/src/domain/JsonRequestBody.ts @@ -3,7 +3,7 @@ import {toJsonMapCollection} from "../utils/toJsonMapCollection"; import {JsonMap} from "./JsonMap"; import {JsonSchema} from "./JsonSchema"; -export type JsonRequestBodyOptions = OS3RequestBody +export type JsonRequestBodyOptions = OS3RequestBody; export class JsonRequestBody extends JsonMap { constructor(obj: Partial = {}) { diff --git a/packages/schema/src/domain/JsonResponse.ts b/packages/schema/src/domain/JsonResponse.ts index 741cb701065..09c9333bcaa 100644 --- a/packages/schema/src/domain/JsonResponse.ts +++ b/packages/schema/src/domain/JsonResponse.ts @@ -1,4 +1,5 @@ -import {OpenSpecHash, OS3MediaType, OS3Response} from "@tsed/openspec"; +import {OS3MediaType, OS3Response} from "@tsed/openspec"; +import {HashOf} from "@tsed/core"; import {JsonHeader, JsonSchemaOptions} from "../interfaces"; import {mapHeaders} from "../utils/mapHeaders"; import {serializeItem} from "../utils/serializeJsonSchema"; @@ -24,13 +25,13 @@ export class JsonResponse extends JsonMap { return this; } - headers(headers: OpenSpecHash): this { + headers(headers: HashOf): this { this.set("headers", mapHeaders(headers)); return this; } - content(content: OpenSpecHash>) { + content(content: HashOf>) { this.set("content", toJsonMapCollection(content)); return this; @@ -50,7 +51,7 @@ export class JsonResponse extends JsonMap { toJSON(options: JsonSchemaOptions = {}): any { const response = super.toJSON(options); - if (options.spec !== SpecTypes.OPENAPI) { + if (options.specType !== SpecTypes.OPENAPI) { delete response.content; response.schema = serializeItem(this.$schema, options); diff --git a/packages/schema/src/domain/JsonSchema.ts b/packages/schema/src/domain/JsonSchema.ts index 8881547ef10..aa92e0ead84 100644 --- a/packages/schema/src/domain/JsonSchema.ts +++ b/packages/schema/src/domain/JsonSchema.ts @@ -1,11 +1,5 @@ import {classOf, Hooks, isArray, isClass, isFunction, nameOf, Type, uniq, ValueOf} from "@tsed/core"; -import { - JSONSchema6, - JSONSchema6Definition, - JSONSchema6Type, - JSONSchema6TypeName, - JSONSchema6Version -} from "json-schema"; +import {JSONSchema6, JSONSchema6Definition, JSONSchema6Type, JSONSchema6TypeName, JSONSchema6Version} from "json-schema"; import {JsonSchemaOptions} from "../interfaces"; import {IgnoreCallback} from "../interfaces/IgnoreCallback"; import {NestedGenerics} from "../utils/generics"; @@ -35,7 +29,7 @@ function mapToJsonSchema(item: any): any { return item instanceof JsonSchema ? item : JsonSchema.from(item as any); } -function mapProperties(properties: { [p: string]: any }) { +function mapProperties(properties: {[p: string]: any}) { return Object.entries(properties).reduce((properties, [key, schema]) => { properties[toJsonRegex(key)] = isArray(schema) ? schema.map(mapToJsonSchema) : mapToJsonSchema(schema); @@ -355,7 +349,7 @@ export class JsonSchema extends Map implements NestedGenerics { * Omitting this keyword has the same behavior as an empty object. * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18 */ - properties(properties: JsonSchema | { [key: string]: JsonSchemaObject }) { + properties(properties: JsonSchema | {[key: string]: JsonSchemaObject}) { super.set("properties", properties instanceof JsonSchema ? properties : mapProperties(properties)); return this; @@ -377,7 +371,7 @@ export class JsonSchema extends Map implements NestedGenerics { * Omitting this keyword has the same behavior as an empty object. * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19 */ - patternProperties(patternProperties: { [p: string]: JsonSchemaObject | JsonSchema }) { + patternProperties(patternProperties: {[p: string]: JsonSchemaObject | JsonSchema}) { super.set("patternProperties", mapProperties(patternProperties)); return this; @@ -403,7 +397,7 @@ export class JsonSchema extends Map implements NestedGenerics { * Omitting this keyword has the same behavior as an empty object. * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21 */ - dependencies(dependencies: { [p: string]: JSONSchema6Definition | JsonSchema | string[] }) { + dependencies(dependencies: {[p: string]: JSONSchema6Definition | JsonSchema | string[]}) { super.set("dependencies", mapProperties(dependencies)); return this; @@ -439,7 +433,7 @@ export class JsonSchema extends Map implements NestedGenerics { /** * @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1 */ - definitions(definitions: { [p: string]: JsonSchemaObject | JsonSchema }) { + definitions(definitions: {[p: string]: JsonSchemaObject | JsonSchema}) { super.set("definitions", mapProperties(definitions)); return this; diff --git a/packages/schema/src/index.ts b/packages/schema/src/index.ts index ddeece5604b..d9fc91f777d 100644 --- a/packages/schema/src/index.ts +++ b/packages/schema/src/index.ts @@ -3,6 +3,7 @@ export * from "./utils/getJsonType"; export * from "./utils/getPropertiesStores"; export * from "./utils/getOperationsStores"; export * from "./utils/getSpec"; +export * from "./utils/mergeSpec"; export * from "./utils/generics"; export * from "./utils/mapHeaders"; export * from "./utils/isSuccessStatus"; diff --git a/packages/schema/src/interfaces/JsonOpenSpec.ts b/packages/schema/src/interfaces/JsonOpenSpec.ts index 7464b1fd96c..5a3f99a3f48 100644 --- a/packages/schema/src/interfaces/JsonOpenSpec.ts +++ b/packages/schema/src/interfaces/JsonOpenSpec.ts @@ -1,8 +1,7 @@ import {OS3Header} from "@tsed/openspec"; -export interface JsonHeader extends OS3Header { -} +export interface JsonHeader extends OS3Header {} export interface JsonHeaders { - [key: string]: number | string | (JsonHeader & { value?: string | number }); + [key: string]: number | string | (JsonHeader & {value?: string | number}); } diff --git a/packages/schema/src/interfaces/JsonSchemaOptions.ts b/packages/schema/src/interfaces/JsonSchemaOptions.ts index 9cf73c06296..ff852c96e08 100644 --- a/packages/schema/src/interfaces/JsonSchemaOptions.ts +++ b/packages/schema/src/interfaces/JsonSchemaOptions.ts @@ -1,10 +1,23 @@ +import {OpenSpecHash, OS2Schema, OS3Schema} from "@tsed/openspec"; import {SpecTypes} from "../domain/SpecTypes"; export interface JsonSchemaOptions { + /** + * Map properties with the alias name. By default: false + */ useAlias?: boolean; - schemas?: any; - root?: any; - spec?: SpecTypes; + /** + * Reference to Schema Object. + */ + schemas?: OpenSpecHash; + /** + * Is root object. + */ + root?: boolean; + /** + * Define Spec types level + */ + specType?: SpecTypes; [key: string]: any; } diff --git a/packages/schema/src/utils/getJsonSchema.ts b/packages/schema/src/utils/getJsonSchema.ts index b8ce76c506e..d6b1de857b5 100644 --- a/packages/schema/src/utils/getJsonSchema.ts +++ b/packages/schema/src/utils/getJsonSchema.ts @@ -33,7 +33,7 @@ export function getJsonSchema(model: Type | JsonEntityStore, options: JsonS options = { ...options, root: true, - spec: options.spec || SpecTypes.JSON, + specType: options.specType || SpecTypes.JSON, schemas: {} }; diff --git a/packages/schema/src/utils/getSpec.spec.ts b/packages/schema/src/utils/getSpec.spec.ts index 27c27e37fa9..7495a40b0a8 100644 --- a/packages/schema/src/utils/getSpec.spec.ts +++ b/packages/schema/src/utils/getSpec.spec.ts @@ -56,7 +56,7 @@ describe("getSpec()", () => { // THEN const spec = getSpec(Controller, { - spec: SpecTypes.SWAGGER + specType: SpecTypes.SWAGGER }); expect(await validate(spec)).to.eq(true); }); @@ -68,7 +68,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(await validate(spec)).to.eq(true); expect(spec).to.deep.equal({ @@ -120,7 +120,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(await validate(spec)).to.eq(true); expect(spec).to.deep.equal({ @@ -173,7 +173,7 @@ describe("getSpec()", () => { // THEN const spec = getSpec(Controller, { - spec: SpecTypes.OPENAPI + specType: SpecTypes.OPENAPI }); expect(spec).to.deep.eq({ paths: { @@ -215,7 +215,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -268,7 +268,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -327,7 +327,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ components: { @@ -388,7 +388,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -437,7 +437,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ paths: { @@ -487,7 +487,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -535,7 +535,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ paths: { @@ -592,7 +592,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { @@ -649,7 +649,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ components: { @@ -710,7 +710,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { @@ -771,7 +771,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { @@ -825,7 +825,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -881,7 +881,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(await validate(spec)).to.eq(true); expect(spec).to.deep.equal({ tags: [ @@ -940,7 +940,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(await validate(spec, SpecTypes.OPENAPI)).to.eq(true); expect(spec).to.deep.equal({ tags: [ @@ -1024,8 +1024,8 @@ describe("getSpec()", () => { } // THEN - const spec1 = getSpec(Controller1, {spec: SpecTypes.SWAGGER}); - const spec2 = getSpec(Controller2, {spec: SpecTypes.SWAGGER}); + const spec1 = getSpec(Controller1, {specType: SpecTypes.SWAGGER}); + const spec2 = getSpec(Controller2, {specType: SpecTypes.SWAGGER}); expect(spec1).to.deep.equal({ definitions: { @@ -1145,7 +1145,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -1182,7 +1182,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ tags: [ @@ -1222,7 +1222,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ tags: [ @@ -1262,7 +1262,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ tags: [ @@ -1321,7 +1321,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { @@ -1419,7 +1419,7 @@ describe("getSpec()", () => { }); // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ components: { @@ -1528,8 +1528,8 @@ describe("getSpec()", () => { } // THEN - const spec2 = getSpec(Controller2, {spec: SpecTypes.SWAGGER}); - const spec = getSpec(Controller, {spec: SpecTypes.SWAGGER}); + const spec2 = getSpec(Controller2, {specType: SpecTypes.SWAGGER}); + const spec = getSpec(Controller, {specType: SpecTypes.SWAGGER}); expect(spec).to.deep.equal({ definitions: { @@ -1668,7 +1668,7 @@ describe("getSpec()", () => { } // THEN - const spec = getSpec(Controller, {spec: SpecTypes.OPENAPI}); + const spec = getSpec(Controller, {specType: SpecTypes.OPENAPI}); expect(spec).to.deep.equal({ components: { diff --git a/packages/schema/src/utils/getSpec.ts b/packages/schema/src/utils/getSpec.ts index 431c2455f96..9aa1fd9da56 100644 --- a/packages/schema/src/utils/getSpec.ts +++ b/packages/schema/src/utils/getSpec.ts @@ -1,4 +1,5 @@ import {cleanObject, Type, uniqBy} from "@tsed/core"; +import {OpenSpec2, OpenSpec3} from "@tsed/openspec"; import {JsonEntityStore} from "../domain/JsonEntityStore"; import {SpecTypes} from "../domain/SpecTypes"; import {JsonSchemaOptions} from "../interfaces"; @@ -8,26 +9,39 @@ import {mergeOperation} from "./mergeOperation"; import {operationIdFormatter} from "./operationIdFormatter"; export interface SpecSerializerOptions extends JsonSchemaOptions { + specType?: SpecTypes.SWAGGER | SpecTypes.OPENAPI; /** * Paths */ paths?: any; /** - * + * Root path. This paths will be added to all generated paths Object. */ rootPath?: string; /** - * - * @param target - * @param propertyKey + * A function to generate the operationId. */ operationIdFormatter?: (name: string, propertyKey: string, path: string) => string; /** - * + * A pattern to generate the operationId. */ operationIdPattern?: string; } +export interface OS3SpecSerializerOptions extends SpecSerializerOptions { + /** + * Define Spec types level + */ + specType: SpecTypes.OPENAPI; +} + +export interface OS2SpecSerializerOptions extends SpecSerializerOptions { + /** + * Define Spec types level + */ + specType: SpecTypes.SWAGGER; +} + const caches: Map, Map> = new Map(); function get(model: Type, options: any, cb: any) { @@ -46,25 +60,39 @@ function get(model: Type, options: any, cb: any) { } /** - * Return the swagger or open spec for the given class + * Return the swagger or open spec for the given class. + * @param model + * @param options + */ +export function getSpec(model: Type, options: OS2SpecSerializerOptions): Partial; +export function getSpec(model: Type): Partial; +export function getSpec(model: Type, options: SpecSerializerOptions): Partial; +/** + * Return the swagger or open spec for the given class. * @param model * @param options */ -export function getSpec(model: Type, options: SpecSerializerOptions = {}) { - if (!options.spec || options.spec === SpecTypes.JSON) { - options.spec = SpecTypes.SWAGGER; +export function getSpec(model: Type, options: OS3SpecSerializerOptions): Partial; +/** + * Return the swagger or open spec for the given class. + * @param model + * @param options + */ +export function getSpec(model: Type, options: SpecSerializerOptions = {specType: SpecTypes.SWAGGER}): Partial { + if (!options.specType) { + options.specType = SpecTypes.SWAGGER; } options = { - operationIdFormatter: options.operationIdFormatter || operationIdFormatter(options.operationIdPattern), ...options, + operationIdFormatter: options.operationIdFormatter || operationIdFormatter(options.operationIdPattern), root: false, - spec: options.spec + specType: options.specType }; return get(model, options, () => { const store = JsonEntityStore.from(model); - const {spec = SpecTypes.SWAGGER, schemas = {}, paths = {}, rootPath = "/", tags = []} = options; + const {specType = SpecTypes.SWAGGER, schemas = {}, paths = {}, rootPath = "/", tags = []} = options; const ctrlPath = store.path; const defaultTags = cleanObject({ name: store.schema.getName(), @@ -74,7 +102,7 @@ export function getSpec(model: Type, options: SpecSerializerOptions = {}) { const specJson: any = {paths}; getOperationsStores(model).forEach((operationStore) => { - const operation = operationStore.operation!.toJSON({...options, spec, schemas}); + const operation = operationStore.operation!.toJSON({...options, specType, schemas}); operationStore.operation!.operationPaths.forEach(({path, method}: {path: string; method: string}) => { if (method) { @@ -84,9 +112,9 @@ export function getSpec(model: Type, options: SpecSerializerOptions = {}) { method, defaultTags, tags, - spec, + specType, operationId: (path: string) => - options.operationIdFormatter?.( + options.operationIdFormatter!( operationStore.parent.schema.get("name") || operationStore.parent.targetName, operationStore.propertyName, path @@ -99,7 +127,7 @@ export function getSpec(model: Type, options: SpecSerializerOptions = {}) { specJson.tags = uniqBy(tags, "name"); if (Object.keys(schemas).length) { - if (spec === SpecTypes.OPENAPI) { + if (specType === SpecTypes.OPENAPI) { specJson.components = { schemas }; diff --git a/packages/schema/src/utils/mergeOperation.ts b/packages/schema/src/utils/mergeOperation.ts index 449dc3366a5..925aef62589 100644 --- a/packages/schema/src/utils/mergeOperation.ts +++ b/packages/schema/src/utils/mergeOperation.ts @@ -1,18 +1,34 @@ import {SpecTypes} from "../domain/SpecTypes"; import {concatParameters} from "./concatParameters"; import {getJsonPathParameters} from "./getJsonPathParameters"; +/** + * @ignore + */ +export interface MergeOperationOptions { + rootPath: string; + specType: SpecTypes; + operationId: (path: string) => string | undefined; + defaultTags: string[]; + tags: string[]; + path: string; + method: string; +} /** * @ignore */ -export function mergeOperation(obj: any, operation: any, {rootPath, spec, operationId, defaultTags, tags, path, method}: any) { +export function mergeOperation( + obj: any, + operation: any, + {rootPath, specType, operationId, defaultTags, tags, path, method}: MergeOperationOptions +) { return getJsonPathParameters(rootPath, path).reduce((obj, {path, parameters}) => { parameters = concatParameters(parameters, operation); path = path ? path : "/"; const operationTags = operation.tags?.length ? operation.tags : [defaultTags]; - if (spec === SpecTypes.OPENAPI) { + if (specType === SpecTypes.OPENAPI) { parameters = parameters.map(({type, ...param}) => { if (type) { return { diff --git a/packages/schema/src/utils/mergeSpec.spec.ts b/packages/schema/src/utils/mergeSpec.spec.ts new file mode 100644 index 00000000000..a3b12bd7fa2 --- /dev/null +++ b/packages/schema/src/utils/mergeSpec.spec.ts @@ -0,0 +1,175 @@ +import {OpenSpec2} from "@tsed/openspec"; +import {expect} from "chai"; +import {mergeSpec} from "./mergeSpec"; + +describe("mergeSpec", () => { + describe("security", () => { + it("should merge spec", () => { + const spec1: OpenSpec2 = { + swagger: "2.0", + paths: { + "/get": { + get: { + operationId: "id", + security: [ + { + openid: ["profile", "email"] + }, + { + ga: ["profile", "email"] + } + ], + responses: {} + } + } + } + }; + + const spec2: OpenSpec2 = { + swagger: "2.0", + paths: { + "/get": { + get: { + operationId: "id", + security: [ + { + fb: ["profile", "email"], + openid: ["profile", "email"] + }, + { + ga: ["profile", "email", "custom"] + } + ], + responses: {} + } + } + } + }; + + expect(mergeSpec(spec1, spec2)).to.deep.eq({ + paths: { + "/get": { + get: { + operationId: "id", + responses: {}, + security: [ + { + fb: ["profile", "email"], + openid: ["profile", "email"] + }, + { + ga: ["profile", "email", "custom"] + } + ] + } + } + }, + swagger: "2.0" + }); + }); + }); + describe("oneOf", () => { + it("should merge spec", () => { + const spec1: OpenSpec2 = { + swagger: "2.0", + paths: { + "/get": { + get: { + operationId: "id", + responses: { + "200": { + description: "description", + schema: { + type: "object", + properties: { + test: { + allOf: [ + { + type: "string" + }, + { + type: "number" + } + ] + } + } + } + } + } + } + } + } + }; + + const spec2: OpenSpec2 = { + swagger: "2.0", + paths: { + "/get": { + get: { + operationId: "id", + responses: { + "200": { + description: "description", + schema: { + type: "object", + properties: { + test: { + allOf: [ + { + type: "string" + }, + { + type: "number", + minimum: 1 + }, + { + type: "boolean" + } + ] + } + } + } + } + } + } + } + } + }; + + expect(mergeSpec(spec1, spec2)).to.deep.eq({ + paths: { + "/get": { + get: { + operationId: "id", + responses: { + "200": { + description: "description", + schema: { + properties: { + test: { + allOf: [ + { + type: "string" + }, + { + minimum: 1, + type: "number" + }, + { + type: "boolean" + } + ] + } + }, + type: "object" + } + } + } + } + } + }, + swagger: "2.0" + }); + }); + }); +}); diff --git a/packages/schema/src/utils/mergeSpec.ts b/packages/schema/src/utils/mergeSpec.ts new file mode 100644 index 00000000000..47cd53a6ed6 --- /dev/null +++ b/packages/schema/src/utils/mergeSpec.ts @@ -0,0 +1,81 @@ +import {cleanObject, deepExtends} from "@tsed/core"; +import {OpenSpec2, OpenSpec3} from "@tsed/openspec"; + +/** + * @ignore + */ +export const defaultReducer = (collection: any[], value: any) => { + if (collection.indexOf(value) === -1) { + collection.push(value); + } + + return collection; +}; + +/** + * @ignore + */ +export const schemesReducer = (collection: any[], value: any) => { + const current = collection.find((current) => current.type === value.type); + + if (current) { + deepExtends(current, value); + } else { + collection.push(value); + } + + return collection; +}; + +/** + * @ignore + */ +export const parameters = (collection: any[], value: any) => { + const current = collection.find((current) => current.in === value.in && current.name === value.name); + + if (current) { + deepExtends(current, value); + } else { + collection.push(value); + } + + return collection; +}; + +/** + * @ignore + */ +export const security = (collection: any[], value: any) => { + const current = collection.find((current: any): any => { + return Object.keys(value).find((key) => !!current[key]); + }); + + if (current) { + deepExtends(current, value, {default: defaultReducer}); + } else { + collection.push(value); + } + + return collection; +}; + +/** + * @ignore + */ +const SPEC_REDUCERS = { + default: defaultReducer, + security, + parameters, + oneOf: schemesReducer, + anyOf: schemesReducer, + allOf: schemesReducer +}; + +/** + * Merge two spec + * @param spec + * @param input + */ +export function mergeSpec(spec: Partial, input: Partial): Partial { + return cleanObject(deepExtends(spec, input, SPEC_REDUCERS)); +} diff --git a/packages/schema/src/utils/operationIdFormatter.ts b/packages/schema/src/utils/operationIdFormatter.ts index 02cd483113b..ec593ab8420 100644 --- a/packages/schema/src/utils/operationIdFormatter.ts +++ b/packages/schema/src/utils/operationIdFormatter.ts @@ -1,5 +1,8 @@ import {camelCase} from "change-case"; +/** + * @ignore + */ export function operationIdFormatter(pattern = "%c.%m") { const OPERATION_IDS = new Map(); diff --git a/packages/schema/src/utils/serializeJsonSchema.ts b/packages/schema/src/utils/serializeJsonSchema.ts index a4f6c562fc7..4c072a37379 100644 --- a/packages/schema/src/utils/serializeJsonSchema.ts +++ b/packages/schema/src/utils/serializeJsonSchema.ts @@ -48,7 +48,7 @@ export function createRef(value: any, options: JsonSchemaOptions = {}) { ); } - const {host = `#/${options.spec === "openapi3" ? "components/schemas" : "definitions"}`} = options; + const {host = `#/${options.specType === "openapi3" ? "components/schemas" : "definitions"}`} = options; return { $ref: `${host}/${name}` @@ -185,7 +185,7 @@ export function serializeJsonSchema(schema: JsonSchema, options: JsonSchemaOptio value = schema.getJsonType(); } - if (key === "examples" && isObject(value) && options.spec !== SpecTypes.SWAGGER) { + if (key === "examples" && isObject(value) && options.specType !== SpecTypes.SWAGGER) { value = Object.values(value); } From b10d6a0cdb36f1fed5e2bbb2316b2fda7d6de159 Mon Sep 17 00:00:00 2001 From: Romain Lenzotti Date: Sat, 10 Oct 2020 10:38:54 +0200 Subject: [PATCH 4/5] chore(swagger): Refactoring swagger package --- .../platform-test-utils/src/tests/testAuth.ts | 1 - packages/swagger/package.json | 7 +- packages/swagger/readme.md | 8 +- .../swagger/src/interfaces/SwaggerSettings.ts | 42 ++--- .../src/services/SwaggerService.spec.ts | 5 +- .../swagger/src/services/SwaggerService.ts | 123 ++++--------- .../swagger/src/utils/getSpecType.spec.ts | 17 ++ packages/swagger/src/utils/getSpecType.ts | 10 ++ packages/swagger/src/utils/index.spec.ts | 108 ----------- packages/swagger/src/utils/index.ts | 169 +----------------- packages/swagger/src/utils/mapOpenSpec.ts | 30 ++++ packages/swagger/src/utils/mapOpenSpec2.ts | 42 +++++ packages/swagger/src/utils/mapOpenSpec3.ts | 18 ++ packages/swagger/src/utils/mapOpenSpecInfo.ts | 14 ++ packages/swagger/test/swagger.errors.spec.ts | 1 - .../swagger/test/swagger.integration.spec.ts | 10 +- packages/swagger/test/swagger.query.spec.ts | 1 - yarn.lock | 5 - 18 files changed, 203 insertions(+), 408 deletions(-) create mode 100644 packages/swagger/src/utils/getSpecType.spec.ts create mode 100644 packages/swagger/src/utils/getSpecType.ts delete mode 100644 packages/swagger/src/utils/index.spec.ts create mode 100644 packages/swagger/src/utils/mapOpenSpec.ts create mode 100644 packages/swagger/src/utils/mapOpenSpec2.ts create mode 100644 packages/swagger/src/utils/mapOpenSpec3.ts create mode 100644 packages/swagger/src/utils/mapOpenSpecInfo.ts diff --git a/packages/platform-test-utils/src/tests/testAuth.ts b/packages/platform-test-utils/src/tests/testAuth.ts index be7973a37ef..d58f361d7d9 100644 --- a/packages/platform-test-utils/src/tests/testAuth.ts +++ b/packages/platform-test-utils/src/tests/testAuth.ts @@ -274,7 +274,6 @@ export function testAuth(options: PlatformTestOptions) { } }, produces: ["application/json"], - securityDefinitions: {}, swagger: "2.0", tags: [ { diff --git a/packages/swagger/package.json b/packages/swagger/package.json index 6f8c33ad8e2..78cc7880dfa 100644 --- a/packages/swagger/package.json +++ b/packages/swagger/package.json @@ -13,11 +13,14 @@ "tslib": "2.0.1" }, "peerDependencies": { - "@types/swagger-schema-official": "^2.0.21" + "@tsed/common": "6.0.0-beta.13", + "@tsed/openspec": "6.0.0-beta.13", + "@tsed/schema": "6.0.0-beta.13" }, "private": false, "devDependencies": { "@tsed/common": "6.0.0-beta.13", - "@types/swagger-schema-official": "2.0.21" + "@tsed/openspec": "6.0.0-beta.13", + "@tsed/schema": "6.0.0-beta.13" } } \ No newline at end of file diff --git a/packages/swagger/readme.md b/packages/swagger/readme.md index 4dc80e4fae0..81ccc4fc31d 100644 --- a/packages/swagger/readme.md +++ b/packages/swagger/readme.md @@ -19,7 +19,7 @@ A package of Ts.ED framework. See website: https://tsed.io/#/tutorials/swagger Before using the Swagger, we have to install the [swagger-ui-express](https://www.npmjs.com/package/swagger-ui-express) module. ```bash -npm install --save @types/swagger-schema-official @tsed/swagger +npm install --save @tsed/swagger ``` Then add the following configuration in your Server: @@ -33,7 +33,7 @@ const rootDir = resolve(__dirname) @Configuration({ rootDir, swagger: [{ - path: "/api-docs" + path: "/api-docs" }] }) export class Server { @@ -46,7 +46,6 @@ Normally, Swagger-ui is ready. You can start your server and check if it work fi > Note: Ts.ED will print the swagger url in the console. - ### Swagger options Some options is available to configure Swagger-ui, Ts.ED and the default spec information. @@ -54,6 +53,7 @@ Some options is available to configure Swagger-ui, Ts.ED and the default spec in Key | Example | Description ---|---|--- path | `/api-doc` | The url subpath to access to the documentation. +specVersion | `2.0`, `3.0.1` | The spec version. doc | `hidden-doc` | The documentation key used by `@Docs` decorator to create several swagger documentations. cssPath | `${rootDir}/spec/style.css` | The path to the CSS file. jsPath | `${rootDir}/spec/main.js` | The path to the JS file. @@ -63,8 +63,6 @@ specPath | `${rootDir}/spec/swagger.base.json` | Load the base spec documentatio outFile | `${rootDir}/spec/swagger.json` | Write the `swagger.json` spec documentation on the specified path. hidden | `true` | Hide the documentation in the dropdown explorer list. options | Swagger-UI options | SwaggerUI options. See (https://github.com/swagger-api/swagger-ui/blob/HEAD/docs/usage/configuration.md) -operationIdFormat | `%c.%m` | Format of operationId field (`%c`: class name, `%m`: method name). - ### Multi documentations diff --git a/packages/swagger/src/interfaces/SwaggerSettings.ts b/packages/swagger/src/interfaces/SwaggerSettings.ts index ee25547f029..216b875dc1e 100644 --- a/packages/swagger/src/interfaces/SwaggerSettings.ts +++ b/packages/swagger/src/interfaces/SwaggerSettings.ts @@ -1,4 +1,4 @@ -import {BodyParameter, ExternalDocs, Info, Path, QueryParameter, Response, Schema, Security, Tag} from "swagger-schema-official"; +import {OpenSpec2, OpenSpec3, OpenSpecVersions, OS2Versions, OS3Versions} from "@tsed/openspec"; export interface SwaggerUIOptions { configUrl?: string; @@ -12,25 +12,7 @@ export interface SwaggerUIOptions { [key: string]: any; } -export interface SwaggerSpec { - swagger?: string; - info?: Info; - externalDocs?: ExternalDocs; - host?: string; - basePath?: string; - schemes?: string[]; - consumes?: string[]; - produces?: string[]; - paths?: {[pathName: string]: Path}; - definitions?: {[definitionsName: string]: Schema}; - parameters?: {[parameterName: string]: BodyParameter | QueryParameter}; - responses?: {[responseName: string]: Response}; - security?: {[securityDefinitionName: string]: string[]}[]; - securityDefinitions?: {[securityDefinitionName: string]: Security}; - tags?: Tag[]; -} - -export interface SwaggerSettings { +export interface SwaggerSettingsBase { /** * The url subpath to access to the documentation. */ @@ -38,7 +20,7 @@ export interface SwaggerSettings { /** * Specify the spec version you want to generate. */ - specVersion?: "2.0" | "3.0.1"; + specVersion?: OpenSpecVersions; /** * Swagger file name. By default swagger.json */ @@ -79,8 +61,22 @@ export interface SwaggerSettings { * Write the `swagger.json` spec documentation on the specified path. */ outFile?: string; +} + +export interface SwaggerOS2Settings extends SwaggerSettingsBase { + specVersion?: OS2Versions; /** - * + * OpenSpec 2 */ - spec?: SwaggerSpec; + spec?: Partial; } + +export interface SwaggerOS3Settings extends SwaggerSettingsBase { + specVersion?: OS3Versions; + /** + * OpenSpec 3 + */ + spec?: Partial; +} + +export type SwaggerSettings = SwaggerOS2Settings | SwaggerOS3Settings; diff --git a/packages/swagger/src/services/SwaggerService.spec.ts b/packages/swagger/src/services/SwaggerService.spec.ts index 698f0bd4534..35c5ff68dcd 100644 --- a/packages/swagger/src/services/SwaggerService.spec.ts +++ b/packages/swagger/src/services/SwaggerService.spec.ts @@ -48,8 +48,7 @@ describe("SwaggerService", () => { version: "1.0.0" }, produces: ["application/json", "application/octet-stream", "application/xml"], - consumes: ["application/json"], - securityDefinitions: {} + consumes: ["application/json"] }); }); }); @@ -68,7 +67,6 @@ describe("SwaggerService", () => { version: "1.0.0" }, produces: ["application/json"], - securityDefinitions: {}, swagger: "2.0" }); }); @@ -90,7 +88,6 @@ describe("SwaggerService", () => { version: "1.0.0" }, produces: ["application/json"], - securityDefinitions: {}, swagger: "2.0" }); }); diff --git a/packages/swagger/src/services/SwaggerService.ts b/packages/swagger/src/services/SwaggerService.ts index 022f4cedd57..3d104f8ab40 100644 --- a/packages/swagger/src/services/SwaggerService.ts +++ b/packages/swagger/src/services/SwaggerService.ts @@ -1,12 +1,13 @@ -import {Configuration, ControllerProvider, InjectorService, Platform, Service} from "@tsed/common"; -import {deepExtends} from "@tsed/core"; -import {getSpec, SpecSerializerOptions, SpecTypes} from "@tsed/schema"; +import {Configuration, ControllerProvider, Injectable, InjectorService, Platform} from "@tsed/common"; +import {getValue} from "@tsed/core"; +import {OpenSpec2, OpenSpec3} from "@tsed/openspec"; +import {getSpec, mergeSpec, SpecSerializerOptions} from "@tsed/schema"; +import {SwaggerOS3Settings, SwaggerOS2Settings, SwaggerSettings} from "../interfaces/SwaggerSettings"; import * as Fs from "fs"; -import {Spec, Tag} from "swagger-schema-official"; -import {SwaggerSettings} from "../interfaces"; -import {getReducers} from "../utils"; +import {getSpecTypeFromSpec} from "../utils/getSpecType"; +import {mapOpenSpec} from "../utils/mapOpenSpec"; -@Service() +@Injectable() export class SwaggerService { constructor( private injectorService: InjectorService, @@ -15,21 +16,25 @@ export class SwaggerService { ) {} /** - * + * Generate Spec for the given configuration * @returns {Spec} */ - public getOpenAPISpec(conf: SwaggerSettings): Spec { - const defaultSpec = this.getDefaultSpec(conf); - const doc = conf.doc; - const finalSpec = {}; - - const options = { + public getOpenAPISpec(conf: SwaggerOS3Settings): OpenSpec3; + public getOpenAPISpec(conf: SwaggerOS2Settings): OpenSpec2; + public getOpenAPISpec(conf: SwaggerSettings): OpenSpec2; + public getOpenAPISpec(conf: SwaggerSettings) { + const defaultSpec: any = this.getDefaultSpec(conf); + const specType = getSpecTypeFromSpec(defaultSpec); + const {doc} = conf; + const finalSpec: any = {}; + + const options: SpecSerializerOptions = { paths: {}, tags: [], schemas: {}, - spec: defaultSpec.openapi ? SpecTypes.OPENAPI : SpecTypes.SWAGGER, + specType, append(spec: any) { - deepExtends(finalSpec, spec, getReducers()); + mergeSpec(finalSpec, spec); } }; @@ -47,61 +52,26 @@ export class SwaggerService { } }); - return deepExtends(defaultSpec, finalSpec, getReducers()); + return mergeSpec(defaultSpec, finalSpec) as any; } /** * Return the global api information. */ - public getDefaultSpec(conf: Partial): any { - const {version} = this.configuration; - const spec: any = - conf.spec || - ({ - info: {} - } as any); - - const {specPath} = conf; - - let specPathContent: any = {}; - - if (specPath) { - specPathContent = this.readSpecPath(specPath); - } - - const {specVersion = specPathContent.openapi || specPathContent.swagger || "2.0"} = conf; - /* istanbul ignore next */ - const {title = "Api documentation", description = "", version: versionInfo, termsOfService = "", contact, license} = - spec.info || ({} as any); - - if ((specVersion || "").startsWith("3.")) { - spec.openapi = specVersion; - } else { - spec.swagger = specVersion; - spec.consumes = (this.configuration.acceptMimes || ["application/json"]).concat(spec.consumes || []); - spec.produces = spec.produces || ["application/json"]; - spec.securityDefinitions = {}; - } - - return deepExtends( - { - ...spec, - info: { - version: versionInfo || version, - title, - description, - termsOfService, - contact, - license - }, - securityDefinitions: spec.securityDefinitions || {} - }, - specPathContent, - getReducers() - ); + protected getDefaultSpec(conf: Partial): Partial { + const {version, acceptMimes} = this.configuration; + const {specPath, specVersion} = conf; + const fileSpec: Partial = specPath ? this.readSpecPath(specPath) : {}; + + return mapOpenSpec(getValue(conf, "spec", {}), { + fileSpec, + version, + specVersion, + acceptMimes + }); } - private readSpecPath(path: string) { + protected readSpecPath(path: string) { path = this.configuration.resolve(path); if (Fs.existsSync(path)) { const json = Fs.readFileSync(path, {encoding: "utf8"}); @@ -119,7 +89,7 @@ export class SwaggerService { * @param ctrl * @param options */ - private buildRoutes(ctrl: ControllerProvider, options: SpecSerializerOptions): Tag[] { + protected buildRoutes(ctrl: ControllerProvider, options: SpecSerializerOptions) { ctrl.children .map((ctrl) => this.injectorService.getProvider(ctrl)) .forEach((provider: ControllerProvider) => { @@ -135,27 +105,4 @@ export class SwaggerService { return getSpec(ctrl.token, options); } - - // private createOperationIdFormatter = (conf: ISwaggerSettings) => { - // const OPERATION_IDS: any = {}; - // - // return (targetName: string, methodName: string) => { - // const {operationIdFormat = "%c.%m"} = conf || {}; - // - // const operationId = operationIdFormat.replace(/%c/, targetName).replace(/%m/, methodName); - // const operationKey = targetName + methodName; - // - // if (OPERATION_IDS[operationKey] === undefined) { - // OPERATION_IDS[operationKey] = 0; - // - // return operationId; - // } - // - // const id = OPERATION_IDS[operationKey] + 1; - // - // OPERATION_IDS[operationKey] = id; - // - // return `${operationId}_${id}`; - // }; - // }; } diff --git a/packages/swagger/src/utils/getSpecType.spec.ts b/packages/swagger/src/utils/getSpecType.spec.ts new file mode 100644 index 00000000000..e45e975c1f6 --- /dev/null +++ b/packages/swagger/src/utils/getSpecType.spec.ts @@ -0,0 +1,17 @@ +import {SpecTypes} from "@tsed/schema"; +import {expect} from "chai"; +import {getSpecType, getSpecTypeFromSpec} from "./getSpecType"; + +describe("getSpecType", () => { + it("should return spect type from version", () => { + expect(getSpecType("2.0")).to.equal(SpecTypes.SWAGGER); + expect(getSpecType("3.0.1")).to.equal(SpecTypes.OPENAPI); + }); +}); + +describe("getSpecTypeFromSpec", () => { + it("should return spect type from version", () => { + expect(getSpecTypeFromSpec({swagger: "2.0"})).to.equal(SpecTypes.SWAGGER); + expect(getSpecTypeFromSpec({openapi: "3.0.1"})).to.equal(SpecTypes.OPENAPI); + }); +}); diff --git a/packages/swagger/src/utils/getSpecType.ts b/packages/swagger/src/utils/getSpecType.ts new file mode 100644 index 00000000000..0678ded3696 --- /dev/null +++ b/packages/swagger/src/utils/getSpecType.ts @@ -0,0 +1,10 @@ +import {OpenSpec2, OpenSpec3} from "@tsed/openspec"; +import {SpecTypes} from "@tsed/schema"; + +export function getSpecType(version: string) { + return version.startsWith("3.") ? SpecTypes.OPENAPI : SpecTypes.SWAGGER; +} + +export function getSpecTypeFromSpec(spec: Partial) { + return "openapi" in spec ? SpecTypes.OPENAPI : SpecTypes.SWAGGER; +} diff --git a/packages/swagger/src/utils/index.spec.ts b/packages/swagger/src/utils/index.spec.ts deleted file mode 100644 index 738c855e8c8..00000000000 --- a/packages/swagger/src/utils/index.spec.ts +++ /dev/null @@ -1,108 +0,0 @@ -import {expect} from "chai"; -import {parseSwaggerPath} from "./index"; - -describe("parseSwaggerPath()", () => { - it("should return params and path(1)", () => { - expect(parseSwaggerPath("/rest/", "/get/:path1/:path2?")).to.deep.eq([ - { - path: "/rest/get/{path1}", - pathParams: [ - { - in: "path", - name: "path1", - required: true, - type: "string" - } - ] - }, - { - path: "/rest/get/{path1}/{path2}", - pathParams: [ - { - in: "path", - name: "path1", - required: true, - type: "string" - }, - { - in: "path", - name: "path2", - required: true, - type: "string" - } - ] - } - ]); - }); - - it("should return params and path(2)", () => { - expect(parseSwaggerPath("/rest/", "/get/:path1/:path2")).to.deep.eq([ - { - path: "/rest/get/{path1}/{path2}", - pathParams: [ - { - in: "path", - name: "path1", - required: true, - type: "string" - }, - { - in: "path", - name: "path2", - required: true, - type: "string" - } - ] - } - ]); - }); - - it("should return params and path(3)", () => { - expect(parseSwaggerPath("/rest/", "/get/path1/path2")).to.deep.eq([ - { - path: "/rest/get/path1/path2", - pathParams: [] - } - ]); - }); - - it("should return params and path(4)", () => { - expect(parseSwaggerPath("/rest/calendar/", "/")).to.deep.eq([ - { - path: "/rest/calendar", - pathParams: [] - } - ]); - }); - it("should return params and path /file/:filename.json", () => { - expect(parseSwaggerPath("/rest/", "/file/:filename.json")).to.deep.eq([ - { - path: "/rest/file/{filename}.json", - pathParams: [ - { - in: "path", - name: "filename", - required: true, - type: "string" - } - ] - } - ]); - }); - - it("should return params and path /category/:category([a-zA-Z/_-]+).json", () => { - expect(parseSwaggerPath("/rest/", "/category/:category([a-zA-Z/_-]+).json")).to.deep.eq([ - { - path: "/rest/category/{category}.json", - pathParams: [ - { - in: "path", - name: "category", - required: true, - type: "string" - } - ] - } - ]); - }); -}); diff --git a/packages/swagger/src/utils/index.ts b/packages/swagger/src/utils/index.ts index d67a0c297ec..d5df5f44d3a 100644 --- a/packages/swagger/src/utils/index.ts +++ b/packages/swagger/src/utils/index.ts @@ -1,164 +1,5 @@ -import {getJsonType, PathParamsType} from "@tsed/common"; -import {deepExtends} from "@tsed/core"; - -function getVariable(subpath: string) { - const splited = subpath.split("."); - const name = splited.splice(0, 1)[0]; - - return { - name, - postfix: splited.length ? `.${splited.join(".")}` : "" - }; -} - -export function parseSwaggerPath(base: string, path: PathParamsType = ""): {path: string; pathParams: any[]}[] { - if (path instanceof RegExp) { - path = path.toString().replace(/^\//, "").replace(/\/$/, "").replace(/\\/, ""); - } - - const params: any[] = []; - const paths: any[] = []; - let isOptional = false; - let current = ""; - - `${base}${path}` - .replace(/\((.*)\)/gi, "") - .split("/") - .filter((o) => !!o) - .map((key) => { - const subpath = key.replace(":", "").replace("?", ""); - - if (key.includes(":")) { - const optional = key.includes("?"); - - // Append previous config - if (optional && !isOptional) { - isOptional = true; - - paths.push({ - path: current, - pathParams: [].concat(params as any) - }); - } - - const {name, postfix} = getVariable(subpath); - current += `/{${name}}${postfix}`; - - params.push({ - in: "path", - name, - type: "string", - required: true - }); - - if (optional && isOptional) { - paths.push({ - path: current, - pathParams: [].concat(params as any) - }); - } - } else { - current += `/${key}`; - } - }); - - return paths.length - ? paths - : [ - { - path: current, - pathParams: [].concat(params as any) - } - ]; -} - -/** - * - * @param type - * @returns {string | string[]} - */ -export function swaggerType(type: any): string { - return getJsonType(type) as any; -} - -/** - * Filter the null type, unsupported by swagger and apply the right type on schema. - * @param schema - * @param type - */ -export function swaggerApplyType(schema: any, type: any): any { - const types = [] - .concat(swaggerType(type) as any) - .filter((type) => { - if (type === "null") { - schema.nullable = true; - - return false; - } - - return type; - }) - .map((type) => String(type)); - - if (types.length === 1) { - schema.type = types[0]; - } else { - delete schema.type; - schema.oneOf = types.map((type) => ({type})); - } - - return schema; -} - -/** - * - * @returns {{[p: string]: (collection: any[], value: any) => any}} - */ -export function getReducers(): {[key: string]: (collection: any[], value: any) => any} { - const defaultReducer = (collection: any[], value: any) => { - if (collection.indexOf(value) === -1) { - collection.push(value); - } - - return collection; - }; - - return { - default: defaultReducer, - security: (collection, value) => { - const current = collection.find((current: any): any => { - return Object.keys(value).find((key) => !!current[key]); - }); - - if (current) { - deepExtends(current, value, {default: defaultReducer}); - } else { - collection.push(value); - } - - return collection; - }, - parameters: (collection, value) => { - const current = collection.find((current) => current.in === value.in && current.name === value.name); - - if (current) { - deepExtends(current, value); - } else { - collection.push(value); - } - - return collection; - }, - oneOf: (collection, value) => { - const current = collection.find((current) => current.type === value.type); - - if (current) { - deepExtends(current, value); - } else { - collection.push(value); - } - - return collection; - } - }; -} +export * from "./getSpecType"; +export * from "./mapOpenSpec"; +export * from "./mapOpenSpec2"; +export * from "./mapOpenSpec3"; +export * from "./mapOpenSpecInfo"; diff --git a/packages/swagger/src/utils/mapOpenSpec.ts b/packages/swagger/src/utils/mapOpenSpec.ts new file mode 100644 index 00000000000..cf72d226c2c --- /dev/null +++ b/packages/swagger/src/utils/mapOpenSpec.ts @@ -0,0 +1,30 @@ +import {getValue} from "@tsed/core"; +import {OpenSpec2, OpenSpec3, OpenSpecVersions} from "@tsed/openspec"; +import {mergeSpec, SpecTypes} from "@tsed/schema"; +import {getSpecType} from "./getSpecType"; +import {mapOpenSpec2} from "./mapOpenSpec2"; +import {mapOpenSpec3} from "./mapOpenSpec3"; + +export function mapOpenSpec(spec: any, {fileSpec, version, acceptMimes, specVersion}: any): Partial { + specVersion = specVersion || getValue(spec, "openapi", getValue(spec, "swagger", "2.0")); + + const options = { + version, + specVersion, + acceptMimes + }; + + switch (getSpecType(specVersion)) { + case SpecTypes.OPENAPI: + spec = mapOpenSpec3(spec, options); + fileSpec = fileSpec ? mapOpenSpec3(fileSpec, options) : fileSpec; + break; + default: + case SpecTypes.SWAGGER: + spec = mapOpenSpec2(spec, options); + fileSpec = fileSpec ? mapOpenSpec2(fileSpec, options) : fileSpec; + break; + } + + return mergeSpec(spec, fileSpec); +} diff --git a/packages/swagger/src/utils/mapOpenSpec2.ts b/packages/swagger/src/utils/mapOpenSpec2.ts new file mode 100644 index 00000000000..604ab53fc25 --- /dev/null +++ b/packages/swagger/src/utils/mapOpenSpec2.ts @@ -0,0 +1,42 @@ +import {getValue, uniq} from "@tsed/core"; +import {OpenSpec2} from "@tsed/openspec"; +import {mapOpenSpecInfo} from "./mapOpenSpecInfo"; + +export function mapOpenSpec2( + spec: Partial, + {version, specVersion, acceptMimes = ["application/json"]}: any +): Partial { + const { + paths, + security, + tags, + host, + basePath, + schemes, + consumes = [], + produces = ["application/json"], + definitions, + parameters, + responses, + securityDefinitions, + externalDocs + } = spec; + + return { + swagger: specVersion, + consumes: uniq([...acceptMimes, ...consumes]), + produces: uniq([...produces]), + info: mapOpenSpecInfo(getValue(spec, "info", {}), version), + paths, + host, + basePath, + schemes, + definitions, + parameters, + responses, + security, + securityDefinitions, + tags, + externalDocs + }; +} diff --git a/packages/swagger/src/utils/mapOpenSpec3.ts b/packages/swagger/src/utils/mapOpenSpec3.ts new file mode 100644 index 00000000000..e91491d4395 --- /dev/null +++ b/packages/swagger/src/utils/mapOpenSpec3.ts @@ -0,0 +1,18 @@ +import {getValue} from "@tsed/core"; +import {OpenSpec3} from "@tsed/openspec"; +import {mapOpenSpecInfo} from "./mapOpenSpecInfo"; + +export function mapOpenSpec3(spec: any, {version, specVersion}: any): Partial { + const {servers, paths, components, security, tags, externalDocs} = spec; + + return { + openapi: specVersion, + info: mapOpenSpecInfo(getValue(spec, "info", {}), version), + servers, + paths, + components, + security, + tags, + externalDocs + }; +} diff --git a/packages/swagger/src/utils/mapOpenSpecInfo.ts b/packages/swagger/src/utils/mapOpenSpecInfo.ts new file mode 100644 index 00000000000..10e6dfefcea --- /dev/null +++ b/packages/swagger/src/utils/mapOpenSpecInfo.ts @@ -0,0 +1,14 @@ +import {OpenSpecInfo} from "@tsed/openspec"; + +export function mapOpenSpecInfo(info: Partial, defaultVersion: string): OpenSpecInfo { + const {title = "Api documentation", description = "", version: versionInfo, termsOfService = "", contact, license} = info; + + return { + version: versionInfo || defaultVersion, + title, + description, + termsOfService, + contact, + license + }; +} diff --git a/packages/swagger/test/swagger.errors.spec.ts b/packages/swagger/test/swagger.errors.spec.ts index e1379f5cb4a..2340262a557 100644 --- a/packages/swagger/test/swagger.errors.spec.ts +++ b/packages/swagger/test/swagger.errors.spec.ts @@ -119,7 +119,6 @@ describe("Swagger errors params", () => { } }, produces: ["application/json"], - securityDefinitions: {}, swagger: "2.0", tags: [ { diff --git a/packages/swagger/test/swagger.integration.spec.ts b/packages/swagger/test/swagger.integration.spec.ts index 40c0f91472f..f4e87aac430 100644 --- a/packages/swagger/test/swagger.integration.spec.ts +++ b/packages/swagger/test/swagger.integration.spec.ts @@ -56,7 +56,7 @@ class CalendarsController { } describe("Swagger integration", () => { - describe("swagger 2", () => { + describe("OpenSpec2", () => { let request: SuperTest.SuperTest; beforeEach( PlatformTest.bootstrap(Server, { @@ -190,7 +190,6 @@ describe("Swagger integration", () => { } }, produces: ["application/json"], - securityDefinitions: {}, swagger: "2.0", tags: [ { @@ -234,10 +233,9 @@ describe("Swagger integration", () => { ]); expect(response.body).to.deep.eq({ - info: {version: "1.0.0", title: "Api documentation", description: "", termsOfService: ""}, - openapi: "3.0.1", - securityDefinitions: {}, - paths: { + "info": {"version": "1.0.0", "title": "Api documentation", "description": "", "termsOfService": ""}, + "openapi": "3.0.1", + "paths": { "/rest/events/events": { get: { operationId: "eventCtrlGet", diff --git a/packages/swagger/test/swagger.query.spec.ts b/packages/swagger/test/swagger.query.spec.ts index 0070c7b51a3..af390a9c94c 100644 --- a/packages/swagger/test/swagger.query.spec.ts +++ b/packages/swagger/test/swagger.query.spec.ts @@ -152,7 +152,6 @@ describe("Swagger query params", () => { } }, produces: ["application/json"], - securityDefinitions: {}, swagger: "2.0", tags: [ { diff --git a/yarn.lock b/yarn.lock index 55a58d159f2..d570b1061c7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2757,11 +2757,6 @@ dependencies: "@types/superagent" "*" -"@types/swagger-schema-official@2.0.21": - version "2.0.21" - resolved "https://registry.yarnpkg.com/@types/swagger-schema-official/-/swagger-schema-official-2.0.21.tgz#56812a86dcd57ba60e5c51705ee96a2b2dc9b374" - integrity sha512-n9BbLOjR4Hre7B4TSGGMPohOgOg8tcp00uxqsIE00uuWQC0QuX57G1bqC1csLsk2DpTGtHkd0dEb3ipsCZ9dAA== - "@types/tmp@^0.2.0": version "0.2.0" resolved "https://registry.yarnpkg.com/@types/tmp/-/tmp-0.2.0.tgz#e3f52b4d7397eaa9193592ef3fdd44dc0af4298c" From adc6f13bda89ac8be959d3d49c2839d4be6fdb35 Mon Sep 17 00:00:00 2001 From: Romain Lenzotti Date: Sat, 10 Oct 2020 12:04:45 +0200 Subject: [PATCH 5/5] chore: Update monorepotool version --- package.json | 2 +- reports/eslint/test-results-eslint.xml | 4 ++-- reports/mocha/test-results-unit.xml | 6 +++--- yarn.lock | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 0ac6bc0731f..58f448aa3ca 100644 --- a/package.json +++ b/package.json @@ -79,7 +79,7 @@ "consolidate": "0.16.0" }, "devDependencies": { - "@tsed/monorepo-utils": "1.9.5", + "@tsed/monorepo-utils": "1.10.0", "@typedproject/ts-doc": "4.0.9", "@types/chai": "4.2.12", "@types/chai-as-promised": "7.1.3", diff --git a/reports/eslint/test-results-eslint.xml b/reports/eslint/test-results-eslint.xml index d3168bf51cf..2daee878a73 100644 --- a/reports/eslint/test-results-eslint.xml +++ b/reports/eslint/test-results-eslint.xml @@ -2796,8 +2796,8 @@ - - + + diff --git a/reports/mocha/test-results-unit.xml b/reports/mocha/test-results-unit.xml index 68a567d79ec..facfd987838 100644 --- a/reports/mocha/test-results-unit.xml +++ b/reports/mocha/test-results-unit.xml @@ -4644,8 +4644,8 @@ - - + + @@ -5176,7 +5176,7 @@ - + diff --git a/yarn.lock b/yarn.lock index d570b1061c7..7421e662489 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2183,10 +2183,10 @@ streamroller "^1.0.3" tslib "1.10.0" -"@tsed/monorepo-utils@1.9.5": - version "1.9.5" - resolved "https://registry.yarnpkg.com/@tsed/monorepo-utils/-/monorepo-utils-1.9.5.tgz#087331a5de28a37504f951d552da4832f4132fa1" - integrity sha512-g7RbRszoCIDYEb5dAJaHJUt5gMaxg3agKa/CkFVV33OnjN/n6guN9qztXL3y/wRiJCoskVjjCALA8ZJP688q4A== +"@tsed/monorepo-utils@1.10.0": + version "1.10.0" + resolved "https://registry.yarnpkg.com/@tsed/monorepo-utils/-/monorepo-utils-1.10.0.tgz#a868c4cbe18adf1d364ee9fc85242cfd7b8e6496" + integrity sha512-uSbl4sdfvxYgywF2hgYcjuXqNKqPkpUn0KRhy8RSBTCEcLE8PVR3ar+qzsTvKpxfVIHDOB5LAgiQH4ZUQ7GOQA== dependencies: axios "0.19.2" chalk "3.0.0"