@hey-api/openapi-ts
Version:
🌀 OpenAPI to TypeScript codegen. Production-ready SDKs, Zod schemas, TanStack Query hooks, and 20+ plugins. Used by Vercel, OpenCode, and PayPal.
1,255 lines (1,251 loc) • 664 kB
text/typescript
import { AnalysisContext, BindingKind, ExportModule, File, FromRef, IProject, ImportModule, Language, NameConflictResolver, Node, NodeName as NodeName$1, NodeNameSanitizer, NodeRelationship, NodeScope, Project, Ref, Refs, RenderContext, Renderer, StructureLocation, Symbol, SymbolIdentifier, SymbolIn, SymbolMeta } from "@hey-api/codegen-core";
import ts from "typescript";
import { RangeOptions, SemVer } from "semver";
//#region src/types/utils.d.ts
/**
* Accepts a value, a function returning a value, or a function returning a promise of a value.
*/
type LazyOrAsync<T> = T | (() => MaybePromise<T>);
/**
* Accepts a value or a readonly array of values of type T.
*/
type MaybeArray$1<T> = T | ReadonlyArray<T>;
/**
* Accepts a value or a function returning a value.
*/
type MaybeFunc$1<T extends (...args: Array<any>) => any> = T | ReturnType<T>;
/**
* Accepts a value or a promise of a value.
*/
type MaybePromise<T> = T | Promise<T>;
//#endregion
//#region src/utils/naming/types.d.ts
/**
* Available casing strategies.
*/
type Casing = 'camelCase' | 'PascalCase' | 'preserve' | 'snake_case' | 'SCREAMING_SNAKE_CASE';
/**
* Name transformer: template string or function.
*
* Template supports `{{name}}` variable.
*/
type NameTransformer = MaybeFunc$1<(name: string) => string>;
/**
* Full naming configuration.
*/
interface NamingConfig {
/**
* Casing strategy applied after transformation.
*
* @deprecated Use `casing` instead.
*/
case?: Casing;
/**
* Casing strategy applied after transformation.
*/
casing?: Casing;
/**
* Name template or transformer function.
*
* Applied before `casing` transformation.
*/
name?: NameTransformer;
}
/**
* Name customization: shorthand or full configuration.
*/
type NamingRule = NameTransformer | NamingConfig;
//#endregion
//#region src/config/output/source/types.d.ts
// TODO: json-schema-ref-parser needs to expose source extension so
// we can default to it
type SourceExtension = 'json';
// type SourceExtension = 'json' | 'yaml';
interface UserSourceConfig {
/**
* Callback invoked with the serialized source string.
*
* Runs after the `serialize` function.
*
* @example
* source => console.log(source)
*/
callback?: (source: string) => MaybePromise<void>;
/**
* Whether the source should be generated at all.
*
* When `false`, no source file is created or processed.
*
* @default true
*/
enabled?: boolean;
// * Only `'json'` and `'yaml'` are allowed.
/**
* File extension for the source file.
*
* @default 'json'
*/
extension?: SourceExtension;
/**
* Base file name for the source file.
*
* The extension from `extension` will be appended automatically.
*
* @default 'source'
*/
fileName?: string;
/**
* Target location for the source file.
*
* - `true` / `undefined` → write to output root (default)
* - `string` → relative to output root or absolute path
* - `false` / `null` → do not write
*
* @default true
*/
path?: boolean | string | null;
/**
* Function to serialize the input object into a string.
*
* @default
* JSON.stringify(input, null, 2)
*
* @example
* input => JSON.stringify(input, null, 0) // minified
*/
serialize?: (input: Record<string, any>) => MaybePromise<string>;
}
interface SourceConfig {
/**
* Callback invoked with the serialized source string.
*
* Runs after the `serialize` function.
*/
callback?: (source: string) => MaybePromise<void>;
/**
* Whether the source should be generated at all.
*/
enabled: boolean;
/**
* File extension for the source file.
*/
extension: SourceExtension;
/**
* Base file name for the source file.
*/
fileName: string;
/**
* Target location for the source file.
*/
path: string | null;
/**
* Function to serialize the input object into a string.
*/
serialize: (input: Record<string, any>) => MaybePromise<string>;
}
//#endregion
//#region src/config/output/types.d.ts
type Formatters = 'biome' | 'prettier';
type Linters = 'biome' | 'eslint' | 'oxlint';
type ImportFileExtensions = '.js' | '.ts';
type Header$1 = MaybeFunc$1<(ctx: RenderContext) => MaybeArray$1<string> | null | undefined>;
type UserOutput = {
/**
* Defines casing of the output fields. By default, we preserve `input`
* values as data transforms incur a performance penalty at runtime.
*
* @default undefined
*/
case?: Casing;
/**
* Clean the `output` folder on every run? If disabled, this folder may
* be used to store additional files. The default option is `true` to
* reduce the risk of keeping outdated files around when configuration,
* input, or package version changes.
*
* @default true
*/
clean?: boolean;
/**
* Optional function to transform file names before they are used.
*
* @param name The original file name.
* @returns The transformed file name.
* @default '{{name}}'
*/
fileName?: NameTransformer | {
/**
* The casing convention to use for generated file names.
*
* @default 'preserve'
*/
case?: Casing;
/**
* Custom naming pattern for generated file names.
*
* @default '{{name}}'
*/
name?: NameTransformer;
/**
* Suffix to append to file names (before the extension). For example,
* with a suffix of `.gen`, `example.ts` becomes `example.gen.ts`.
*
* @default '.gen'
* @example
* // Given a suffix of `.gen`
* 'index.ts' -> 'index.ts' (index files are not renamed)
* 'user.ts' -> 'user.gen.ts'
* 'order.gen.ts' -> 'order.gen.ts' (files already containing the suffix are not renamed)
*/
suffix?: string | null;
};
/**
* Which formatter to use to process output folder?
*
* @default null
*/
format?: Formatters | null;
/**
* Text to include at the top of every generated file.
*/
header?: Header$1;
/**
* If specified, this will be the file extension used when importing
* other modules. By default, we don't add a file extension and let the
* runtime resolve it. If you're using moduleResolution `nodenext` or
* `node16`, we default to `.js`.
*
* @default undefined
*/
importFileExtension?: ImportFileExtensions | (string & {}) | null;
/**
* Should the exports from plugin files be re-exported in the index
* barrel file? By default, this is enabled and only default plugins
* are re-exported.
*
* @default true
*/
indexFile?: boolean;
/**
* Which linter to use to process output folder?
*
* @default null
*/
lint?: Linters | null;
/**
* Optional name conflict resolver to customize how naming conflicts
* are handled.
*/
nameConflictResolver?: NameConflictResolver;
/**
* The absolute path to the output folder.
*/
path: string;
/**
* Whether `export * from 'module'` should be used when possible
* instead of named exports.
*
* @default false
*/
preferExportAll?: boolean;
/**
* Optional function to transform module specifiers.
*
* @default undefined
*/
resolveModuleName?: (moduleName: string) => string | undefined;
/**
* Configuration for generating a copy of the input source used to produce this output.
*
* Set to `false` to skip generating the source, or `true` to use defaults.
*
* You can also provide a configuration object to further customize behavior.
*
* @default false
*/
source?: boolean | UserSourceConfig;
/**
* Relative or absolute path to the tsconfig file we should use to
* generate the output. If a path to tsconfig file is not provided, we
* attempt to find one starting from the location of the
* `@hey-api/openapi-ts` configuration file and traversing up.
*
* @default undefined
*/
tsConfigPath?: (string & {}) | null;
};
type Output = {
/**
* Defines casing of the output fields. By default, we preserve `input`
* values as data transforms incur a performance penalty at runtime.
*/
case: Casing | undefined;
/**
* Clean the `output` folder on every run? If disabled, this folder may
* be used to store additional files. The default option is `true` to
* reduce the risk of keeping outdated files around when configuration,
* input, or package version changes.
*/
clean: boolean;
/**
* Optional function to transform file names before they are used.
*
* @param name The original file name.
* @returns The transformed file name.
*/
fileName: {
/**
* The casing convention to use for generated file names.
*/
case: Casing;
/**
* Custom naming pattern for generated file names.
*/
name: NameTransformer;
/**
* Suffix to append to file names (before the extension). For example,
* with a suffix of `.gen`, `example.ts` becomes `example.gen.ts`.
*
* @example
* // Given a suffix of `.gen`
* 'index.ts' -> 'index.ts' (index files are not renamed)
* 'user.ts' -> 'user.gen.ts'
* 'order.gen.ts' -> 'order.gen.ts' (files already containing the suffix are not renamed)
*/
suffix: string | null;
};
/**
* Which formatter to use to process output folder?
*/
format: Formatters | null;
/**
* Text to include at the top of every generated file.
*/
header: Header$1;
/**
* If specified, this will be the file extension used when importing
* other modules. By default, we don't add a file extension and let the
* runtime resolve it. If you're using moduleResolution `nodenext` or
* `node16`, we default to `.js`.
*/
importFileExtension: ImportFileExtensions | (string & {}) | null | undefined;
/**
* Should the exports from plugin files be re-exported in the index
* barrel file? By default, this is enabled and only default plugins
* are re-exported.
*/
indexFile: boolean;
/**
* Which linter to use to process output folder?
*/
lint: Linters | null;
/**
* Optional name conflict resolver to customize how naming conflicts
* are handled.
*/
nameConflictResolver: NameConflictResolver | undefined;
/**
* The absolute path to the output folder.
*/
path: string;
/**
* Whether `export * from 'module'` should be used when possible
* instead of named exports.
*/
preferExportAll: boolean;
/**
* Optional function to transform module specifiers.
*/
resolveModuleName: ((moduleName: string) => string | undefined) | undefined;
/**
* Configuration for generating a copy of the input source used to produce this output.
*/
source: SourceConfig;
/**
* The parsed TypeScript configuration used to generate the output.
* If no `tsconfig` file path was provided or found, this will be `null`.
*/
tsConfig: ts.ParsedCommandLine | null;
/**
* Relative or absolute path to the tsconfig file we should use to
* generate the output. If a path to tsconfig file is not provided, we
* attempt to find one starting from the location of the
* `@hey-api/openapi-ts` configuration file and traversing up.
*/
tsConfigPath: (string & {}) | null | undefined;
};
//#endregion
//#region src/openApi/shared/types/openapi-spec-extensions.d.ts
type LinguistLanguages = 'C' | 'C#' | 'C++' | 'CoffeeScript' | 'CSS' | 'Dart' | 'DM' | 'Elixir' | 'Go' | 'Groovy' | 'HTML' | 'Java' | 'JavaScript' | 'Kotlin' | 'Objective-C' | 'Perl' | 'PHP' | 'PowerShell' | 'Python' | 'Ruby' | 'Rust' | 'Scala' | 'Shell' | 'Swift' | 'TypeScript';
interface CodeSampleObject {
/**
* Code sample label, for example `Node` or `Python2.7`.
*
* @default `lang` value
*/
label?: string;
/**
* **REQUIRED**. Code sample language. Can be one of the automatically supported languages or any other language identifier of your choice (for custom code samples).
*/
lang: LinguistLanguages;
/**
* **REQUIRED**. Code sample source code, or a `$ref` to the file containing the code sample.
*/
source: string;
}
interface EnumExtensions {
/**
* `x-enum-descriptions` are {@link https://stackoverflow.com/a/66471626 supported} by OpenAPI Generator.
*/
'x-enum-descriptions'?: ReadonlyArray<string>;
/**
* `x-enum-varnames` are {@link https://stackoverflow.com/a/66471626 supported} by OpenAPI Generator.
*/
'x-enum-varnames'?: ReadonlyArray<string>;
/**
* {@link https://github.com/RicoSuter/NSwag NSwag} generates `x-enumNames` field containing custom enum names.
*/
'x-enumNames'?: ReadonlyArray<string>;
}
//#endregion
//#region src/openApi/3.1.x/types/spec.d.ts
/**
* OpenAPI Specification Extensions.
*
* See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*/
interface SpecificationExtensions$2 {
[extension: `x-${string}`]: unknown;
}
/**
* This is the root object of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-document OpenAPI document}.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*/
interface OpenApiV3_1_X extends SpecificationExtensions$2 {
/**
* An element to hold various schemas for the document.
*/
components?: ComponentsObject$1;
/**
* Additional external documentation.
*/
externalDocs?: ExternalDocumentationObject$2;
/**
* **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required.
*/
info: InfoObject$2;
/**
* The default value for the `$schema` keyword within {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object Schema Objects} contained within this OAS document. This MUST be in the form of a URI.
*/
jsonSchemaDialect?: string;
/**
* **REQUIRED**. This string MUST be the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#versions version number} of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is _not_ related to the API {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#infoVersion `info.version`} string.
*/
openapi: '3.1.0' | '3.1.1' | '3.1.2';
/**
* The available paths and operations for the API.
*/
paths?: PathsObject$2;
/**
* 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. To make security optional, an empty security requirement (`{}`) can be included in the array.
*/
security?: ReadonlyArray<SecurityRequirementObject$2>;
/**
* 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 {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-object Server Object} with a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#serverUrl url} value of `/`.
*/
servers?: ReadonlyArray<ServerObject$1>;
/**
* A list of tags used by the document 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 {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object 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?: ReadonlyArray<TagObject$2>;
/**
* The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An {@link https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.1/webhook-example.yaml example} is available.
*/
webhooks?: Record<string, PathItemObject$2 | ReferenceObject$3>;
}
/**
* A map of possible out-of band callbacks related to the parent operation. Each value in the map is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object} that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
*
* To describe incoming requests from the API provider independent from another API call, use the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasWebhooks `webhooks`} field.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* **Key Expression**
*
* The key that identifies the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object} is a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions runtime expression} that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. A simple example might be $request.body#/url. However, using a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions runtime expression} the complete HTTP message can be accessed. This includes accessing any part of a body that a JSON Pointer {@link https://tools.ietf.org/html/rfc6901 RFC6901} can reference.
*
* For example, given the following HTTP request:
*
* ```http
* POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1
* Host: example.org
* Content-Type: application/json
* Content-Length: 187
*
* {
* "failedUrl" : "https://clientdomain.com/failed",
* "successUrls" : [
* "https://clientdomain.com/fast",
* "https://clientdomain.com/medium",
* "https://clientdomain.com/slow"
* ]
* }
*
* 201 Created
* Location: https://example.org/subscription/1
* ```
*
* The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`.
*
* | Expression | Value |
* | -------- | ------- |
* | $url | https://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning |
* | $method | POST |
* | $request.path.eventType | myevent |
* | $request.query.queryUrl | https://clientdomain.com/stillrunning |
* | $request.header.content-Type | application/json |
* | $request.body#/failedUrl | https://clientdomain.com/failed |
* | $request.body#/successUrls/2 | https://clientdomain.com/medium |
* | $response.header.Location | https://example.org/subscription/1 |
*
* **Callback Object Examples**
*
* The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook.
*
* ```yaml
* myCallback:
* '{$request.query.queryUrl}':
* post:
* requestBody:
* description: Callback payload
* content:
* 'application/json':
* schema:
* $ref: '#/components/schemas/SomePayload'
* responses:
* '200':
* description: callback successfully processed
* ```
*
* The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body.
*
* ```yaml
* transactionCallback:
* 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}':
* post:
* requestBody:
* description: Callback payload
* content:
* 'application/json':
* schema:
* $ref: '#/components/schemas/SomePayload'
* responses:
* '200':
* description: callback successfully processed
* ```
*/
interface CallbackObject$1 extends SpecificationExtensions$2 {
/**
* A Path Item Object, or a reference to one, used to define a callback request and expected responses. A {@link https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.0/callback-example.yaml complete example} is available.
*/
[expression: string]: PathItemObject$2 | ReferenceObject$3 | unknown;
}
/**
* Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`.
*
* Field Name Examples:
*
* ```
* User
* User_1
* User_Name
* user-name
* my.org.User
* ```
*
* **Components Object Example**
*
* ```yaml
* components:
* schemas:
* GeneralError:
* type: object
* properties:
* code:
* type: integer
* format: int32
* message:
* type: string
* Category:
* type: object
* properties:
* id:
* type: integer
* format: int64
* name:
* type: string
* Tag:
* type: object
* properties:
* id:
* type: integer
* format: int64
* name:
* type: string
* parameters:
* skipParam:
* name: skip
* in: query
* description: number of items to skip
* required: true
* schema:
* type: integer
* format: int32
* limitParam:
* name: limit
* in: query
* description: max records to return
* required: true
* schema:
* type: integer
* format: int32
* responses:
* NotFound:
* description: Entity not found.
* IllegalInput:
* description: Illegal input for operation.
* GeneralError:
* description: General Error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/GeneralError'
* securitySchemes:
* api_key:
* type: apiKey
* name: api_key
* in: header
* petstore_auth:
* type: oauth2
* flows:
* implicit:
* authorizationUrl: https://example.org/api/oauth/dialog
* scopes:
* write:pets: modify pets in your account
* read:pets: read your pets
* ```
*/
interface ComponentsObject$1 extends SpecificationExtensions$2 {
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object Callback Objects}.
*/
callbacks?: Record<string, CallbackObject$1 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#example-object Example Objects}.
*/
examples?: Record<string, ExampleObject$2 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#header-object Header Objects}.
*/
headers?: Record<string, HeaderObject$2 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object Link Objects}.
*/
links?: Record<string, LinkObject$1 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object Parameter Objects}.
*/
parameters?: Record<string, ParameterObject$2 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#path-item-object Path Item Object}.
*/
pathItems?: Record<string, PathItemObject$2 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#request-body-object Request Body Objects}.
*/
requestBodies?: Record<string, RequestBodyObject$1 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#response-object Response Objects}.
*/
responses?: Record<string, ResponseObject$2 | ReferenceObject$3>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#schema-object Schema Objects}.
*/
schemas?: Record<string, SchemaObject$2>;
/**
* An object to hold reusable {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#security-scheme-object Security Scheme Objects}.
*/
securitySchemes?: Record<string, SecuritySchemeObject$2 | ReferenceObject$3>;
}
/**
* Contact information for the exposed API.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* @example
* ```yaml
* name: API Support
* url: https://www.example.com/support
* email: support@example.com
* ```
*/
interface ContactObject$2 extends SpecificationExtensions$2 {
/**
* The email address of the contact person/organization. This MUST be in the form of an email address.
*/
email?: string;
/**
* The identifying name of the contact person/organization.
*/
name?: string;
/**
* The URL pointing to the contact information. This MUST be in the form of a URL.
*/
url?: string;
}
/**
* When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the document of an alternative schema based on the value associated with it.
*
* When using the discriminator, _inline_ schemas will not be considered.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`.
*
* In OAS 3.0, a response payload MAY be described to be exactly one of any number of types:
*
* ```yaml
* MyResponseType:
* oneOf:
* - $ref: '#/components/schemas/Cat'
* - $ref: '#/components/schemas/Dog'
* - $ref: '#/components/schemas/Lizard'
* ```
*
* which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use:
*
* ```yaml
* MyResponseType:
* oneOf:
* - $ref: '#/components/schemas/Cat'
* - $ref: '#/components/schemas/Dog'
* - $ref: '#/components/schemas/Lizard'
* discriminator:
* propertyName: petType
* ```
*
* The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload:
*
* ```json
* {
* "id": 12345,
* "petType": "Cat"
* }
* ```
*
* Will indicate that the `Cat` schema be used in conjunction with this payload.
*
* In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used:
*
* ```yaml
* MyResponseType:
* oneOf:
* - $ref: '#/components/schemas/Cat'
* - $ref: '#/components/schemas/Dog'
* - $ref: '#/components/schemas/Lizard'
* - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json'
* discriminator:
* propertyName: petType
* mapping:
* dog: '#/components/schemas/Dog'
* monster: 'https://gigantic-server.com/schemas/Monster/schema.json'
* ```
*
* Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison.
*
* When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload.
*
* In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema.
*
* For example:
*
* ```yaml
* components:
* schemas:
* Pet:
* type: object
* required:
* - petType
* properties:
* petType:
* type: string
* discriminator:
* propertyName: petType
* mapping:
* dog: Dog
* Cat:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* # all other properties specific to a `Cat`
* properties:
* name:
* type: string
* Dog:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* # all other properties specific to a `Dog`
* properties:
* bark:
* type: string
* Lizard:
* allOf:
* - $ref: '#/components/schemas/Pet'
* - type: object
* # all other properties specific to a `Lizard`
* properties:
* lovesRocks:
* type: boolean
* ```
*
* a payload like this:
*
* ```json
* {
* "petType": "Cat",
* "name": "misty"
* }
* ```
*
* will indicate that the `Cat` schema be used. Likewise this schema:
*
* ```json
* {
* "petType": "dog",
* "bark": "soft"
* }
* ```
*
* will map to `Dog` because of the definition in the `mapping` element.
*/
interface DiscriminatorObject$1 extends SpecificationExtensions$2 {
/**
* An object to hold mappings between payload values and schema names or references.
*/
mapping?: Record<string, string>;
/**
* **REQUIRED**. The name of the property in the payload that will hold the discriminator value.
*/
propertyName: string;
}
/**
* A single encoding definition applied to a single schema property.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* @example
* ```yaml
* requestBody:
* content:
* multipart/form-data:
* schema:
* type: object
* properties:
* id:
* # default is text/plain
* type: string
* format: uuid
* address:
* # default is application/json
* type: object
* properties: {}
* historyMetadata:
* # need to declare XML format!
* description: metadata in XML format
* type: object
* properties: {}
* profileImage: {}
* encoding:
* historyMetadata:
* # require XML Content-Type in utf-8 encoding
* contentType: application/xml; charset=utf-8
* profileImage:
* # only accept png/jpeg
* contentType: image/png, image/jpeg
* headers:
* X-Rate-Limit-Limit:
* description: The number of allowed requests in the current period
* schema:
* type: integer
* ```
*/
interface EncodingObject$1 extends SpecificationExtensions$2 {
/**
* Determines whether the parameter value SHOULD allow reserved characters, as defined by {@link https://tools.ietf.org/html/rfc3986#section-2.2 RFC3986} `:/?#[]@!$&'()*+,;=` 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` or `multipart/form-data`. If a value is explicitly defined, then the value of {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingContentType `contentType`} (implicit or explicit) SHALL be ignored.
*/
allowReserved?: boolean;
/**
* The Content-Type for encoding a specific property. Default value depends on the property type: for `object` - `application/json`; for `array` – the default is defined based on the inner type; for all other cases the default is `application/octet-stream`. 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;
/**
* 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 {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingStyle `style`} 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` or `multipart/form-data`. If a value is explicitly defined, then the value of {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingContentType `contentType`} (implicit or explicit) SHALL be ignored.
*/
explode?: boolean;
/**
* 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?: Record<string, HeaderObject$2 | ReferenceObject$3>;
/**
* Describes how a specific property value will be serialized depending on its type. See {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object Parameter Object} for details on the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`} 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` or `multipart/form-data`. If a value is explicitly defined, then the value of {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#encodingContentType `contentType`} (implicit or explicit) SHALL be ignored.
*/
style?: 'deepObject' | 'form' | 'label' | 'matrix' | 'pipeDelimited' | 'simple' | 'spaceDelimited';
}
/**
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.
*
* Example Object Examples
*
* In a request body:
*
* @example
* ```yaml
* requestBody:
* content:
* 'application/json':
* schema:
* $ref: '#/components/schemas/Address'
* examples:
* foo:
* summary: A foo example
* value: {"foo": "bar"}
* bar:
* summary: A bar example
* value: {"bar": "baz"}
* 'application/xml':
* examples:
* xmlExample:
* summary: This is an example in XML
* externalValue: 'https://example.org/examples/address-example.xml'
* 'text/plain':
* examples:
* textExample:
* summary: This is a text example
* externalValue: 'https://foo.bar/examples/address-example.txt'
* ```
*
* In a parameter:
*
* @example
* ```yaml
* parameters:
* - name: 'zipCode'
* in: 'query'
* schema:
* type: 'string'
* format: 'zip-code'
* examples:
* zip-example:
* $ref: '#/components/examples/zip-example'
* ```
*
* In a response:
*
* @example
* ```yaml
* responses:
* '200':
* description: your car appointment has been booked
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SuccessResponse'
* examples:
* confirmation-success:
* $ref: '#/components/examples/confirmation-success'
* ```
*/
interface ExampleObject$2 extends SpecificationExtensions$2 {
/**
* Long description for the example. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation.
*/
description?: string;
/**
* A URI 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. See the rules for resolving {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#relative-references-in-uris Relative References}.
*/
externalValue?: string;
/**
* Short description for the example.
*/
summary?: 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?: unknown;
}
/**
* Allows referencing an external resource for extended documentation.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* @example
* ```yaml
* description: Find more info here
* url: https://example.com
* ```
*/
interface ExternalDocumentationObject$2 extends SpecificationExtensions$2 {
/**
* A description of the target documentation. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation.
*/
description?: string;
/**
* **REQUIRED**. The URL for the target documentation. This MUST be in the form of a URL.
*/
url: string;
}
/**
* The Header Object follows the structure of the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-object Parameter Object} with the following changes:
*
* 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map.
* 1. `in` MUST NOT be specified, it is implicitly in `header`.
* 1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle `style`}).
*
* @example
* ```yaml
* description: The number of allowed requests in the current period
* schema:
* type: integer
* ```
*/
type HeaderObject$2 = Omit<ParameterObject$2, 'in' | 'name'>;
/**
* The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* @example
* ```yaml
* title: Sample Pet Store App
* summary: A pet store manager.
* description: This is a sample server for a pet store.
* termsOfService: https://example.com/terms/
* contact:
* name: API Support
* url: https://www.example.com/support
* email: support@example.com
* license:
* name: Apache 2.0
* url: https://www.apache.org/licenses/LICENSE-2.0.html
* version: 1.0.1
* ```
*/
interface InfoObject$2 extends SpecificationExtensions$2 {
/**
* The contact information for the exposed API.
*/
contact?: ContactObject$2;
/**
* A description of the API. {@link https://spec.commonmark.org/ CommonMark syntax} MAY be used for rich text representation.
*/
description?: string;
/**
* The license information for the exposed API.
*/
license?: LicenseObject$2;
/**
* A short summary of the API.
*/
summary?: string;
/**
* A URL to the Terms of Service for the API. This MUST be in the form of a URL.
*/
termsOfService?: string;
/**
* **REQUIRED**. The title of the API.
*/
title: string;
/**
* **REQUIRED**. The version of the OpenAPI document (which is distinct from the {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasVersion OpenAPI Specification version} or the API implementation version).
*/
version: string;
}
/**
* License information for the exposed API.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* @example
* ```yaml
* name: Apache 2.0
* identifier: Apache-2.0
* ```
*/
interface LicenseObject$2 extends SpecificationExtensions$2 {
/**
* An {@link https://spdx.org/licenses/ SPDX} license expression for the API. The `identifier` field is mutually exclusive of the `url` field.
*/
identifier?: string;
/**
* **REQUIRED**. The license name used for the API.
*/
name: string;
/**
* A URL to the license used for the API. This MUST be in the form of a URL. The `url` field is mutually exclusive of the `identifier` field.
*/
url?: string;
}
/**
* The `Link object` represents a possible design-time link for a response. The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.
*
* Unlike _dynamic_ links (i.e. links provided in the response payload), the OAS linking mechanism does not require link information in the runtime response.
*
* For computing links, and providing instructions to execute them, a {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#runtime-expressions runtime expression} is used for accessing values in an operation and using them as parameters while invoking the linked operation.
*
* This object MAY be extended with {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specification-extensions Specification Extensions}.
*
* A linked operation MUST be identified using either an `operationRef` or `operationId`. In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. Because of the potential for name clashes, the `operationRef` syntax is preferred for OpenAPI documents with external references.
*
* **Examples**
*
* Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation.
*
* ```yaml
* paths:
* /users/{id}:
* parameters:
* - name: id
* in: path
* required: true
* description: the user identifier, as userId
* schema:
* type: string
* get:
* responses:
* '200':
* description: the user being returned
* content:
* application/json:
* schema:
* type: object
* properties:
* uuid: # the unique user id
* type: string
* format: uuid
* links:
* address:
* # the target link operationId
* operationId: getUserAddress
* parameters:
* # get the `id` field from the request path parameter named `id`
* userId: $request.path.id
* # the path item of the linked operation
* /users/{userid}/address:
* parameters:
* - name: userid
* in: path
* required: true
* description: the user identifier, as userId
* schema:
* type: string
* # linked operation
* get:
* operationId: getUserAddress
* responses:
* '200':
* description: the user's address
* ```
*
* When a runtime expression fails to evaluate, no parameter value is passed to the target operation.
*
* Values from the response body can be used to drive a linked operation.
*
* ```yaml
* links:
* address:
* operationId: getUserAddressByUUID
* parameters:
* # get the `uuid` field from the `uuid` field in the response body
* userUuid: $response.body#/uuid
* ```
*
* Clients follow all links at their discretion. Neither permissions, nor the capability to make a successful call to that link, is guaranteed solely by the existence of a relationship.
*
* **OperationRef Examples**
*
* As references to `operationId` MAY NOT be possible (the `operationId` is an optional field in an {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#operation-object Operation Object}), references MAY also be made through a relative `operationRef`:
*
* ```yaml
* links:
* UserRepositories:
* # returns array of '#/components/schemas/repository'
* operationRef: '#/paths/~12.0~1repositories~1{username}/get'
* parameters:
* username: $response.body#/username
* ```
*
* or an absolute `operationRef`:
*
* ```yaml
* links:
* UserRepositories:
* # returns array of '#/components/schemas/repository'
* operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get'
* parameters:
* username: $response.body#/username
* ```
*
* Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when using JSON references.
*
* **Runtime Expressions**
*
* Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. This mechanism is used by {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#link-object Link Objects} and {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object Callback Objects}.
*
* The runtime expression is defined by the following {@link https://tools.ietf.org/html/rfc5234 ABNF} syntax
*
* ```abnf
* expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source )
* source = ( header-reference / query-reference / path-reference / body-reference )
* header-reference = "header." token
* query-reference = "query." name
* path-reference = "path." name
* body-reference = "body" ["#" json-pointer ]
* json-pointer = *( "/" reference-token )
* reference-token = *( unescaped / escaped )
* unescaped = %x00-2E / %x30-7D / %x7F-10FFFF
* ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped'
* escaped = "~" ( "0" / "1" )
* ; representing '~' and '/', respectively
* name = *( CHAR )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
* "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
* ```
*
* Here, `json-pointer` is taken from {@link https://tools.ietf.org/html/rfc6901 RFC6901}, `char` from {@link https://tools.ietf.org/html/rfc7159#section-7 RFC7159} and `token` from {@link https://tools.ietf.org/html/rfc7230#section-3.2.6 RFC7230}.
*
* The `name` identifier is case-sensitive, whereas `token` is not.
*
* The table below provides examples of runtime expressions and examples of their use in a value:
*
* **Examples**
*
* | Source Location | example expression | notes |
* | -------- | ------- | ------- |
* | HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. |
* | Requested media type | `$request.header.accept` | |
* | Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. |
* | Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. |
* | Request URL | `$url` | |
* | Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. |
* | Response header | `$response.header.Server` | Single header values only are available |
*
* Runtime expressions preserve the