https://project.mdnd-it.cc/work_packages/94
This commit is contained in:
2025-08-23 04:25:28 +02:00
parent 725516ad6c
commit 19cfa031d0
25823 changed files with 1095587 additions and 2801760 deletions
@@ -0,0 +1,192 @@
Change Log
====================================================================================================
All notable changes will be documented in this file.
Swagger Parser adheres to [Semantic Versioning](http://semver.org/).
[v10.0.0](https://github.com/APIDevTools/swagger-parser/tree/v10.0.0) (2020-07-10)
----------------------------------------------------------------------------------------------------
#### Breaking Changes
- Removed the `YAML` export. We recommend using [`@stoplight/yaml`](https://www.npmjs.com/package/@stoplight/yaml) instead
#### Other Changes
- Added a new [`continueOnError` option](https://apitools.dev/swagger-parser/docs/options) that allows you to get all errors rather than just the first one
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v9.0.1...v10.0.0)
[v9.0.0](https://github.com/APIDevTools/swagger-parser/tree/v9.0.0) (2020-03-14)
----------------------------------------------------------------------------------------------------
- Moved Swagger Parser to the [@APIDevTools scope](https://www.npmjs.com/org/apidevtools) on NPM
- The "swagger-parser" NPM package is now just a wrapper around the scoped "@apidevtools/swagger-parser" package
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v8.0.4...v9.0.0)
[v8.0.0](https://github.com/APIDevTools/swagger-parser/tree/v8.0.0) (2019-06-22)
----------------------------------------------------------------------------------------------------
#### Potentially Breaking Changes
- [The `validate()` function](https://apitools.dev/swagger-parser/docs/swagger-parser.html#validateapi-options-callback) now uses [the official JSON Schemas](https://github.com/OAI/OpenAPI-Specification/tree/master/schemas) for Swagger 2.0 and OpenAPI 3.0 schema validation. We tested this change on [over 1,500 real-world APIs](https://apis.guru/browse-apis/) and there were **no breaking changes**, but we're bumped the major version number just to be safe.
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v7.0.1...v8.0.0)
[v7.0.0](https://github.com/APIDevTools/swagger-parser/tree/v7.0.0) (2019-06-12)
----------------------------------------------------------------------------------------------------
#### Breaking Changes
- Dropped support for Node 6
- Updated all code to ES6+ syntax (async/await, template literals, arrow functions, etc.)
- No longer including a pre-built bundle in the package. such as [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/), [Parcel](https://parceljs.org/), or [Browserify](http://browserify.org/) to include Swagger Parser in your app
#### Other Changes
- Added [TypeScript definitions](lib/index.d.ts)
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v6.0.5...v7.0.0)
[v6.0.0](https://github.com/APIDevTools/swagger-parser/tree/v6.0.0) (2018-10-05)
----------------------------------------------------------------------------------------------------
- Dropped support for [Bower](https://www.npmjs.com/package/bower), since it has been deprecated
- Removed the [`debug`](https://npmjs.com/package/debug) dependency
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v5.0.0...v6.0.0)
[v5.0.0](https://github.com/APIDevTools/swagger-parser/tree/v5.0.0) (2018-05-25)
----------------------------------------------------------------------------------------------------
- After [months](https://github.com/APIDevTools/swagger-parser/issues/62) and [months](https://github.com/APIDevTools/swagger-parser/issues/72) of delays, initial support for OpenAPI 3.0 is finally here! A big "Thank You!" to [Leo Long](https://github.com/yujunlong2000) for doing the work and submitting [PR #88](https://github.com/APIDevTools/swagger-parser/pull/88).
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v4.1.0...v5.0.0)
[v4.1.0](https://github.com/APIDevTools/swagger-parser/tree/v4.1.0) (2018-04-11)
----------------------------------------------------------------------------------------------------
- [@marcelstoer](https://github.com/marcelstoer) submitted [PR #83](https://github.com/APIDevTools/swagger-parser/pull/83) and [PR #84](https://github.com/APIDevTools/swagger-parser/pull/84), both of which improve the [`validate()` method](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#validateapi-options-callback). It will now detect when a JSON Schema in your API definition has `required` properties that don't exist.
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v4.0.0...v4.1.0)
[v4.0.0](https://github.com/APIDevTools/swagger-parser/tree/v4.0.0) (2017-10-19)
----------------------------------------------------------------------------------------------------
#### Breaking Changes
- Update the [Swagger 2.0 JSON schema](https://www.npmjs.com/package/swagger-schema-official), so it's possible that an API that previously passed validation may no longer pass due to changes in the Swagger schema
- To reduce the size of this library, it no longer includes polyfills for [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and [TypedArrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), which are natively supported in the latest versions of Node and web browsers. If you need to support older browsers (such as IE9), then just use [this `Promise` polyfill](https://github.com/stefanpenner/es6-promise) and [this `TypedArray` polyfill](https://github.com/inexorabletash/polyfill/blob/master/typedarray.js).
#### Minor Changes
- [PR #74](https://github.com/APIDevTools/swagger-parser/pull/74) - Fixes [an edge-case bug](https://github.com/APIDevTools/swagger-parser/issues/73) with the `validate()` method and `x-` vendor extensions
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v4.0.0-beta.2...v4.0.0)
[v4.0.0-beta.2](https://github.com/APIDevTools/swagger-parser/tree/v4.0.0-beta.2) (2016-04-25)
----------------------------------------------------------------------------------------------------
#### Just one small fix
Fixed [issue #13](https://github.com/APIDevTools/json-schema-ref-parser/issues/13). You can now pass a URL _and_ an object to any method.
```javascript
SwaggerParser.validate("http://example.com/my-schema.json", mySchemaObject, {})
```
> **NOTE:** As shown in the example above, you _must_ also pass an options object (even an empty object will work), otherwise, the method signature looks like you're just passing a URL and options.
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v4.4.0-beta.1...v4.0.0-beta.2)
[v4.0.0-beta.1](https://github.com/APIDevTools/swagger-parser/tree/v4.0.0-beta.1) (2016-04-10)
----------------------------------------------------------------------------------------------------
#### Plug-ins !!!
That's the major new feature in this version. Originally requested in [PR #8](https://github.com/APIDevTools/json-schema-ref-parser/pull/8), and refined a few times over the past few months, the plug-in API is now finalized and ready to use. You can now define your own [resolvers](https://github.com/APIDevTools/json-schema-ref-parser/blob/v3.0.0/docs/plugins/resolvers.md) and [parsers](https://github.com/APIDevTools/json-schema-ref-parser/blob/v3.0.0/docs/plugins/parsers.md).
#### Breaking Changes
The available [options have changed](https://github.com/APIDevTools/swagger-parser/blob/releases/4.0.0/docs/options.md), mostly due to the new plug-in API. There's not a one-to-one mapping of old options to new options, so you'll have to read the docs and determine which options you need to set. If any. The out-of-the-box configuration works for most people.
All of the [caching options have been removed](https://github.com/APIDevTools/json-schema-ref-parser/commit/1f4260184bfd370e9cd385b523fb08c098fac6db). Instead, files are now cached by default, and the entire cache is reset for each new parse operation. Caching options may come back in a future release, if there is enough demand for it. If you used the old caching options, please open an issue and explain your use-case and requirements. I need a better understanding of what caching functionality is actually needed by users.
#### Bug Fixes
Lots of little bug fixes, and a couple major bug fixes:
- [completely rewrote the bundling logic](https://github.com/APIDevTools/json-schema-ref-parser/commit/32510a38a29723fb24f56d30f055e7358acdd935) to fix [issue #16](https://github.com/APIDevTools/swagger-parser/issues/16)
- Added support for [root-level `$ref`s](https://github.com/APIDevTools/json-schema-ref-parser/issues/16)
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v3.3.0...v4.0.0-beta.1)
[v3.3.0](https://github.com/APIDevTools/swagger-parser/tree/v3.3.0) (2015-10-02)
----------------------------------------------------------------------------------------------------
Updated to the latest version of [the Official Swagger 2.0 Schema](https://www.npmjs.com/package/swagger-schema-official). The schema [hadn't been updated for six months](https://github.com/OAI/OpenAPI-Specification/issues/335), so Swagger Parser was missing [several recent changes](https://github.com/OAI/OpenAPI-Specification/commits/master/schemas/v2.0/schema.json).
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v3.2.0...v3.3.0)
[v3.2.0](https://github.com/APIDevTools/swagger-parser/tree/v3.2.0) (2015-10-01)
----------------------------------------------------------------------------------------------------
Swagger Parser now uses [call-me-maybe](https://www.npmjs.com/package/call-me-maybe) to support [promises or callbacks](https://github.com/APIDevTools/swagger-parser/tree/master/docs#callbacks-vs-promises).
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v3.1.0...v3.2.0)
[v3.1.0](https://github.com/APIDevTools/swagger-parser/tree/v3.1.0) (2015-09-28)
----------------------------------------------------------------------------------------------------
Fixed several bugs with circular references, particularly with the [`validate()`](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#validateapi-options-callback) method.
Added a new [`$refs.circular` option](https://github.com/APIDevTools/swagger-parser/blob/master/docs/options.md) to determine how circular references are handled. Options are fully-dereferencing them (default), throwing an error, or ignoring them.
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v3.0.0...v3.1.0)
[v3.0.0](https://github.com/APIDevTools/swagger-parser/tree/v3.0.0) (2015-09-25)
----------------------------------------------------------------------------------------------------
This is a **complete rewrite** of Swagger Parser. Major changes include:
**Swagger 2.0 Compliant**<br>
Previous versions of Swagger Parser were based on early drafts of Swagger 2.0, and were not compliant with [the final version of the spec](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md). Swagger Parser v3.0 is now compliant with the final spec as well as related specs, such as [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and [JSON Pointer](https://tools.ietf.org/html/rfc6901)
**All-New API**<br>
The old API only had a single method: `parse()`. But depending on which options you passed it, the method did _much_ more than its name implied. The new API has separate methods to make things a bit more intuitive. The most commonly used will be [`validate()`](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#validateapi-options-callback), [`bundle()`](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#bundleapi-options-callback), and [`dereference()`](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#dereferenceapi-options-callback). The [`parse()`](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#parseapi-options-callback) and [`resolve()`](https://github.com/APIDevTools/swagger-parser/blob/master/docs/swagger-parser.md#resolveapi-options-callback) methods are also available, but these are mostly just for internal use by the other methods.
**Asynchronous API**<br>
The old API was "asynchronous", but it relied on global state, so it did not support multiple simultaneous operations. The new API is truly asynchronous and supports both [ES6 Promises](http://javascriptplayground.com/blog/2015/02/promises/) and Node-style callbacks.
**New JSON Schema Validator**<br>
Swagger Parser has switched from [tv4](https://github.com/geraintluff/tv4) to [Z-Schema](https://github.com/zaggino/z-schema), which is [faster](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) and performs [more accurate validation](https://github.com/ebdrup/json-schema-benchmark#test-failure-summary). This means that some APIs that previously passed validation will now fail. But that's a _good_ thing!
[Full Changelog](https://github.com/APIDevTools/swagger-parser/compare/v2.5.0...v3.0.0)
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 James Messinger
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.
+146
View File
@@ -0,0 +1,146 @@
Swagger 2.0 and OpenAPI 3.0 parser/validator
============================
[![Build Status](https://github.com/APIDevTools/swagger-parser/workflows/CI-CD/badge.svg?branch=master)](https://github.com/APIDevTools/swagger-parser/actions)
[![Coverage Status](https://coveralls.io/repos/github/APIDevTools/swagger-parser/badge.svg?branch=master)](https://coveralls.io/github/APIDevTools/swagger-parser)
[![Tested on APIs.guru](https://api.apis.guru/badges/tested_on.svg)](https://apis.guru/browse-apis/)
[![npm](https://img.shields.io/npm/v/@apidevtools/swagger-parser.svg)](https://www.npmjs.com/package/@apidevtools/swagger-parser)
[![Dependencies](https://david-dm.org/APIDevTools/swagger-parser.svg)](https://david-dm.org/APIDevTools/swagger-parser)
[![License](https://img.shields.io/npm/l/@apidevtools/swagger-parser.svg)](LICENSE)
[![Buy us a tree](https://img.shields.io/badge/Treeware-%F0%9F%8C%B3-lightgreen)](https://plant.treeware.earth/APIDevTools/swagger-parser)
[![OS and Browser Compatibility](https://apitools.dev/img/badges/ci-badges-with-ie.svg)](https://github.com/APIDevTools/swagger-parser/actions)
[![Online Demo](https://apitools.dev/swagger-parser/online/img/demo.svg)](https://apitools.dev/swagger-parser/online/)
Features
--------------------------
- Parses Swagger specs in **JSON** or **YAML** format
- Validates against the [Swagger 2.0 schema](https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v2.0/schema.json) or [OpenAPI 3.0 Schema](https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v3.0/schema.json)
- [Resolves](https://apitools.dev/swagger-parser/docs/swagger-parser.html#resolveapi-options-callback) all `$ref` pointers, including external files and URLs
- Can [bundle](https://apitools.dev/swagger-parser/docs/swagger-parser.html#bundleapi-options-callback) all your Swagger files into a single file that only has _internal_ `$ref` pointers
- Can [dereference](https://apitools.dev/swagger-parser/docs/swagger-parser.html#dereferenceapi-options-callback) all `$ref` pointers, giving you a normal JavaScript object that's easy to work with
- **[Tested](https://github.com/APIDevTools/swagger-parser/actions)** in Node.js and all modern web browsers on Mac, Windows, and Linux
- Tested on **[over 1,500 real-world APIs](https://apis.guru/browse-apis/)** from Google, Microsoft, Facebook, Spotify, etc.
- Supports [circular references](https://apitools.dev/swagger-parser/docs/#circular-refs), nested references, back-references, and cross-references
- Maintains object reference equality &mdash; `$ref` pointers to the same value always resolve to the same object instance
Related Projects
--------------------------
- [Swagger CLI](https://github.com/APIDevTools/swagger-cli)
- [Swagger Express Middleware](https://github.com/APIDevTools/swagger-express-middleware)
Example
--------------------------
```javascript
SwaggerParser.validate(myAPI, (err, api) => {
if (err) {
console.error(err);
}
else {
console.log("API name: %s, Version: %s", api.info.title, api.info.version);
}
});
```
Or use `async`/`await` or [Promise](http://javascriptplayground.com/blog/2015/02/promises/) syntax instead. The following example is the same as above:
```javascript
try {
let api = await SwaggerParser.validate(myAPI);
console.log("API name: %s, Version: %s", api.info.title, api.info.version);
}
catch(err) {
console.error(err);
}
```
For more detailed examples, please see the [API Documentation](https://apitools.dev/swagger-parser/docs/)
Installation
--------------------------
Install using [npm](https://docs.npmjs.com/about-npm/):
```bash
npm install @apidevtools/swagger-parser
```
Usage
--------------------------
When using Swagger Parser in Node.js apps, you'll probably want to use **CommonJS** syntax:
```javascript
const SwaggerParser = require("@apidevtools/swagger-parser");
```
When using a transpiler such as [Babel](https://babeljs.io/) or [TypeScript](https://www.typescriptlang.org/), or a bundler such as [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/), you can use **ECMAScript modules** syntax instead:
```javascript
import SwaggerParser from "@apidevtools/swagger-parser";
```
Browser support
--------------------------
Swagger Parser supports recent versions of every major web browser. Older browsers may require [Babel](https://babeljs.io/) and/or [polyfills](https://babeljs.io/docs/en/next/babel-polyfill).
To use Swagger Parser in a browser, you'll need to use a bundling tool such as [Webpack](https://webpack.js.org/), [Rollup](https://rollupjs.org/), [Parcel](https://parceljs.org/), or [Browserify](http://browserify.org/). Some bundlers may require a bit of configuration, such as setting `browser: true` in [rollup-plugin-resolve](https://github.com/rollup/rollup-plugin-node-resolve).
API Documentation
--------------------------
Full API documentation is available [right here](https://apitools.dev/swagger-parser/docs/)
Contributing
--------------------------
I welcome any contributions, enhancements, and bug-fixes. [Open an issue](https://github.com/APIDevTools/swagger-parser/issues) on GitHub and [submit a pull request](https://github.com/APIDevTools/swagger-parser/pulls).
#### Building/Testing
To build/test the project locally on your computer:
1. __Clone this repo__<br>
`git clone https://github.com/APIDevTools/swagger-parser.git`
2. __Install dependencies__<br>
`npm install`
3. __Run the build script__<br>
`npm run build`
4. __Run the tests__<br>
`npm test`
License
--------------------------
Swagger Parser is 100% free and open-source, under the [MIT license](LICENSE). Use it however you want.
This package is [Treeware](http://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/APIDevTools/swagger-parser) to thank us for our work. By contributing to the Treeware forest youll be creating employment for local families and restoring wildlife habitats.
Big Thanks To
--------------------------
Thanks to these awesome companies for their support of Open Source developers ❤
[![GitHub](https://apitools.dev/img/badges/github.svg)](https://github.com/open-source)
[![NPM](https://apitools.dev/img/badges/npm.svg)](https://www.npmjs.com/)
[![Coveralls](https://apitools.dev/img/badges/coveralls.svg)](https://coveralls.io)
[![SauceLabs](https://apitools.dev/img/badges/sauce-labs.svg)](https://saucelabs.com)
@@ -0,0 +1,439 @@
import { OpenAPI } from "openapi-types";
export = SwaggerParser;
/**
* This is the default export of Swagger Parser. You can creates instances of this class using new SwaggerParser(), or you can just call its static methods.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html
*/
declare class SwaggerParser {
/**
* The `api` property is the parsed/bundled/dereferenced OpenAPI definition. This is the same value that is passed to the callback function (or Promise) when calling the parse, bundle, or dereference methods.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#api
*/
public api: OpenAPI.Document;
/**
* The $refs property is a `$Refs` object, which lets you access all of the externally-referenced files in the OpenAPI definition, as well as easily get and set specific values in the OpenAPI definition using JSON pointers.
*
* This is the same value that is passed to the callback function (or Promise) when calling the `resolve` method.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#refs
*/
public $refs: SwaggerParser.$Refs;
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#validateapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public validate(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public validate(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public validate(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public validate(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#validateapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public static validate(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static validate(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static validate(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static validate(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static validate(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Dereferences all `$ref` pointers in the OpenAPI definition, replacing each reference with its resolved value. This results in an API definition that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
*
* The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the API definition using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#dereferenceapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public dereference(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public dereference(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Dereferences all `$ref` pointers in the OpenAPI definition, replacing each reference with its resolved value. This results in an API definition that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
*
* The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the API definition using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#dereferenceapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the dereferenced OpenAPI definition
*/
public static dereference(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static dereference(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static dereference(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static dereference(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Bundles all referenced files/URLs into a single API definition that only has internal `$ref` pointers. This lets you split-up your API definition however you want while you're building it, but easily combine all those files together when it's time to package or distribute the API definition to other people. The resulting API definition size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
*
* This also eliminates the risk of circular references, so the API definition can be safely serialized using `JSON.stringify()`.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#bundleapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the bundled API definition object
*/
public bundle(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public bundle(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* Bundles all referenced files/URLs into a single API definition that only has internal `$ref` pointers. This lets you split-up your API definition however you want while you're building it, but easily combine all those files together when it's time to package or distribute the API definition to other people. The resulting API definition size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
*
* This also eliminates the risk of circular references, so the API definition can be safely serialized using `JSON.stringify()`.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#bundleapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive the bundled API definition object
*/
public static bundle(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static bundle(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static bundle(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static bundle(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Parses the given OpenAPI definition file (in JSON or YAML format), and returns it as a JavaScript object. This method `does not` resolve `$ref` pointers or dereference anything. It simply parses one file and returns it.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#parseapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page.
* @param options (optional)
* @param callback (optional) A callback that will receive the parsed OpenAPI definition object, or an error
*/
public parse(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public parse(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public parse(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public parse(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Parses the given OpenAPI definition file (in JSON or YAML format), and returns it as a JavaScript object. This method `does not` resolve `$ref` pointers or dereference anything. It simply parses one file and returns it.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#parseapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. The path can be absolute or relative. In Node, the path is relative to `process.cwd()`. In the browser, it's relative to the URL of the page.
* @param options (optional)
* @param callback (optional) A callback that will receive the parsed OpenAPI definition object, or an error
*/
public static parse(api: string | OpenAPI.Document, callback: SwaggerParser.ApiCallback): void;
public static parse(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.ApiCallback): void;
public static parse(api: string | OpenAPI.Document): Promise<OpenAPI.Document>;
public static parse(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
public static parse(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<OpenAPI.Document>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Resolves all JSON references (`$ref` pointers) in the given OpenAPI definition file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a `$Refs` object, which is a map of all the resolved references and their values.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#resolveapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive a `$Refs` object
*/
public resolve(api: string | OpenAPI.Document, callback: SwaggerParser.$RefsCallback): void;
public resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public resolve(api: string | OpenAPI.Document): Promise<SwaggerParser.$Refs>;
public resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
public resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
/**
* *This method is used internally by other methods, such as `bundle` and `dereference`. You probably won't need to call this method yourself.*
*
* Resolves all JSON references (`$ref` pointers) in the given OpenAPI definition file. If it references any other files/URLs, then they will be downloaded and resolved as well. This method **does not** dereference anything. It simply gives you a `$Refs` object, which is a map of all the resolved references and their values.
*
* See https://apitools.dev/swagger-parser/docs/swagger-parser.html#resolveapi-options-callback
*
* @param api An OpenAPI definition, or the file path or URL of an OpenAPI definition. See the `parse` method for more info.
* @param options (optional)
* @param callback (optional) A callback that will receive a `$Refs` object
*/
public static resolve(api: string | OpenAPI.Document, callback: SwaggerParser.$RefsCallback): void;
public static resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public static resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options, callback: SwaggerParser.$RefsCallback): void;
public static resolve(api: string | OpenAPI.Document): Promise<SwaggerParser.$Refs>;
public static resolve(api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
public static resolve(baseUrl: string, api: string | OpenAPI.Document, options: SwaggerParser.Options): Promise<SwaggerParser.$Refs>;
}
// eslint-disable-next-line no-redeclare
declare namespace SwaggerParser {
export type ApiCallback = (err: Error | null, api?: OpenAPI.Document) => any;
export type $RefsCallback = (err: Error | null, $refs?: $Refs) => any;
/**
* See https://apitools.dev/swagger-parser/docs/options.html
*/
export interface Options {
/**
* The `parse` options determine how different types of files will be parsed.
*
* JSON Schema `$Ref` Parser comes with built-in JSON, YAML, plain-text, and binary parsers, any of which you can configure or disable. You can also add your own custom parsers if you want.
*/
parse?: {
json?: ParserOptions | boolean;
yaml?: ParserOptions | boolean;
text?: (ParserOptions & { encoding?: string }) | boolean;
[key: string]: ParserOptions | boolean | undefined;
};
/**
* The `resolve` options control how Swagger Parser will resolve file paths and URLs, and how those files will be read/downloaded.
*
* JSON Schema `$Ref` Parser comes with built-in support for HTTP and HTTPS, as well as support for local files (when running in Node.js). You can configure or disable either of these built-in resolvers. You can also add your own custom resolvers if you want.
*/
resolve?: {
/**
* Determines whether external $ref pointers will be resolved. If this option is disabled, then external `$ref` pointers will simply be ignored.
*/
external?: boolean;
file?: Partial<ResolverOptions> | boolean;
http?: HTTPResolverOptions | boolean;
};
/**
* The `dereference` options control how JSON Schema `$Ref` Parser will dereference `$ref` pointers within the JSON schema.
*/
dereference?: {
/**
* Determines whether circular `$ref` pointers are handled.
*
* If set to `false`, then a `ReferenceError` will be thrown if the schema contains any circular references.
*
* If set to `"ignore"`, then circular references will simply be ignored. No error will be thrown, but the `$Refs.circular` property will still be set to `true`.
*/
circular?: boolean | "ignore";
};
/**
* The `validate` options control how Swagger Parser will validate the API.
*/
validate?: {
/**
* If set to `false`, then validating against the Swagger 2.0 Schema or OpenAPI 3.0 Schema is disabled.
*/
schema?: boolean;
/**
* If set to `false`, then validating against the Swagger 2.0 Specification is disabled.
*/
spec?: boolean;
};
}
export interface HTTPResolverOptions extends Partial<ResolverOptions> {
/**
* You can specify any HTTP headers that should be sent when downloading files. For example, some servers may require you to set the `Accept` or `Referrer` header.
*/
headers?: object;
/**
* The amount of time (in milliseconds) to wait for a response from the server when downloading files. The default is 5 seconds.
*/
timeout?: number;
/**
* The maximum number of HTTP redirects to follow per file. The default is 5. To disable automatic following of redirects, set this to zero.
*/
redirects?: number;
/**
* Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
*/
withCredentials?: boolean;
}
/**
* JSON Schema `$Ref` Parser comes with built-in resolvers for HTTP and HTTPS URLs, as well as local filesystem paths (when running in Node.js). You can add your own custom resolvers to support additional protocols, or even replace any of the built-in resolvers with your own custom implementation.
*
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html
*/
export interface ResolverOptions {
/**
* All resolvers have an order property, even the built-in resolvers. If you don't specify an order property, then your resolver will run last. Specifying `order: 1`, like we did in this example, will make your resolver run first. Or you can squeeze your resolver in-between some of the built-in resolvers. For example, `order: 101` would make it run after the file resolver, but before the HTTP resolver. You can see the order of all the built-in resolvers by looking at their source code.
*
* The order property and canRead property are related to each other. For each file that Swagger Parser needs to resolve, it first determines which resolvers can read that file by checking their canRead property. If only one resolver matches a file, then only that one resolver is called, regardless of its order. If multiple resolvers match a file, then those resolvers are tried in order until one of them successfully reads the file. Once a resolver successfully reads the file, the rest of the resolvers are skipped.
*/
order?: number;
/**
* The `canRead` property tells JSON Schema `$Ref` Parser what kind of files your resolver can read. In this example, we've simply specified a regular expression that matches "mogodb://" URLs, but we could have used a simple boolean, or even a function with custom logic to determine which files to resolve. Here are examples of each approach:
*/
canRead: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
/**
* This is where the real work of a resolver happens. The `read` method accepts the same file info object as the `canRead` function, but rather than returning a boolean value, the `read` method should return the contents of the file. The file contents should be returned in as raw a form as possible, such as a string or a byte array. Any further parsing or processing should be done by parsers.
*
* Unlike the `canRead` function, the `read` method can also be asynchronous. This might be important if your resolver needs to read data from a database or some other external source. You can return your asynchronous value using either an ES6 Promise or a Node.js-style error-first callback. Of course, if your resolver has the ability to return its data synchronously, then that's fine too. Here are examples of all three approaches:
*/
read(
file: FileInfo,
callback?: (error: Error | null, data: string | null) => any
): string | Buffer | Promise<string | Buffer>;
}
export interface ParserOptions {
/**
* Parsers run in a specific order, relative to other parsers. For example, a parser with `order: 5` will run before a parser with `order: 10`. If a parser is unable to successfully parse a file, then the next parser is tried, until one succeeds or they all fail.
*
* You can change the order in which parsers run, which is useful if you know that most of your referenced files will be a certain type, or if you add your own custom parser that you want to run first.
*/
order?: number;
/**
* All of the built-in parsers allow empty files by default. The JSON and YAML parsers will parse empty files as `undefined`. The text parser will parse empty files as an empty string. The binary parser will parse empty files as an empty byte array.
*
* You can set `allowEmpty: false` on any parser, which will cause an error to be thrown if a file empty.
*/
allowEmpty?: boolean;
/**
* Determines which parsers will be used for which files.
*
* A regular expression can be used to match files by their full path. A string (or array of strings) can be used to match files by their file extension. Or a function can be used to perform more complex matching logic. See the custom parser docs for details.
*/
canParse?: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
}
/**
* JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canRead()`, `read()`, `canParse()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed.
*
* The file info object currently only consists of a few properties, but it may grow in the future if plug-ins end up needing more information.
*
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
*/
export interface FileInfo {
/**
* The full URL of the file. This could be any type of URL, including "http://", "https://", "file://", "ftp://", "mongodb://", or even a local filesystem path (when running in Node.js).
*/
url: string;
/**
* The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
*/
extension: string;
/**
* The raw file contents, in whatever form they were returned by the resolver that read the file.
*/
data: string | Buffer;
}
/**
* When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of SwaggerParser objects.
*
* This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References.
*
* See https://apitools.dev/swagger-parser/docs/refs.html
*/
export class $Refs {
/**
* This property is true if the API definition contains any circular references. You may want to check this property before serializing the dereferenced API definition as JSON, since JSON.stringify() does not support circular references by default.
*
* See https://apitools.dev/swagger-parser/docs/refs.html#circular
*/
public circular: boolean;
/**
* Returns the paths/URLs of all the files in your API definition (including the main API definition file).
*
* See https://apitools.dev/swagger-parser/docs/refs.html#pathstypes
*
* @param types (optional) Optionally only return certain types of paths ("file", "http", etc.)
*/
public paths(...types: string[]): string[]
/**
* Returns a map of paths/URLs and their correspond values.
*
* See https://apitools.dev/swagger-parser/docs/refs.html#valuestypes
*
* @param types (optional) Optionally only return values from certain locations ("file", "http", etc.)
*/
public values(...types: string[]): { [url: string]: any }
/**
* Returns `true` if the given path exists in the OpenAPI definition; otherwise, returns `false`
*
* See https://apitools.dev/swagger-parser/docs/refs.html#existsref
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
*/
public exists($ref: string): boolean
/**
* Gets the value at the given path in the OpenAPI definition. Throws an error if the path does not exist.
*
* See https://apitools.dev/swagger-parser/docs/refs.html#getref
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
*/
public get($ref: string): any
/**
* Sets the value at the given path in the OpenAPI definition. If the property, or any of its parents, don't exist, they will be created.
*
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
* @param value The value to assign. Can be anything (object, string, number, etc.)
*/
public set($ref: string, value: any): void
}
}
@@ -0,0 +1,187 @@
/* eslint-disable no-unused-vars */
"use strict";
const validateSchema = require("./validators/schema");
const validateSpec = require("./validators/spec");
const normalizeArgs = require("@apidevtools/json-schema-ref-parser/lib/normalize-args");
const util = require("./util");
const Options = require("./options");
const maybe = require("call-me-maybe");
const { ono } = require("@jsdevtools/ono");
const $RefParser = require("@apidevtools/json-schema-ref-parser");
const dereference = require("@apidevtools/json-schema-ref-parser/lib/dereference");
module.exports = SwaggerParser;
/**
* This class parses a Swagger 2.0 or 3.0 API, resolves its JSON references and their resolved values,
* and provides methods for traversing, dereferencing, and validating the API.
*
* @class
* @augments $RefParser
*/
function SwaggerParser () {
$RefParser.apply(this, arguments);
}
util.inherits(SwaggerParser, $RefParser);
SwaggerParser.parse = $RefParser.parse;
SwaggerParser.resolve = $RefParser.resolve;
SwaggerParser.bundle = $RefParser.bundle;
SwaggerParser.dereference = $RefParser.dereference;
/**
* Alias {@link $RefParser#schema} as {@link SwaggerParser#api}
*/
Object.defineProperty(SwaggerParser.prototype, "api", {
configurable: true,
enumerable: true,
get () {
return this.schema;
}
});
/**
* Parses the given Swagger API.
* This method does not resolve any JSON references.
* It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
* @param {ParserOptions} [options] - Options that determine how the API is parsed
* @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
* @returns {Promise} - The returned promise resolves with the parsed API object.
*/
SwaggerParser.prototype.parse = async function (path, api, options, callback) {
let args = normalizeArgs(arguments);
args.options = new Options(args.options);
try {
let schema = await $RefParser.prototype.parse.call(this, args.path, args.schema, args.options);
if (schema.swagger) {
// Verify that the parsed object is a Swagger API
if (schema.swagger === undefined || schema.info === undefined || schema.paths === undefined) {
throw ono.syntax(`${args.path || args.schema} is not a valid Swagger API definition`);
}
else if (typeof schema.swagger === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('Swagger version number must be a string (e.g. "2.0") not a number.');
}
else if (typeof schema.info.version === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.');
}
else if (schema.swagger !== "2.0") {
throw ono.syntax(`Unrecognized Swagger version: ${schema.swagger}. Expected 2.0`);
}
}
else {
let supportedVersions = ["3.0.0", "3.0.1", "3.0.2", "3.0.3"];
// Verify that the parsed object is a Openapi API
if (schema.openapi === undefined || schema.info === undefined || schema.paths === undefined) {
throw ono.syntax(`${args.path || args.schema} is not a valid Openapi API definition`);
}
else if (typeof schema.openapi === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('Openapi version number must be a string (e.g. "3.0.0") not a number.');
}
else if (typeof schema.info.version === "number") {
// This is a very common mistake, so give a helpful error message
throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.');
}
else if (supportedVersions.indexOf(schema.openapi) === -1) {
throw ono.syntax(
`Unsupported OpenAPI version: ${schema.openapi}. ` +
`Swagger Parser only supports versions ${supportedVersions.join(", ")}`
);
}
}
// Looks good!
return maybe(args.callback, Promise.resolve(schema));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
* @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated
* @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
* @returns {Promise} - The returned promise resolves with the parsed API object.
*/
SwaggerParser.validate = function (path, api, options, callback) {
let Class = this; // eslint-disable-line consistent-this
let instance = new Class();
return instance.validate.apply(instance, arguments);
};
/**
* Parses, dereferences, and validates the given Swagger API.
* Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
*
* @param {string} [path] - The file path or URL of the JSON schema
* @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
* @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated
* @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
* @returns {Promise} - The returned promise resolves with the parsed API object.
*/
SwaggerParser.prototype.validate = async function (path, api, options, callback) {
let me = this;
let args = normalizeArgs(arguments);
args.options = new Options(args.options);
// ZSchema doesn't support circular objects, so don't dereference circular $refs yet
// (see https://github.com/zaggino/z-schema/issues/137)
let circular$RefOption = args.options.dereference.circular;
args.options.validate.schema && (args.options.dereference.circular = "ignore");
try {
await this.dereference(args.path, args.schema, args.options);
// Restore the original options, now that we're done dereferencing
args.options.dereference.circular = circular$RefOption;
if (args.options.validate.schema) {
// Validate the API against the Swagger schema
// NOTE: This is safe to do, because we haven't dereferenced circular $refs yet
validateSchema(me.api);
if (me.$refs.circular) {
if (circular$RefOption === true) {
// The API has circular references,
// so we need to do a second-pass to fully-dereference it
dereference(me, args.options);
}
else if (circular$RefOption === false) {
// The API has circular references, and they're not allowed, so throw an error
throw ono.reference("The API contains circular references");
}
}
}
if (args.options.validate.spec) {
// Validate the API against the Swagger spec
validateSpec(me.api);
}
return maybe(args.callback, Promise.resolve(me.schema));
}
catch (err) {
return maybe(args.callback, Promise.reject(err));
}
};
/**
* The Swagger object
* https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
*
* @typedef {{swagger: string, info: {}, paths: {}}} SwaggerObject
*/
@@ -0,0 +1,35 @@
"use strict";
const $RefParserOptions = require("@apidevtools/json-schema-ref-parser/lib/options");
const schemaValidator = require("./validators/schema");
const specValidator = require("./validators/spec");
const util = require("util");
module.exports = ParserOptions;
/**
* Options that determine how Swagger APIs are parsed, resolved, dereferenced, and validated.
*
* @param {object|ParserOptions} [_options] - Overridden options
* @class
* @augments $RefParserOptions
*/
function ParserOptions (_options) {
$RefParserOptions.call(this, ParserOptions.defaults);
$RefParserOptions.apply(this, arguments);
}
ParserOptions.defaults = {
/**
* Determines how the API definition will be validated.
*
* You can add additional validators of your own, replace an existing one with
* your own implemenation, or disable any validator by setting it to false.
*/
validate: {
schema: schemaValidator,
spec: specValidator,
},
};
util.inherits(ParserOptions, $RefParserOptions);
@@ -0,0 +1,11 @@
"use strict";
const util = require("util");
exports.format = util.format;
exports.inherits = util.inherits;
/**
* Regular Expression that matches Swagger path params.
*/
exports.swaggerParamRegExp = /\{([^/}]+)}/g;
@@ -0,0 +1,70 @@
"use strict";
const util = require("../util");
const { ono } = require("@jsdevtools/ono");
const ZSchema = require("z-schema");
const { openapi } = require("@apidevtools/openapi-schemas");
module.exports = validateSchema;
let zSchema = initializeZSchema();
/**
* Validates the given Swagger API against the Swagger 2.0 or 3.0 schema.
*
* @param {SwaggerObject} api
*/
function validateSchema (api) {
// Choose the appropriate schema (Swagger or OpenAPI)
let schema = api.swagger ? openapi.v2 : openapi.v3;
// Validate against the schema
let isValid = zSchema.validate(api, schema);
if (!isValid) {
let err = zSchema.getLastError();
let message = "Swagger schema validation failed. \n" + formatZSchemaError(err.details);
throw ono.syntax(err, { details: err.details }, message);
}
}
/**
* Performs one-time initialization logic to prepare for Swagger Schema validation.
*/
function initializeZSchema () {
// HACK: Delete the OpenAPI schema IDs because ZSchema can't resolve them
delete openapi.v2.id;
delete openapi.v3.id;
// The OpenAPI 3.0 schema uses "uri-reference" formats.
// Assume that any non-whitespace string is valid.
ZSchema.registerFormat("uri-reference", (value) => value.trim().length > 0);
// Configure ZSchema
return new ZSchema({
breakOnFirstError: true,
noExtraKeywords: true,
ignoreUnknownFormats: false,
reportPathAsArray: true
});
}
/**
* Z-Schema validation errors are a nested tree structure.
* This function crawls that tree and builds an error message string.
*
* @param {object[]} errors - The Z-Schema error details
* @param {string} [indent] - The whitespace used to indent the error message
* @returns {string}
*/
function formatZSchemaError (errors, indent) {
indent = indent || " ";
let message = "";
for (let error of errors) {
message += util.format(`${indent}${error.message} at #/${error.path.join("/")}\n`);
if (error.inner) {
message += formatZSchemaError(error.inner, indent + " ");
}
}
return message;
}
@@ -0,0 +1,344 @@
"use strict";
const util = require("../util");
const { ono } = require("@jsdevtools/ono");
const swaggerMethods = require("@apidevtools/swagger-methods");
const primitiveTypes = ["array", "boolean", "integer", "number", "string"];
const schemaTypes = ["array", "boolean", "integer", "number", "string", "object", "null", undefined];
module.exports = validateSpec;
/**
* Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema.
*
* @param {SwaggerObject} api
*/
function validateSpec (api) {
if (api.openapi) {
// We don't (yet) support validating against the OpenAPI spec
return;
}
let paths = Object.keys(api.paths || {});
let operationIds = [];
for (let pathName of paths) {
let path = api.paths[pathName];
let pathId = "/paths" + pathName;
if (path && pathName.indexOf("/") === 0) {
validatePath(api, path, pathId, operationIds);
}
}
let definitions = Object.keys(api.definitions || {});
for (let definitionName of definitions) {
let definition = api.definitions[definitionName];
let definitionId = "/definitions/" + definitionName;
validateRequiredPropertiesExist(definition, definitionId);
}
}
/**
* Validates the given path.
*
* @param {SwaggerObject} api - The entire Swagger API object
* @param {object} path - A Path object, from the Swagger API
* @param {string} pathId - A value that uniquely identifies the path
* @param {string} operationIds - An array of collected operationIds found in other paths
*/
function validatePath (api, path, pathId, operationIds) {
for (let operationName of swaggerMethods) {
let operation = path[operationName];
let operationId = pathId + "/" + operationName;
if (operation) {
let declaredOperationId = operation.operationId;
if (declaredOperationId) {
if (operationIds.indexOf(declaredOperationId) === -1) {
operationIds.push(declaredOperationId);
}
else {
throw ono.syntax(`Validation failed. Duplicate operation id '${declaredOperationId}'`);
}
}
validateParameters(api, path, pathId, operation, operationId);
let responses = Object.keys(operation.responses || {});
for (let responseName of responses) {
let response = operation.responses[responseName];
let responseId = operationId + "/responses/" + responseName;
validateResponse(responseName, (response || {}), responseId);
}
}
}
}
/**
* Validates the parameters for the given operation.
*
* @param {SwaggerObject} api - The entire Swagger API object
* @param {object} path - A Path object, from the Swagger API
* @param {string} pathId - A value that uniquely identifies the path
* @param {object} operation - An Operation object, from the Swagger API
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validateParameters (api, path, pathId, operation, operationId) {
let pathParams = path.parameters || [];
let operationParams = operation.parameters || [];
// Check for duplicate path parameters
try {
checkForDuplicates(pathParams);
}
catch (e) {
throw ono.syntax(e, `Validation failed. ${pathId} has duplicate parameters`);
}
// Check for duplicate operation parameters
try {
checkForDuplicates(operationParams);
}
catch (e) {
throw ono.syntax(e, `Validation failed. ${operationId} has duplicate parameters`);
}
// Combine the path and operation parameters,
// with the operation params taking precedence over the path params
let params = pathParams.reduce((combinedParams, value) => {
let duplicate = combinedParams.some((param) => {
return param.in === value.in && param.name === value.name;
});
if (!duplicate) {
combinedParams.push(value);
}
return combinedParams;
}, operationParams.slice());
validateBodyParameters(params, operationId);
validatePathParameters(params, pathId, operationId);
validateParameterTypes(params, api, operation, operationId);
}
/**
* Validates body and formData parameters for the given operation.
*
* @param {object[]} params - An array of Parameter objects
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validateBodyParameters (params, operationId) {
let bodyParams = params.filter((param) => { return param.in === "body"; });
let formParams = params.filter((param) => { return param.in === "formData"; });
// There can only be one "body" parameter
if (bodyParams.length > 1) {
throw ono.syntax(
`Validation failed. ${operationId} has ${bodyParams.length} body parameters. Only one is allowed.`,
);
}
else if (bodyParams.length > 0 && formParams.length > 0) {
// "body" params and "formData" params are mutually exclusive
throw ono.syntax(
`Validation failed. ${operationId} has body parameters and formData parameters. Only one or the other is allowed.`,
);
}
}
/**
* Validates path parameters for the given path.
*
* @param {object[]} params - An array of Parameter objects
* @param {string} pathId - A value that uniquely identifies the path
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validatePathParameters (params, pathId, operationId) {
// Find all {placeholders} in the path string
let placeholders = pathId.match(util.swaggerParamRegExp) || [];
// Check for duplicates
for (let i = 0; i < placeholders.length; i++) {
for (let j = i + 1; j < placeholders.length; j++) {
if (placeholders[i] === placeholders[j]) {
throw ono.syntax(
`Validation failed. ${operationId} has multiple path placeholders named ${placeholders[i]}`);
}
}
}
params = params.filter((param) => { return param.in === "path"; });
for (let param of params) {
if (param.required !== true) {
throw ono.syntax(
"Validation failed. Path parameters cannot be optional. " +
`Set required=true for the "${param.name}" parameter at ${operationId}`,
);
}
let match = placeholders.indexOf("{" + param.name + "}");
if (match === -1) {
throw ono.syntax(
`Validation failed. ${operationId} has a path parameter named "${param.name}", ` +
`but there is no corresponding {${param.name}} in the path string`
);
}
placeholders.splice(match, 1);
}
if (placeholders.length > 0) {
throw ono.syntax(`Validation failed. ${operationId} is missing path parameter(s) for ${placeholders}`);
}
}
/**
* Validates data types of parameters for the given operation.
*
* @param {object[]} params - An array of Parameter objects
* @param {object} api - The entire Swagger API object
* @param {object} operation - An Operation object, from the Swagger API
* @param {string} operationId - A value that uniquely identifies the operation
*/
function validateParameterTypes (params, api, operation, operationId) {
for (let param of params) {
let parameterId = operationId + "/parameters/" + param.name;
let schema, validTypes;
switch (param.in) {
case "body":
schema = param.schema;
validTypes = schemaTypes;
break;
case "formData":
schema = param;
validTypes = primitiveTypes.concat("file");
break;
default:
schema = param;
validTypes = primitiveTypes;
}
validateSchema(schema, parameterId, validTypes);
validateRequiredPropertiesExist(schema, parameterId);
if (schema.type === "file") {
// "file" params must consume at least one of these MIME types
let formData = /multipart\/(.*\+)?form-data/;
let urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/;
let consumes = operation.consumes || api.consumes || [];
let hasValidMimeType = consumes.some((consume) => {
return formData.test(consume) || urlEncoded.test(consume);
});
if (!hasValidMimeType) {
throw ono.syntax(
`Validation failed. ${operationId} has a file parameter, so it must consume multipart/form-data ` +
"or application/x-www-form-urlencoded",
);
}
}
}
}
/**
* Checks the given parameter list for duplicates, and throws an error if found.
*
* @param {object[]} params - An array of Parameter objects
*/
function checkForDuplicates (params) {
for (let i = 0; i < params.length - 1; i++) {
let outer = params[i];
for (let j = i + 1; j < params.length; j++) {
let inner = params[j];
if (outer.name === inner.name && outer.in === inner.in) {
throw ono.syntax(`Validation failed. Found multiple ${outer.in} parameters named "${outer.name}"`);
}
}
}
}
/**
* Validates the given response object.
*
* @param {string} code - The HTTP response code (or "default")
* @param {object} response - A Response object, from the Swagger API
* @param {string} responseId - A value that uniquely identifies the response
*/
function validateResponse (code, response, responseId) {
if (code !== "default" && (code < 100 || code > 599)) {
throw ono.syntax(`Validation failed. ${responseId} has an invalid response code (${code})`);
}
let headers = Object.keys(response.headers || {});
for (let headerName of headers) {
let header = response.headers[headerName];
let headerId = responseId + "/headers/" + headerName;
validateSchema(header, headerId, primitiveTypes);
}
if (response.schema) {
let validTypes = schemaTypes.concat("file");
if (validTypes.indexOf(response.schema.type) === -1) {
throw ono.syntax(
`Validation failed. ${responseId} has an invalid response schema type (${response.schema.type})`);
}
else {
validateSchema(response.schema, responseId + "/schema", validTypes);
}
}
}
/**
* Validates the given Swagger schema object.
*
* @param {object} schema - A Schema object, from the Swagger API
* @param {string} schemaId - A value that uniquely identifies the schema object
* @param {string[]} validTypes - An array of the allowed schema types
*/
function validateSchema (schema, schemaId, validTypes) {
if (validTypes.indexOf(schema.type) === -1) {
throw ono.syntax(
`Validation failed. ${schemaId} has an invalid type (${schema.type})`);
}
if (schema.type === "array" && !schema.items) {
throw ono.syntax(`Validation failed. ${schemaId} is an array, so it must include an "items" schema`);
}
}
/**
* Validates that the declared properties of the given Swagger schema object actually exist.
*
* @param {object} schema - A Schema object, from the Swagger API
* @param {string} schemaId - A value that uniquely identifies the schema object
*/
function validateRequiredPropertiesExist (schema, schemaId) {
/**
* Recursively collects all properties of the schema and its ancestors. They are added to the props object.
*/
function collectProperties (schemaObj, props) {
if (schemaObj.properties) {
for (let property in schemaObj.properties) {
if (schemaObj.properties.hasOwnProperty(property)) {
props[property] = schemaObj.properties[property];
}
}
}
if (schemaObj.allOf) {
for (let parent of schemaObj.allOf) {
collectProperties(parent, props);
}
}
}
if (schema.required && Array.isArray(schema.required)) {
let props = {};
collectProperties(schema, props);
for (let requiredProperty of schema.required) {
if (!props[requiredProperty]) {
throw ono.syntax(
`Validation failed. Property '${requiredProperty}' listed as required but does not exist in '${schemaId}'`
);
}
}
}
}
@@ -0,0 +1,87 @@
{
"name": "@apidevtools/swagger-parser",
"version": "10.0.3",
"description": "Swagger 2.0 and OpenAPI 3.0 parser and validator for Node and browsers",
"keywords": [
"swagger",
"openapi",
"open-api",
"json",
"yaml",
"parse",
"parser",
"validate",
"validator",
"validation",
"spec",
"specification",
"schema",
"reference",
"dereference"
],
"author": {
"name": "James Messinger",
"url": "https://jamesmessinger.com"
},
"homepage": "https://apitools.dev/swagger-parser/",
"repository": {
"type": "git",
"url": "https://github.com/APIDevTools/swagger-parser.git"
},
"license": "MIT",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"files": [
"lib"
],
"scripts": {
"clean": "shx rm -rf .nyc_output coverage",
"lint": "eslint lib test online/src/js",
"build": "npm run build:website && npm run build:sass",
"build:website": "simplifyify online/src/js/index.js --outfile online/js/bundle.js --bundle --debug --minify",
"build:sass": "node-sass --source-map true --output-style compressed online/src/scss/style.scss online/css/style.min.css",
"test": "npm run test:node && npm run test:typescript && npm run test:browser && npm run lint",
"test:node": "mocha",
"test:browser": "karma start --single-run",
"test:typescript": "tsc --noEmit --strict --lib esnext,dom test/specs/typescript-definition.spec.ts",
"coverage": "npm run coverage:node && npm run coverage:browser",
"coverage:node": "nyc node_modules/mocha/bin/mocha",
"coverage:browser": "npm run test:browser -- --coverage",
"upgrade": "npm-check -u && npm audit fix",
"bump": "bump --tag --push --all",
"release": "npm run upgrade && npm run clean && npm run build && npm test && npm run bump"
},
"devDependencies": {
"@babel/polyfill": "^7.11.5",
"@jsdevtools/eslint-config": "^1.1.4",
"@jsdevtools/host-environment": "^2.1.2",
"@jsdevtools/karma-config": "^3.1.7",
"@jsdevtools/version-bump-prompt": "^6.1.0",
"@types/node": "^14.6.4",
"chai": "^4.2.0",
"eslint": "^7.8.1",
"js-yaml": "^3.14.0",
"karma": "^5.2.1",
"karma-cli": "^2.0.0",
"mocha": "^8.1.3",
"node-fetch": "^2.6.1",
"node-sass": "^4.14.1",
"npm-check": "^5.9.0",
"nyc": "^15.1.0",
"openapi-types": "^7.0.1",
"shx": "^0.3.2",
"simplifyify": "^8.0.3",
"typescript": "^4.0.2"
},
"dependencies": {
"@apidevtools/json-schema-ref-parser": "^9.0.6",
"@apidevtools/openapi-schemas": "^2.0.4",
"@apidevtools/swagger-methods": "^3.0.2",
"@jsdevtools/ono": "^7.1.3",
"call-me-maybe": "^1.0.1",
"z-schema": "^5.0.1"
},
"peerDependencies": {
"openapi-types": ">=7"
}
}