oas 24.9.0 → 25.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -5
- package/dist/analyzer/index.cjs +2 -2
- package/dist/analyzer/index.js +1 -1
- package/dist/{chunk-YX5TCZYW.cjs → chunk-OEMVNKDJ.cjs} +2 -2
- package/dist/chunk-OEMVNKDJ.cjs.map +1 -0
- package/dist/{chunk-2PJJRTP6.js → chunk-SGDW7HEE.js} +2 -2
- package/dist/chunk-SGDW7HEE.js.map +1 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/reducer/index.cjs.map +1 -1
- package/dist/reducer/index.js.map +1 -1
- package/package.json +4 -4
- package/dist/chunk-2PJJRTP6.js.map +0 -1
- package/dist/chunk-YX5TCZYW.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ npm install oas
|
|
|
51
51
|
|
|
52
52
|
## Usage
|
|
53
53
|
|
|
54
|
-
>
|
|
54
|
+
> [!NOTE]
|
|
55
55
|
> If you need to use this library within a browser you'll likely need to use a bundler like [Webpack](https://webpack.js.org/) or [Rollup](https://rollupjs.org/).
|
|
56
56
|
|
|
57
57
|
`oas` offers a main `Oas` class, which will be your main entrypoint for using the library.
|
|
@@ -113,7 +113,7 @@ Because this library has full TypeScript types and docblocks this README is not
|
|
|
113
113
|
|
|
114
114
|
#### Specification Extensions
|
|
115
115
|
|
|
116
|
-
>
|
|
116
|
+
> [!NOTE]
|
|
117
117
|
> Optionally you can also supply an instance of the `Operation` to both of these methods to see or retrieve a given extension if it exists on that operation but if it exists in both the operation and at the root the operation-level extension will be prioritized.
|
|
118
118
|
|
|
119
119
|
<!-- prettier-ignore-start -->
|
|
@@ -135,8 +135,6 @@ Information about ReadMe's supported OpenAPI extensions at https://docs.readme.c
|
|
|
135
135
|
| `.getAuth()` | Retrieve the appropriate API keys for the current OpenAPI definition from an object of user data. Check out [Using Variables in Documentation](https://docs.readme.com/docs/user-data-options#using-variables-in-documentation) for some background on how we use this. |
|
|
136
136
|
<!-- prettier-ignore-end -->
|
|
137
137
|
|
|
138
|
-
---
|
|
139
|
-
|
|
140
138
|
### Operations
|
|
141
139
|
|
|
142
140
|
For your convenience, the entrypoint into the `Operation` class should generally always be through `.operation()`. For example:
|
|
@@ -183,7 +181,7 @@ const operation = petstore.operation('/pet', 'post');
|
|
|
183
181
|
|
|
184
182
|
#### Parameters
|
|
185
183
|
|
|
186
|
-
>
|
|
184
|
+
> [!NOTE]
|
|
187
185
|
> All parameter accessors here support, and will automatically retrieve and handle, common parameters that may be set at the [path item level](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathItemObject).
|
|
188
186
|
|
|
189
187
|
<!-- prettier-ignore-start -->
|
|
@@ -254,6 +252,72 @@ The `Callback` class inherits `Operation` so every API available on instances of
|
|
|
254
252
|
|
|
255
253
|
Because our `Webhook` class extends `Operation`, every API that's available on the [Operation](#operation) class is available on webhooks.
|
|
256
254
|
|
|
255
|
+
### Additional Utilities
|
|
256
|
+
|
|
257
|
+
Beyond the `Oas`, `Operation`, `Callback` and `Webhook` interfaces, the `oas` library also offers additional tooling for analyzing and troubleshooting OpenAPI definitions.
|
|
258
|
+
|
|
259
|
+
#### Analyzer
|
|
260
|
+
|
|
261
|
+
The analyzer, `oas/analyzer`, allows you to run a set of query analyses on your API definition to understand the complexity of your API definition.
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import petstore from '@readme/oas-examples/3.0/json/petstore.json';
|
|
265
|
+
import analyzer from 'oas/analyzer';
|
|
266
|
+
|
|
267
|
+
console.log(await analyzer(petstore));
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
##### General
|
|
271
|
+
|
|
272
|
+
<!-- prettier-ignore-start -->
|
|
273
|
+
| Metric | Description |
|
|
274
|
+
| :--- | :--- |
|
|
275
|
+
| `mediaTypes` | What are the different media type shapes that your API operations support? |
|
|
276
|
+
| `operationTotal` | The total amount of operations in your definition. |
|
|
277
|
+
| `securityTypes` | The different types of security that your API contains. |
|
|
278
|
+
<!-- prettier-ignore-end -->
|
|
279
|
+
|
|
280
|
+
##### OpenAPI Features
|
|
281
|
+
|
|
282
|
+
<!-- prettier-ignore-start -->
|
|
283
|
+
| Metric | Description |
|
|
284
|
+
| :--- | :--- |
|
|
285
|
+
| `additionalProperties` | Does your API use `additionalProperties`? |
|
|
286
|
+
| `callbacks` | Does your API use [callbacks](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#callback-object)? |
|
|
287
|
+
| `circularRefs` | Does your API have any circular `$ref` pointers, and if so where are they located? |
|
|
288
|
+
| `discriminators` | Does your API use polymorphic [discriminators](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#discriminator-object)? |
|
|
289
|
+
| `links` | Does your API use [links](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#link-object)? |
|
|
290
|
+
| `style` | Do any parameters in your API require [style](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#user-content-parameterstyle) serialization?
|
|
291
|
+
| `polymorphism` | Does your API use [polymorphism](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#composition-and-inheritance-polymorphism) (`anyOf`, `oneOf`, `allOf`)? |
|
|
292
|
+
| `serverVariables` | Does your API use [server variables](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#server-variable-object)? |
|
|
293
|
+
| `webhooks` | Does your API use [webhooks](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#oasWebhooks)?
|
|
294
|
+
| `xml` | Does any parameter or schema in your API use the [XML object](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#xml-object) for declaring how a schema should be treated in XML? |
|
|
295
|
+
<!-- prettier-ignore-end -->
|
|
296
|
+
|
|
297
|
+
#### Reducer
|
|
298
|
+
|
|
299
|
+
The reducer, `oas/reducer`, can be used to reduce an OpenAPI definition down to only the information necessary for a specific set of tags, paths, or operations. OpenAPI reduction can be helpful to isolate and troubleshoot issues with a very large API definition -- all while still having a fully functional and valid OpenAPI definition.
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
import petstore from '@readme/oas-examples/3.0/json/petstore.json';
|
|
303
|
+
import reducer from 'oas/reducer';
|
|
304
|
+
|
|
305
|
+
// This will reduce the `petstore` API definition down to only operations, and
|
|
306
|
+
// any referenced schemas, that are a part of the `Store` tag.
|
|
307
|
+
console.log(reducer(petstore, { tags: ['Store'] }));
|
|
308
|
+
|
|
309
|
+
// Reduces the `petstore` down to only the `POST /pet` operation.
|
|
310
|
+
console.log(reducer(petstore, { paths: { '/pet': ['post'] } });
|
|
311
|
+
|
|
312
|
+
// You can also select all of the methods of a given path by using the `*`
|
|
313
|
+
// wildcard. The resulting reduced API definition here will contain `POST /pet`
|
|
314
|
+
// and `PUT /put`.
|
|
315
|
+
console.log(reducer(petstore, { paths: { '/pet': ['*'] } });
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
> [!NOTE]
|
|
319
|
+
> Though the reducer does not require you to first dereference your API definition it currently unfortunately cannot, depending on the circumstances, be used to dereference an API operation that has circular `$ref` pointers.
|
|
320
|
+
|
|
257
321
|
## FAQ
|
|
258
322
|
|
|
259
323
|
#### Can I create an OpenAPI definition with this?
|
package/dist/analyzer/index.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkOEMVNKDJcjs = require('../chunk-OEMVNKDJ.cjs');
|
|
4
4
|
require('../chunk-3FVUMJJI.cjs');
|
|
5
5
|
require('../chunk-VIIXOUMH.cjs');
|
|
6
6
|
require('../chunk-OD3GKGB2.cjs');
|
|
@@ -19,7 +19,7 @@ function callbacks(definition) {
|
|
|
19
19
|
return _chunkW6GBV2JTcjs.query.call(void 0, ["$.components.callbacks", "$.paths..callbacks"], definition).map((res) => _chunkW6GBV2JTcjs.refizePointer.call(void 0, res.pointer));
|
|
20
20
|
}
|
|
21
21
|
async function circularRefs(definition) {
|
|
22
|
-
const oas = new (0,
|
|
22
|
+
const oas = new (0, _chunkOEMVNKDJcjs.Oas)(JSON.parse(JSON.stringify(definition)));
|
|
23
23
|
await oas.dereference();
|
|
24
24
|
const results = oas.getCircularReferences();
|
|
25
25
|
results.sort();
|
package/dist/analyzer/index.js
CHANGED
|
@@ -160,7 +160,7 @@ function generatePathMatches(paths, pathName, origin) {
|
|
|
160
160
|
function filterPathMethods(pathMatches, targetMethod) {
|
|
161
161
|
const regExp = _pathtoregexp.pathToRegexp.call(void 0, targetMethod);
|
|
162
162
|
return pathMatches.map((p) => {
|
|
163
|
-
const captures = Object.keys(p.operation).filter((r) => regExp.exec(r));
|
|
163
|
+
const captures = Object.keys(p.operation).filter((r) => regExp.regexp.exec(r));
|
|
164
164
|
if (captures.length) {
|
|
165
165
|
const method = captures[0];
|
|
166
166
|
p.url.method = method.toUpperCase();
|
|
@@ -775,4 +775,4 @@ var Oas = class _Oas {
|
|
|
775
775
|
|
|
776
776
|
|
|
777
777
|
exports.Oas = Oas;
|
|
778
|
-
//# sourceMappingURL=chunk-
|
|
778
|
+
//# sourceMappingURL=chunk-OEMVNKDJ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/get-auth.ts","../src/lib/get-user-variable.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,gBAAgB;AACvB,SAAS,cAAc,aAAa;;;ACGpC,SAAS,OAAO,MAAkB,QAAkD;AAClF,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,KAAK,OAAO,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,KAAK;AAAA,IAEpE,KAAK;AACH,UAAI,OAAO,WAAW,SAAS;AAC7B,eAAO,KAAK,OAAO,IAAI,KAA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AAW;AAE9B,WAAO,OACJ,YAAY,OAAO,CAAC,GAAG;AAAA,MACtB,SAAS;AAAA;AAAA,QAEP,UAAU;AAAA,MACZ;AAAA,MACA,aAAa;AAAA;AAAA;AAAA,QAGX,UAAU;AAAA,MACZ;AAAA,IACF,CAAC,EACA,KAAK,CAAC,iBAAoC;AACzC,UAAI,eAAyB,CAAC;AAC9B,UAAI,OAAO,MAAM,UAAU;AACzB,uBAAe,OAAO,MAAM,aAAa,IAAI,aAAW;AAKtD,iBAAO,IAAI,QAAQ,MAAM,GAAG,EAAE,CAAC,CAAC;AAAA,QAClC,CAAC;AAAA,MACH;AAEA,WAAK,MAAM;AAEX,WAAK,WAAW;AAChB,WAAK,gBAAgB;AAAA,QACnB,YAAY;AAAA,QACZ,UAAU;AAAA,QACV;AAAA,MACF;AAGA,UAAI,KAAK,IAAI;AACX,aAAK,GAAG;AAAA,MACV;AAAA,IACF,CAAC,EACA,KAAK,MAAM;AACV,aAAO,KAAK,SAAS,IAAI,cAAY,SAAS,QAAQ,CAAC;AAAA,IACzD,CAAC;AAAA,EACL;AACF","sourcesContent":["import type { Extensions } from './extensions.js';\nimport type * as RMOAS from './types.js';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { Match, ParamData } from 'path-to-regexp';\n\nimport $RefParser from '@readme/json-schema-ref-parser';\nimport { pathToRegexp, match } from 'path-to-regexp';\n\nimport {\n CODE_SAMPLES,\n HEADERS,\n OAUTH_OPTIONS,\n PARAMETER_ORDERING,\n SAMPLES_LANGUAGES,\n extensionDefaults,\n getExtension,\n hasRootExtension,\n validateParameterOrdering,\n} from './extensions.js';\nimport { getAuth } from './lib/get-auth.js';\nimport getUserVariable from './lib/get-user-variable.js';\nimport { isPrimitive } from './lib/helpers.js';\nimport { Operation, Webhook } from './operation/index.js';\nimport { findSchemaDefinition, supportedMethods } from './utils.js';\n\ninterface PathMatch {\n match?: Match<ParamData>;\n operation: RMOAS.PathsObject;\n url: {\n method?: RMOAS.HttpMethods;\n nonNormalizedPath: string;\n origin: string;\n path: string;\n slugs: Record<string, string>;\n };\n}\ntype PathMatches = PathMatch[];\n\nconst SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\\]]+)}/g;\n\nfunction ensureProtocol(url: string) {\n // Add protocol to urls starting with // e.g. //example.com\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (url.match(/^\\/\\//)) {\n return `https:${url}`;\n }\n\n // Add protocol to urls with no // within them\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (!url.match(/\\/\\//)) {\n return `https://${url}`;\n }\n\n return url;\n}\n\nfunction stripTrailingSlash(url: string) {\n if (url[url.length - 1] === '/') {\n return url.slice(0, -1);\n }\n\n return url;\n}\n\n/**\n * Normalize a OpenAPI server URL by ensuring that it has a proper HTTP protocol and doesn't have a\n * trailing slash.\n *\n * @param api The API definition that we're processing.\n * @param selected The index of the `servers` array in the API definition that we want to normalize.\n */\nfunction normalizedUrl(api: RMOAS.OASDocument, selected: number) {\n const exampleDotCom = 'https://example.com';\n let url;\n try {\n url = api.servers[selected].url;\n // This is to catch the case where servers = [{}]\n if (!url) throw new Error('no url');\n\n // Stripping the '/' off the end\n url = stripTrailingSlash(url);\n\n // Check if the URL is just a path a missing an origin, for example `/api/v3`. If so, then make\n // `example.com` the origin to avoid it becoming something invalid like `https:///api/v3`.\n // RM-1044\n if (url.startsWith('/') && !url.startsWith('//')) {\n const urlWithOrigin = new URL(exampleDotCom);\n urlWithOrigin.pathname = url;\n url = urlWithOrigin.href;\n }\n } catch (e) {\n url = exampleDotCom;\n }\n\n return ensureProtocol(url);\n}\n\n/**\n * With a URL that may contain server variables, transform those server variables into regex that\n * we can query against.\n *\n * For example, when given `https://{region}.node.example.com/v14` this will return back:\n *\n * https://([-_a-zA-Z0-9:.[\\\\]]+).node.example.com/v14\n *\n * @param url URL to transform\n */\nfunction transformUrlIntoRegex(url: string) {\n return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, '([-_a-zA-Z0-9:.[\\\\]]+)'));\n}\n\n/**\n * Normalize a path so that we can use it with `path-to-regexp` to do operation lookups.\n *\n * @param path Path to normalize.\n */\nfunction normalizePath(path: string) {\n return (\n path\n // This regex transforms `{pathParam}` into `:pathParam` so we can regex against it. We're\n // also handling quirks here like if there's an optional proceeding or trailing curly bracket\n // (`{{pathParam}` or `{pathParam}}`) as any unescaped curlys, which would be present in\n // `:pathParam}`, will throw a regex exception.\n .replace(/({?){(.*?)}(}?)/g, (str, ...args) => {\n // If a path contains a path parameter with hyphens, like `:dlc-release`, when it's regexd\n // with `path-to-regexp` it match against the `:dlc` portion of the parameter, breaking all\n // matching against the full path.\n //\n // For example on `/games/:game/dlc/:dlc-release` the regex that's actually used to search\n // against a path like `/games/destiny-2/dlc/witch-queen` is the following:\n // /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))-release[\\/#\\?]?$/i\n //\n // However if `:dlc-release` is rewritten to `:dlcrelease` we end up with a functional\n // regex: /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))[\\/#\\?]?$/i.\n return `:${args[1].replace('-', '')}`;\n })\n\n // In addition to transforming `{pathParam}` into `:pathParam` we also need to escape cases\n // where a non-variabled colon is next to a variabled-colon because if we don't then\n // `path-to-regexp` won't be able to correct identify where the variable starts.\n //\n // For example if the URL is `/post/:param1::param2` we'll be escaping it to\n // `/post/:param1\\::param2`.\n .replace(/::/, '\\\\::')\n\n // We also need to escape question marks too because they're treated as regex modifiers.\n .split('?')[0]\n );\n}\n\n/**\n * Generate path matches for a given path and origin on a set of OpenAPI path objects.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathsObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject}\n * @param paths The OpenAPI Paths Object to process.\n * @param pathName Path to look for a match.\n * @param origin The origin that we're matching against.\n */\nfunction generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin: string) {\n const prunedPathName = pathName.split('?')[0];\n return Object.keys(paths)\n .map(path => {\n const cleanedPath = normalizePath(path);\n\n let matchResult: PathMatch['match'];\n try {\n const matchStatement = match(cleanedPath, { decode: decodeURIComponent });\n matchResult = matchStatement(prunedPathName);\n } catch (err) {\n // If path matching fails for whatever reason (maybe they have a malformed path parameter)\n // then we shouldn't also fail.\n return;\n }\n\n const slugs: Record<string, string> = {};\n\n if (matchResult && Object.keys(matchResult.params).length) {\n Object.keys(matchResult.params).forEach(param => {\n slugs[`:${param}`] = (matchResult.params as Record<string, string>)[param];\n });\n }\n\n // eslint-disable-next-line consistent-return\n return {\n url: {\n origin,\n path: cleanedPath.replace(/\\\\::/, '::'),\n nonNormalizedPath: path,\n slugs,\n },\n operation: paths[path],\n match: matchResult,\n };\n })\n .filter(Boolean)\n .filter(p => p.match) as PathMatches;\n}\n\n/**\n * @param pathMatches Array of path matches to filter down.\n * @param targetMethod HTTP method to look for.\n * @returns Filtered down path matches.\n */\nfunction filterPathMethods(pathMatches: PathMatches, targetMethod: RMOAS.HttpMethods) {\n const regExp = pathToRegexp(targetMethod);\n return pathMatches\n .map(p => {\n const captures = Object.keys(p.operation).filter(r => regExp.regexp.exec(r));\n\n if (captures.length) {\n const method = captures[0];\n p.url.method = method.toUpperCase() as RMOAS.HttpMethods;\n\n return {\n url: p.url,\n operation: p.operation[method],\n };\n }\n\n return false;\n })\n .filter(Boolean) as { operation: RMOAS.OperationObject; url: PathMatch['url'] }[];\n}\n\n/**\n * @param pathMatches URL and PathsObject matches to narrow down to find a target path.\n * @returns An object containing matches that were discovered in the API definition.\n */\nfunction findTargetPath(pathMatches: { operation: RMOAS.PathsObject; url: PathMatch['url'] }[]) {\n let minCount = Object.keys(pathMatches[0].url.slugs).length;\n let operation;\n\n for (let m = 0; m < pathMatches.length; m += 1) {\n const selection = pathMatches[m];\n const paramCount = Object.keys(selection.url.slugs).length;\n if (paramCount <= minCount) {\n minCount = paramCount;\n operation = selection;\n }\n }\n\n return operation;\n}\n\nexport default class Oas {\n /**\n * An OpenAPI API Definition.\n */\n api: RMOAS.OASDocument;\n\n /**\n * The current user that we should use when pulling auth tokens from security schemes.\n */\n user: RMOAS.User;\n\n /**\n * Internal storage array that the library utilizes to keep track of the times the\n * {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all\n * end up returning the same data set once the initial dereference call completed.\n */\n protected promises: {\n reject: any;\n resolve: any;\n }[];\n\n /**\n * Internal storage array that the library utilizes to keep track of its `dereferencing` state so\n * it doesn't initiate multiple dereferencing processes.\n */\n protected dereferencing: {\n circularRefs: string[];\n complete: boolean;\n processing: boolean;\n };\n\n /**\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n constructor(oas: RMOAS.OASDocument | string, user?: RMOAS.User) {\n if (typeof oas === 'string') {\n oas = JSON.parse(oas) as RMOAS.OASDocument;\n }\n // @todo throw an exception here instead of allowing an empty oas\n this.api = oas;\n this.user = user || {};\n\n this.promises = [];\n this.dereferencing = {\n processing: false,\n complete: false,\n circularRefs: [],\n };\n }\n\n /**\n * This will initialize a new instance of the `Oas` class. This method is useful if you're using\n * Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type\n * that object to an `OASDocument` for you.\n *\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n static init(oas: Record<string, unknown> | RMOAS.OASDocument, user?: RMOAS.User) {\n return new Oas(oas as RMOAS.OASDocument, user);\n }\n\n /**\n * Retrieve the OpenAPI version that this API definition is targeted for.\n */\n getVersion() {\n if (this.api.openapi) {\n return this.api.openapi;\n }\n\n throw new Error('Unable to recognize what specification version this API definition conforms to.');\n }\n\n /**\n * Retrieve the current OpenAPI API Definition.\n *\n */\n getDefinition() {\n return this.api;\n }\n\n url(selected = 0, variables?: RMOAS.ServerVariable) {\n const url = normalizedUrl(this.api, selected);\n return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();\n }\n\n variables(selected = 0) {\n let variables;\n try {\n variables = this.api.servers[selected].variables;\n if (!variables) throw new Error('no variables');\n } catch (e) {\n variables = {};\n }\n\n return variables;\n }\n\n defaultVariables(selected = 0) {\n const variables = this.variables(selected);\n const defaults: RMOAS.ServerVariable = {};\n\n Object.keys(variables).forEach(key => {\n defaults[key] = getUserVariable(this.user, key) || variables[key].default || '';\n });\n\n return defaults;\n }\n\n splitUrl(selected = 0): (\n | {\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'text';\n value: string;\n }\n | {\n /**\n * An optional description for the server variable.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n description?: string;\n\n /**\n * An enumeration of string values to be used if the substitution options are from a limited set.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n enum?: string[];\n\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'variable';\n value: string;\n }\n )[] {\n const url = normalizedUrl(this.api, selected);\n const variables = this.variables(selected);\n\n return url\n .split(/({.+?})/)\n .filter(Boolean)\n .map((part, i) => {\n const isVariable = part.match(/[{}]/);\n const value = part.replace(/[{}]/g, '');\n // To ensure unique keys, we're going to create a key\n // with the value concatenated to its index.\n const key = `${value}-${i}`;\n\n if (!isVariable) {\n return {\n type: 'text',\n value,\n key,\n };\n }\n\n const variable = variables?.[value];\n\n return {\n type: 'variable',\n value,\n key,\n description: variable?.description,\n enum: variable?.enum,\n };\n });\n }\n\n /**\n * With a fully composed server URL, run through our list of known OAS servers and return back\n * which server URL was selected along with any contained server variables split out.\n *\n * For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,\n * and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the\n * following:\n *\n * { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }\n *\n * Re-supplying this data to `oas.url()` should return the same URL you passed into this method.\n *\n * @param baseUrl A given URL to extract server variables out of.\n */\n splitVariables(baseUrl: string) {\n const matchedServer = (this.api.servers || [])\n .map((server, i) => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(baseUrl);\n if (!found) {\n return false;\n }\n\n // While it'd be nice to use named regex groups to extract path parameters from the URL and\n // match them up with the variables that we have present in it, JS unfortunately doesn't\n // support having the groups duplicated. So instead of doing that we need to re-regex the\n // server URL, this time splitting on the path parameters -- this way we'll be able to\n // extract the parameter names and match them up with the matched server that we obtained\n // above.\n const variables: Record<string, number | string> = {};\n Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {\n variables[variable[1]] = found[y + 1];\n });\n\n return {\n selected: i,\n variables,\n };\n })\n .filter(Boolean);\n\n return matchedServer.length ? matchedServer[0] : false;\n }\n\n /**\n * Replace templated variables with supplied data in a given URL.\n *\n * There are a couple ways that this will utilize variable data:\n *\n * - Supplying a `variables` object. If this is supplied, this data will always take priority.\n * This incoming `variables` object can be two formats:\n * `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is\n * present, that will take precedence over the latter.\n * - If the supplied `variables` object is empty or does not match the current template name,\n * we fallback to the data stored in `this.user` and attempt to match against that.\n * See `getUserVariable` for some more information on how this data is pulled from `this.user`.\n *\n * If no variables supplied match up with the template name, the template name will instead be\n * used as the variable data.\n *\n * @param url A URL to swap variables into.\n * @param variables An object containing variables to swap into the URL.\n */\n replaceUrl(url: string, variables: RMOAS.ServerVariable = {}) {\n // When we're constructing URLs, server URLs with trailing slashes cause problems with doing\n // lookups, so if we have one here on, slice it off.\n return stripTrailingSlash(\n url.replace(SERVER_VARIABLE_REGEX, (original: string, key: string) => {\n if (key in variables) {\n const data = variables[key];\n if (typeof data === 'object') {\n if (!Array.isArray(data) && data !== null && 'default' in data) {\n return data.default as string;\n }\n } else {\n return data as string;\n }\n }\n\n const userVariable = getUserVariable(this.user, key);\n if (userVariable) {\n return userVariable as string;\n }\n\n return original;\n }),\n );\n }\n\n /**\n * Retrieve an Operation of Webhook class instance for a given path and method.\n *\n * @param path Path to lookup and retrieve.\n * @param method HTTP Method to retrieve on the path.\n */\n operation(\n path: string,\n method: RMOAS.HttpMethods,\n opts: {\n /**\n * If you prefer to first look for a webhook with this path and method.\n */\n isWebhook?: boolean;\n } = {},\n ) {\n // If we're unable to locate an operation for this path+method combination within the API\n // definition, we should still set an empty schema on the operation in the `Operation` class\n // because if we don't trying to use any of the accessors on that class are going to fail as\n // `schema` will be `undefined`.\n let operation: RMOAS.OperationObject = {\n parameters: [],\n };\n\n if (opts.isWebhook) {\n const api = this.api as OpenAPIV3_1.Document;\n // Typecasting this to a `PathsObject` because we don't have `$ref` pointers here.\n if ((api?.webhooks[path] as RMOAS.PathsObject)?.[method]) {\n operation = (api.webhooks[path] as RMOAS.PathsObject)[method] as RMOAS.OperationObject;\n return new Webhook(api, path, method, operation);\n }\n }\n\n if (this?.api?.paths?.[path]?.[method]) {\n operation = this.api.paths[path][method];\n }\n\n return new Operation(this.api, path, method, operation);\n }\n\n findOperationMatches(url: string): PathMatches {\n const { origin, hostname } = new URL(url);\n const originRegExp = new RegExp(origin, 'i');\n const { servers, paths } = this.api;\n\n let pathName;\n let targetServer;\n let matchedServer;\n\n if (!servers || !servers.length) {\n // If this API definition doesn't have any servers set up let's treat it as if it were\n // https://example.com because that's the default origin we add in `normalizedUrl` under the\n // same circumstances. Without this we won't be able to match paths within what is otherwise\n // a valid OpenAPI definition.\n matchedServer = {\n url: 'https://example.com',\n };\n } else {\n matchedServer = servers.find(s => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n if (!matchedServer) {\n const hostnameRegExp = new RegExp(hostname);\n matchedServer = servers.find(s => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n }\n }\n\n // If we **still** haven't found a matching server, then the OAS server URL might have server\n // variables and we should loosen it up with regex to try to discover a matching path.\n //\n // For example if an OAS has `https://{region}.node.example.com/v14` set as its server URL, and\n // the `this.user` object has a `region` value of `us`, if we're trying to locate an operation\n // for https://eu.node.example.com/v14/api/esm we won't be able to because normally the users\n // `region` of `us` will be transposed in and we'll be trying to locate `eu.node.example.com`\n // in `us.node.example.com` -- which won't work.\n //\n // So what this does is transform `https://{region}.node.example.com/v14` into\n // `https://([-_a-zA-Z0-9[\\\\]]+).node.example.com/v14`, and from there we'll be able to match\n // https://eu.node.example.com/v14/api/esm and ultimately find the operation matches for\n // `/api/esm`.\n if (!matchedServer) {\n const matchedServerAndPath = servers\n .map(server => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(url);\n if (!found) {\n return undefined;\n }\n\n return {\n matchedServer: server,\n pathName: url.split(new RegExp(rgx)).slice(-1).pop(),\n };\n })\n .filter(Boolean);\n\n if (!matchedServerAndPath.length) {\n return undefined;\n }\n\n pathName = matchedServerAndPath[0].pathName;\n targetServer = {\n ...matchedServerAndPath[0].matchedServer,\n };\n } else {\n // Instead of setting `url` directly against `matchedServer` we need to set it to an\n // intermediary object as directly modifying `matchedServer.url` will in turn update\n // `this.servers[idx].url` which we absolutely do not want to happen.\n targetServer = {\n ...matchedServer,\n url: this.replaceUrl(matchedServer.url, matchedServer.variables || {}),\n };\n\n [, pathName] = url.split(new RegExp(targetServer.url, 'i'));\n }\n\n if (pathName === undefined) return undefined;\n if (pathName === '') pathName = '/';\n const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);\n if (!annotatedPaths.length) return undefined;\n\n return annotatedPaths;\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object\n * containing a `url` object and another one for `operation`. This differs from `getOperation()`\n * in that it does not return an instance of the `Operation` class.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n findOperation(url: string, method: RMOAS.HttpMethods): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n\n const matches = filterPathMethods(annotatedPaths, method) as {\n operation: RMOAS.PathsObject;\n url: PathMatch['url']; // @fixme this should actually be an `OperationObject`.\n }[];\n if (!matches.length) return undefined;\n return findTargetPath(matches);\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an\n * object containing a `url` object and another one for `operation`.\n *\n * @param url A full URL to look up.\n */\n findOperationWithoutMethod(url: string): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n return findTargetPath(annotatedPaths);\n }\n\n /**\n * Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from\n * `findOperation` in that while this method will return an `Operation` instance,\n * `findOperation()` does not.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n getOperation(url: string, method: RMOAS.HttpMethods) {\n const op = this.findOperation(url, method);\n if (op === undefined) {\n return undefined;\n }\n\n return this.operation(op.url.nonNormalizedPath, method);\n }\n\n /**\n * Retrieve an operation in an OAS by an `operationId`.\n *\n * If an operation does not have an `operationId` one will be generated in place, using the\n * default behavior of `Operation.getOperationId()`, and then asserted against your query.\n *\n * Note that because `operationId`s are unique that uniqueness does include casing so the ID\n * you are looking for will be asserted as an exact match.\n *\n * @see {Operation.getOperationId()}\n * @param id The `operationId` to look up.\n */\n getOperationById(id: string) {\n let found: Operation | Webhook;\n\n Object.values(this.getPaths()).forEach(operations => {\n if (found) return;\n found = Object.values(operations).find(operation => operation.getOperationId() === id);\n });\n\n if (found) {\n return found;\n }\n\n Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {\n if (found) return;\n found = Object.values(webhooks).find(webhook => webhook.getOperationId() === id);\n });\n\n return found;\n }\n\n /**\n * With an object of user information, retrieve the appropriate API auth keys from the current\n * OAS definition.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\n getAuth(user: RMOAS.User, selectedApp?: number | string) {\n if (!this.api?.components?.securitySchemes) {\n return {};\n }\n\n return getAuth(this.api, user, selectedApp);\n }\n\n /**\n * Returns the `paths` object that exists in this API definition but with every `method` mapped\n * to an instance of the `Operation` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getPaths() {\n /**\n * Because a path doesn't need to contain a keyed-object of HTTP methods, we should exclude\n * anything from within the paths object that isn't a known HTTP method.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#fixed-fields-7}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-7}\n */\n const paths: Record<string, Record<RMOAS.HttpMethods, Operation | Webhook>> = {};\n\n Object.keys(this.api.paths ? this.api.paths : []).forEach(path => {\n // If this is a specification extension then we should ignore it.\n if (path.startsWith('x-')) {\n return;\n }\n\n paths[path] = {} as Record<RMOAS.HttpMethods, Operation | Webhook>;\n\n // Though this library is generally unaware of `$ref` pointers we're making a singular\n // exception with this accessor out of convenience.\n if ('$ref' in this.api.paths[path]) {\n this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);\n }\n\n Object.keys(this.api.paths[path]).forEach((method: RMOAS.HttpMethods) => {\n if (!supportedMethods.has(method)) return;\n\n paths[path][method] = this.operation(path, method);\n });\n });\n\n return paths;\n }\n\n /**\n * Returns the `webhooks` object that exists in this API definition but with every `method`\n * mapped to an instance of the `Webhook` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getWebhooks() {\n const webhooks: Record<string, Record<RMOAS.HttpMethods, Webhook>> = {};\n const api = this.api as OpenAPIV3_1.Document;\n\n Object.keys(api.webhooks ? api.webhooks : []).forEach(id => {\n webhooks[id] = {} as Record<RMOAS.HttpMethods, Webhook>;\n Object.keys(api.webhooks[id]).forEach((method: RMOAS.HttpMethods) => {\n webhooks[id][method] = this.operation(id, method, { isWebhook: true }) as Webhook;\n });\n });\n\n return webhooks;\n }\n\n /**\n * Return an array of all tag names that exist on this API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n * @param setIfMissing If a tag is not present on an operation that operations path will be added\n * into the list of tags returned.\n */\n getTags(setIfMissing = false) {\n const allTags = new Set<string>();\n\n const oasTags =\n this.api.tags?.map(tag => {\n return tag.name;\n }) || [];\n\n const disableTagSorting = getExtension('disable-tag-sorting', this.api);\n\n Object.entries(this.getPaths()).forEach(([path, operations]) => {\n Object.values(operations).forEach(operation => {\n const tags = operation.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {\n Object.values(webhooks).forEach(webhook => {\n const tags = webhook.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n // Tags that exist only on the endpoint\n const endpointTags: string[] = [];\n // Tags that the user has defined in the `tags` array\n const tagsArray: string[] = [];\n\n // Distinguish between which tags exist in the `tags` array and which tags\n // exist only at the endpoint level. For tags that exist only at the\n // endpoint level, we'll just tack that on to the end of the sorted tags.\n if (disableTagSorting) {\n return Array.from(allTags);\n }\n\n Array.from(allTags).forEach(tag => {\n if (oasTags.includes(tag)) {\n tagsArray.push(tag);\n } else {\n endpointTags.push(tag);\n }\n });\n\n let sortedTags = tagsArray.sort((a, b) => {\n return oasTags.indexOf(a) - oasTags.indexOf(b);\n });\n\n sortedTags = sortedTags.concat(endpointTags);\n\n return sortedTags;\n }\n\n /**\n * Determine if a given a custom specification extension exists within the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n hasExtension(extension: string) {\n return hasRootExtension(extension, this.api);\n }\n\n /**\n * Retrieve a custom specification extension off of the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n getExtension(extension: string | keyof Extensions, operation?: Operation) {\n return getExtension(extension, this.api, operation);\n }\n\n /**\n * Determine if a given OpenAPI custom extension is valid or not.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to validate.\n * @throws\n */\n validateExtension(extension: keyof Extensions) {\n if (this.hasExtension('x-readme')) {\n const data = this.getExtension('x-readme') as Extensions;\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n throw new TypeError('\"x-readme\" must be of type \"Object\"');\n }\n\n if (extension in data) {\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data[extension])) {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data[extension], `x-readme.${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data[extension] !== 'object') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data[extension] !== 'boolean') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n // If the extension isn't grouped under `x-readme`, we need to look for them with `x-` prefixes.\n if (this.hasExtension(`x-${extension}`)) {\n const data = this.getExtension(`x-${extension}`);\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data)) {\n throw new TypeError(`\"x-${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data, `x-${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data !== 'object') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data !== 'boolean') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n /**\n * Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n */\n validateExtensions() {\n Object.keys(extensionDefaults).forEach((extension: keyof Extensions) => {\n this.validateExtension(extension);\n });\n }\n\n /**\n * Retrieve any circular `$ref` pointers that maybe present within the API definition.\n *\n * This method requires that you first dereference the definition.\n *\n * @see Oas.dereference\n */\n getCircularReferences() {\n if (!this.dereferencing.complete) {\n throw new Error('#dereference() must be called first in order for this method to obtain circular references.');\n }\n\n return this.dereferencing.circularRefs;\n }\n\n /**\n * Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas\n * and circular structures.\n *\n */\n async dereference(\n opts: {\n /**\n * A callback method can be supplied to be called when dereferencing is complete. Used for\n * debugging that the multi-promise handling within this method works.\n *\n * @private\n */\n cb?: () => void;\n\n /**\n * Preserve component schema names within themselves as a `title`.\n */\n preserveRefAsJSONSchemaTitle?: boolean;\n } = { preserveRefAsJSONSchemaTitle: false },\n ) {\n if (this.dereferencing.complete) {\n return new Promise(resolve => {\n resolve(true);\n });\n }\n\n if (this.dereferencing.processing) {\n return new Promise((resolve, reject) => {\n this.promises.push({ resolve, reject });\n });\n }\n\n this.dereferencing.processing = true;\n\n const { api, promises } = this;\n\n // Because referencing will eliminate any lineage back to the original `$ref`, information that\n // we might need at some point, we should run through all available component schemas and denote\n // what their name is so that when dereferencing happens below those names will be preserved.\n if (api && api.components && api.components.schemas && typeof api.components.schemas === 'object') {\n Object.keys(api.components.schemas).forEach(schemaName => {\n // As of OpenAPI 3.1 component schemas can be primitives or arrays. If this happens then we\n // shouldn't try to add `title` or `x-readme-ref-name` properties because we can't. We'll\n // have some data loss on these schemas but as they aren't objects they likely won't be used\n // in ways that would require needing a `title` or `x-readme-ref-name` anyways.\n if (\n isPrimitive(api.components.schemas[schemaName]) ||\n Array.isArray(api.components.schemas[schemaName]) ||\n api.components.schemas[schemaName] === null\n ) {\n return;\n }\n\n if (opts.preserveRefAsJSONSchemaTitle) {\n // This may result in some data loss if there's already a `title` present, but in the case\n // where we want to generate code for the API definition (see http://npm.im/api), we'd\n // prefer to retain original reference name as a title for any generated types.\n (api.components.schemas[schemaName] as RMOAS.SchemaObject).title = schemaName;\n }\n\n (api.components.schemas[schemaName] as RMOAS.SchemaObject)['x-readme-ref-name'] = schemaName;\n });\n }\n\n const parser = new $RefParser();\n\n return parser\n .dereference(api || {}, {\n resolve: {\n // We shouldn't be resolving external pointers at this point so just ignore them.\n external: false,\n },\n dereference: {\n // If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise\n // `$ref‘ just won't exist. This allows us to do easy circular reference detection.\n circular: 'ignore',\n },\n })\n .then((dereferenced: RMOAS.OASDocument) => {\n let circularRefs: string[] = [];\n if (parser.$refs.circular) {\n circularRefs = parser.$refs.circularRefs.map(pointer => {\n // The circular $refs that are coming out of `json-schema-ref-parser` are prefixed\n // with the schema path (file path, url, whatever) that the schema exists in. Because\n // we don't care about this information for this reporting mechanism, and only the\n // $ref pointer, we're removing it.\n return `#${pointer.split('#')[1]}`;\n });\n }\n\n this.api = dereferenced;\n\n this.promises = promises;\n this.dereferencing = {\n processing: false,\n complete: true,\n circularRefs,\n };\n\n // Used for debugging that dereferencing promise awaiting works.\n if (opts.cb) {\n opts.cb();\n }\n })\n .then(() => {\n return this.promises.map(deferred => deferred.resolve());\n });\n }\n}\n","import type * as RMOAS from '../types.js';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\ntype authKey = unknown | { password: number | string; user: number | string } | null;\n\n/**\n * @param user User to retrieve retrieve an auth key for.\n * @param scheme The type of security scheme that we want a key for.\n */\nfunction getKey(user: RMOAS.User, scheme: RMOAS.KeyedSecuritySchemeObject): authKey {\n switch (scheme.type) {\n case 'oauth2':\n case 'apiKey':\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n\n case 'http':\n if (scheme.scheme === 'basic') {\n return user[scheme._key] || { user: user.user || null, pass: user.pass || null };\n }\n\n if (scheme.scheme === 'bearer') {\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n }\n return null;\n\n default:\n return null;\n }\n}\n\n/**\n * Retrieve auth keys for a specific security scheme for a given user for a specific \"app\" that\n * they have configured.\n *\n * For `scheme` we're typing it to a union of `SecurityScheme` and `any` because we have handling\n * and tests for an unknown or unrecognized `type` and though it's not possible with the\n * `SecurityScheme.type` to be unrecognized it may still be possible to get an unrecognized scheme\n * with this method in the wild as we have API definitions in our database that were ingested\n * before we had good validation in place.\n *\n * @param user User\n * @param scheme Security scheme to get auth keys for.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getByScheme(\n user: RMOAS.User,\n scheme = <RMOAS.KeyedSecuritySchemeObject>{},\n selectedApp?: number | string,\n): authKey {\n if (user?.keys && user.keys.length) {\n if (selectedApp) {\n return getKey(\n user.keys.find(key => key.name === selectedApp),\n scheme,\n );\n }\n\n return getKey(user.keys[0], scheme);\n }\n\n return getKey(user, scheme);\n}\n\n/**\n * Retrieve auth keys for an API definition from a given user for a specific \"app\" that they have\n * configured.\n *\n * @param api API definition\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getAuth(\n api: OpenAPIV3_1.Document | OpenAPIV3.Document,\n user: RMOAS.User,\n selectedApp?: number | string,\n) {\n return Object.keys(api?.components?.securitySchemes || {})\n .map(scheme => {\n return {\n [scheme]: getByScheme(\n user,\n {\n // This sucks but since we dereference we'll never have a `$ref` pointer here with a\n // `ReferenceObject` type.\n ...(api.components.securitySchemes[scheme] as RMOAS.SecuritySchemeObject),\n _key: scheme,\n },\n selectedApp,\n ),\n };\n })\n .reduce((prev, next) => Object.assign(prev, next), {});\n}\n","import type * as RMOAS from '../types.js';\n\n/**\n * Retrieve a user variable off of a given user.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user The user to get a user variable for.\n * @param property The name of the variable to retrieve.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport default function getUserVariable(user: RMOAS.User, property: string, selectedApp?: number | string) {\n let key = user;\n\n if ('keys' in user && Array.isArray(user.keys) && user.keys.length) {\n if (selectedApp) {\n key = user.keys.find(k => k.name === selectedApp);\n } else {\n key = user.keys[0];\n }\n }\n\n return key[property] || user[property] || null;\n}\n"]}
|
|
@@ -160,7 +160,7 @@ function generatePathMatches(paths, pathName, origin) {
|
|
|
160
160
|
function filterPathMethods(pathMatches, targetMethod) {
|
|
161
161
|
const regExp = pathToRegexp(targetMethod);
|
|
162
162
|
return pathMatches.map((p) => {
|
|
163
|
-
const captures = Object.keys(p.operation).filter((r) => regExp.exec(r));
|
|
163
|
+
const captures = Object.keys(p.operation).filter((r) => regExp.regexp.exec(r));
|
|
164
164
|
if (captures.length) {
|
|
165
165
|
const method = captures[0];
|
|
166
166
|
p.url.method = method.toUpperCase();
|
|
@@ -775,4 +775,4 @@ var Oas = class _Oas {
|
|
|
775
775
|
export {
|
|
776
776
|
Oas
|
|
777
777
|
};
|
|
778
|
-
//# sourceMappingURL=chunk-
|
|
778
|
+
//# sourceMappingURL=chunk-SGDW7HEE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/lib/get-auth.ts","../src/lib/get-user-variable.ts"],"sourcesContent":["import type { Extensions } from './extensions.js';\nimport type * as RMOAS from './types.js';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { Match, ParamData } from 'path-to-regexp';\n\nimport $RefParser from '@readme/json-schema-ref-parser';\nimport { pathToRegexp, match } from 'path-to-regexp';\n\nimport {\n CODE_SAMPLES,\n HEADERS,\n OAUTH_OPTIONS,\n PARAMETER_ORDERING,\n SAMPLES_LANGUAGES,\n extensionDefaults,\n getExtension,\n hasRootExtension,\n validateParameterOrdering,\n} from './extensions.js';\nimport { getAuth } from './lib/get-auth.js';\nimport getUserVariable from './lib/get-user-variable.js';\nimport { isPrimitive } from './lib/helpers.js';\nimport { Operation, Webhook } from './operation/index.js';\nimport { findSchemaDefinition, supportedMethods } from './utils.js';\n\ninterface PathMatch {\n match?: Match<ParamData>;\n operation: RMOAS.PathsObject;\n url: {\n method?: RMOAS.HttpMethods;\n nonNormalizedPath: string;\n origin: string;\n path: string;\n slugs: Record<string, string>;\n };\n}\ntype PathMatches = PathMatch[];\n\nconst SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\\]]+)}/g;\n\nfunction ensureProtocol(url: string) {\n // Add protocol to urls starting with // e.g. //example.com\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (url.match(/^\\/\\//)) {\n return `https:${url}`;\n }\n\n // Add protocol to urls with no // within them\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (!url.match(/\\/\\//)) {\n return `https://${url}`;\n }\n\n return url;\n}\n\nfunction stripTrailingSlash(url: string) {\n if (url[url.length - 1] === '/') {\n return url.slice(0, -1);\n }\n\n return url;\n}\n\n/**\n * Normalize a OpenAPI server URL by ensuring that it has a proper HTTP protocol and doesn't have a\n * trailing slash.\n *\n * @param api The API definition that we're processing.\n * @param selected The index of the `servers` array in the API definition that we want to normalize.\n */\nfunction normalizedUrl(api: RMOAS.OASDocument, selected: number) {\n const exampleDotCom = 'https://example.com';\n let url;\n try {\n url = api.servers[selected].url;\n // This is to catch the case where servers = [{}]\n if (!url) throw new Error('no url');\n\n // Stripping the '/' off the end\n url = stripTrailingSlash(url);\n\n // Check if the URL is just a path a missing an origin, for example `/api/v3`. If so, then make\n // `example.com` the origin to avoid it becoming something invalid like `https:///api/v3`.\n // RM-1044\n if (url.startsWith('/') && !url.startsWith('//')) {\n const urlWithOrigin = new URL(exampleDotCom);\n urlWithOrigin.pathname = url;\n url = urlWithOrigin.href;\n }\n } catch (e) {\n url = exampleDotCom;\n }\n\n return ensureProtocol(url);\n}\n\n/**\n * With a URL that may contain server variables, transform those server variables into regex that\n * we can query against.\n *\n * For example, when given `https://{region}.node.example.com/v14` this will return back:\n *\n * https://([-_a-zA-Z0-9:.[\\\\]]+).node.example.com/v14\n *\n * @param url URL to transform\n */\nfunction transformUrlIntoRegex(url: string) {\n return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, '([-_a-zA-Z0-9:.[\\\\]]+)'));\n}\n\n/**\n * Normalize a path so that we can use it with `path-to-regexp` to do operation lookups.\n *\n * @param path Path to normalize.\n */\nfunction normalizePath(path: string) {\n return (\n path\n // This regex transforms `{pathParam}` into `:pathParam` so we can regex against it. We're\n // also handling quirks here like if there's an optional proceeding or trailing curly bracket\n // (`{{pathParam}` or `{pathParam}}`) as any unescaped curlys, which would be present in\n // `:pathParam}`, will throw a regex exception.\n .replace(/({?){(.*?)}(}?)/g, (str, ...args) => {\n // If a path contains a path parameter with hyphens, like `:dlc-release`, when it's regexd\n // with `path-to-regexp` it match against the `:dlc` portion of the parameter, breaking all\n // matching against the full path.\n //\n // For example on `/games/:game/dlc/:dlc-release` the regex that's actually used to search\n // against a path like `/games/destiny-2/dlc/witch-queen` is the following:\n // /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))-release[\\/#\\?]?$/i\n //\n // However if `:dlc-release` is rewritten to `:dlcrelease` we end up with a functional\n // regex: /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))[\\/#\\?]?$/i.\n return `:${args[1].replace('-', '')}`;\n })\n\n // In addition to transforming `{pathParam}` into `:pathParam` we also need to escape cases\n // where a non-variabled colon is next to a variabled-colon because if we don't then\n // `path-to-regexp` won't be able to correct identify where the variable starts.\n //\n // For example if the URL is `/post/:param1::param2` we'll be escaping it to\n // `/post/:param1\\::param2`.\n .replace(/::/, '\\\\::')\n\n // We also need to escape question marks too because they're treated as regex modifiers.\n .split('?')[0]\n );\n}\n\n/**\n * Generate path matches for a given path and origin on a set of OpenAPI path objects.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathsObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject}\n * @param paths The OpenAPI Paths Object to process.\n * @param pathName Path to look for a match.\n * @param origin The origin that we're matching against.\n */\nfunction generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin: string) {\n const prunedPathName = pathName.split('?')[0];\n return Object.keys(paths)\n .map(path => {\n const cleanedPath = normalizePath(path);\n\n let matchResult: PathMatch['match'];\n try {\n const matchStatement = match(cleanedPath, { decode: decodeURIComponent });\n matchResult = matchStatement(prunedPathName);\n } catch (err) {\n // If path matching fails for whatever reason (maybe they have a malformed path parameter)\n // then we shouldn't also fail.\n return;\n }\n\n const slugs: Record<string, string> = {};\n\n if (matchResult && Object.keys(matchResult.params).length) {\n Object.keys(matchResult.params).forEach(param => {\n slugs[`:${param}`] = (matchResult.params as Record<string, string>)[param];\n });\n }\n\n // eslint-disable-next-line consistent-return\n return {\n url: {\n origin,\n path: cleanedPath.replace(/\\\\::/, '::'),\n nonNormalizedPath: path,\n slugs,\n },\n operation: paths[path],\n match: matchResult,\n };\n })\n .filter(Boolean)\n .filter(p => p.match) as PathMatches;\n}\n\n/**\n * @param pathMatches Array of path matches to filter down.\n * @param targetMethod HTTP method to look for.\n * @returns Filtered down path matches.\n */\nfunction filterPathMethods(pathMatches: PathMatches, targetMethod: RMOAS.HttpMethods) {\n const regExp = pathToRegexp(targetMethod);\n return pathMatches\n .map(p => {\n const captures = Object.keys(p.operation).filter(r => regExp.regexp.exec(r));\n\n if (captures.length) {\n const method = captures[0];\n p.url.method = method.toUpperCase() as RMOAS.HttpMethods;\n\n return {\n url: p.url,\n operation: p.operation[method],\n };\n }\n\n return false;\n })\n .filter(Boolean) as { operation: RMOAS.OperationObject; url: PathMatch['url'] }[];\n}\n\n/**\n * @param pathMatches URL and PathsObject matches to narrow down to find a target path.\n * @returns An object containing matches that were discovered in the API definition.\n */\nfunction findTargetPath(pathMatches: { operation: RMOAS.PathsObject; url: PathMatch['url'] }[]) {\n let minCount = Object.keys(pathMatches[0].url.slugs).length;\n let operation;\n\n for (let m = 0; m < pathMatches.length; m += 1) {\n const selection = pathMatches[m];\n const paramCount = Object.keys(selection.url.slugs).length;\n if (paramCount <= minCount) {\n minCount = paramCount;\n operation = selection;\n }\n }\n\n return operation;\n}\n\nexport default class Oas {\n /**\n * An OpenAPI API Definition.\n */\n api: RMOAS.OASDocument;\n\n /**\n * The current user that we should use when pulling auth tokens from security schemes.\n */\n user: RMOAS.User;\n\n /**\n * Internal storage array that the library utilizes to keep track of the times the\n * {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all\n * end up returning the same data set once the initial dereference call completed.\n */\n protected promises: {\n reject: any;\n resolve: any;\n }[];\n\n /**\n * Internal storage array that the library utilizes to keep track of its `dereferencing` state so\n * it doesn't initiate multiple dereferencing processes.\n */\n protected dereferencing: {\n circularRefs: string[];\n complete: boolean;\n processing: boolean;\n };\n\n /**\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n constructor(oas: RMOAS.OASDocument | string, user?: RMOAS.User) {\n if (typeof oas === 'string') {\n oas = JSON.parse(oas) as RMOAS.OASDocument;\n }\n // @todo throw an exception here instead of allowing an empty oas\n this.api = oas;\n this.user = user || {};\n\n this.promises = [];\n this.dereferencing = {\n processing: false,\n complete: false,\n circularRefs: [],\n };\n }\n\n /**\n * This will initialize a new instance of the `Oas` class. This method is useful if you're using\n * Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type\n * that object to an `OASDocument` for you.\n *\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n static init(oas: Record<string, unknown> | RMOAS.OASDocument, user?: RMOAS.User) {\n return new Oas(oas as RMOAS.OASDocument, user);\n }\n\n /**\n * Retrieve the OpenAPI version that this API definition is targeted for.\n */\n getVersion() {\n if (this.api.openapi) {\n return this.api.openapi;\n }\n\n throw new Error('Unable to recognize what specification version this API definition conforms to.');\n }\n\n /**\n * Retrieve the current OpenAPI API Definition.\n *\n */\n getDefinition() {\n return this.api;\n }\n\n url(selected = 0, variables?: RMOAS.ServerVariable) {\n const url = normalizedUrl(this.api, selected);\n return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();\n }\n\n variables(selected = 0) {\n let variables;\n try {\n variables = this.api.servers[selected].variables;\n if (!variables) throw new Error('no variables');\n } catch (e) {\n variables = {};\n }\n\n return variables;\n }\n\n defaultVariables(selected = 0) {\n const variables = this.variables(selected);\n const defaults: RMOAS.ServerVariable = {};\n\n Object.keys(variables).forEach(key => {\n defaults[key] = getUserVariable(this.user, key) || variables[key].default || '';\n });\n\n return defaults;\n }\n\n splitUrl(selected = 0): (\n | {\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'text';\n value: string;\n }\n | {\n /**\n * An optional description for the server variable.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n description?: string;\n\n /**\n * An enumeration of string values to be used if the substitution options are from a limited set.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n enum?: string[];\n\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'variable';\n value: string;\n }\n )[] {\n const url = normalizedUrl(this.api, selected);\n const variables = this.variables(selected);\n\n return url\n .split(/({.+?})/)\n .filter(Boolean)\n .map((part, i) => {\n const isVariable = part.match(/[{}]/);\n const value = part.replace(/[{}]/g, '');\n // To ensure unique keys, we're going to create a key\n // with the value concatenated to its index.\n const key = `${value}-${i}`;\n\n if (!isVariable) {\n return {\n type: 'text',\n value,\n key,\n };\n }\n\n const variable = variables?.[value];\n\n return {\n type: 'variable',\n value,\n key,\n description: variable?.description,\n enum: variable?.enum,\n };\n });\n }\n\n /**\n * With a fully composed server URL, run through our list of known OAS servers and return back\n * which server URL was selected along with any contained server variables split out.\n *\n * For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,\n * and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the\n * following:\n *\n * { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }\n *\n * Re-supplying this data to `oas.url()` should return the same URL you passed into this method.\n *\n * @param baseUrl A given URL to extract server variables out of.\n */\n splitVariables(baseUrl: string) {\n const matchedServer = (this.api.servers || [])\n .map((server, i) => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(baseUrl);\n if (!found) {\n return false;\n }\n\n // While it'd be nice to use named regex groups to extract path parameters from the URL and\n // match them up with the variables that we have present in it, JS unfortunately doesn't\n // support having the groups duplicated. So instead of doing that we need to re-regex the\n // server URL, this time splitting on the path parameters -- this way we'll be able to\n // extract the parameter names and match them up with the matched server that we obtained\n // above.\n const variables: Record<string, number | string> = {};\n Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {\n variables[variable[1]] = found[y + 1];\n });\n\n return {\n selected: i,\n variables,\n };\n })\n .filter(Boolean);\n\n return matchedServer.length ? matchedServer[0] : false;\n }\n\n /**\n * Replace templated variables with supplied data in a given URL.\n *\n * There are a couple ways that this will utilize variable data:\n *\n * - Supplying a `variables` object. If this is supplied, this data will always take priority.\n * This incoming `variables` object can be two formats:\n * `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is\n * present, that will take precedence over the latter.\n * - If the supplied `variables` object is empty or does not match the current template name,\n * we fallback to the data stored in `this.user` and attempt to match against that.\n * See `getUserVariable` for some more information on how this data is pulled from `this.user`.\n *\n * If no variables supplied match up with the template name, the template name will instead be\n * used as the variable data.\n *\n * @param url A URL to swap variables into.\n * @param variables An object containing variables to swap into the URL.\n */\n replaceUrl(url: string, variables: RMOAS.ServerVariable = {}) {\n // When we're constructing URLs, server URLs with trailing slashes cause problems with doing\n // lookups, so if we have one here on, slice it off.\n return stripTrailingSlash(\n url.replace(SERVER_VARIABLE_REGEX, (original: string, key: string) => {\n if (key in variables) {\n const data = variables[key];\n if (typeof data === 'object') {\n if (!Array.isArray(data) && data !== null && 'default' in data) {\n return data.default as string;\n }\n } else {\n return data as string;\n }\n }\n\n const userVariable = getUserVariable(this.user, key);\n if (userVariable) {\n return userVariable as string;\n }\n\n return original;\n }),\n );\n }\n\n /**\n * Retrieve an Operation of Webhook class instance for a given path and method.\n *\n * @param path Path to lookup and retrieve.\n * @param method HTTP Method to retrieve on the path.\n */\n operation(\n path: string,\n method: RMOAS.HttpMethods,\n opts: {\n /**\n * If you prefer to first look for a webhook with this path and method.\n */\n isWebhook?: boolean;\n } = {},\n ) {\n // If we're unable to locate an operation for this path+method combination within the API\n // definition, we should still set an empty schema on the operation in the `Operation` class\n // because if we don't trying to use any of the accessors on that class are going to fail as\n // `schema` will be `undefined`.\n let operation: RMOAS.OperationObject = {\n parameters: [],\n };\n\n if (opts.isWebhook) {\n const api = this.api as OpenAPIV3_1.Document;\n // Typecasting this to a `PathsObject` because we don't have `$ref` pointers here.\n if ((api?.webhooks[path] as RMOAS.PathsObject)?.[method]) {\n operation = (api.webhooks[path] as RMOAS.PathsObject)[method] as RMOAS.OperationObject;\n return new Webhook(api, path, method, operation);\n }\n }\n\n if (this?.api?.paths?.[path]?.[method]) {\n operation = this.api.paths[path][method];\n }\n\n return new Operation(this.api, path, method, operation);\n }\n\n findOperationMatches(url: string): PathMatches {\n const { origin, hostname } = new URL(url);\n const originRegExp = new RegExp(origin, 'i');\n const { servers, paths } = this.api;\n\n let pathName;\n let targetServer;\n let matchedServer;\n\n if (!servers || !servers.length) {\n // If this API definition doesn't have any servers set up let's treat it as if it were\n // https://example.com because that's the default origin we add in `normalizedUrl` under the\n // same circumstances. Without this we won't be able to match paths within what is otherwise\n // a valid OpenAPI definition.\n matchedServer = {\n url: 'https://example.com',\n };\n } else {\n matchedServer = servers.find(s => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n if (!matchedServer) {\n const hostnameRegExp = new RegExp(hostname);\n matchedServer = servers.find(s => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n }\n }\n\n // If we **still** haven't found a matching server, then the OAS server URL might have server\n // variables and we should loosen it up with regex to try to discover a matching path.\n //\n // For example if an OAS has `https://{region}.node.example.com/v14` set as its server URL, and\n // the `this.user` object has a `region` value of `us`, if we're trying to locate an operation\n // for https://eu.node.example.com/v14/api/esm we won't be able to because normally the users\n // `region` of `us` will be transposed in and we'll be trying to locate `eu.node.example.com`\n // in `us.node.example.com` -- which won't work.\n //\n // So what this does is transform `https://{region}.node.example.com/v14` into\n // `https://([-_a-zA-Z0-9[\\\\]]+).node.example.com/v14`, and from there we'll be able to match\n // https://eu.node.example.com/v14/api/esm and ultimately find the operation matches for\n // `/api/esm`.\n if (!matchedServer) {\n const matchedServerAndPath = servers\n .map(server => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(url);\n if (!found) {\n return undefined;\n }\n\n return {\n matchedServer: server,\n pathName: url.split(new RegExp(rgx)).slice(-1).pop(),\n };\n })\n .filter(Boolean);\n\n if (!matchedServerAndPath.length) {\n return undefined;\n }\n\n pathName = matchedServerAndPath[0].pathName;\n targetServer = {\n ...matchedServerAndPath[0].matchedServer,\n };\n } else {\n // Instead of setting `url` directly against `matchedServer` we need to set it to an\n // intermediary object as directly modifying `matchedServer.url` will in turn update\n // `this.servers[idx].url` which we absolutely do not want to happen.\n targetServer = {\n ...matchedServer,\n url: this.replaceUrl(matchedServer.url, matchedServer.variables || {}),\n };\n\n [, pathName] = url.split(new RegExp(targetServer.url, 'i'));\n }\n\n if (pathName === undefined) return undefined;\n if (pathName === '') pathName = '/';\n const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);\n if (!annotatedPaths.length) return undefined;\n\n return annotatedPaths;\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object\n * containing a `url` object and another one for `operation`. This differs from `getOperation()`\n * in that it does not return an instance of the `Operation` class.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n findOperation(url: string, method: RMOAS.HttpMethods): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n\n const matches = filterPathMethods(annotatedPaths, method) as {\n operation: RMOAS.PathsObject;\n url: PathMatch['url']; // @fixme this should actually be an `OperationObject`.\n }[];\n if (!matches.length) return undefined;\n return findTargetPath(matches);\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an\n * object containing a `url` object and another one for `operation`.\n *\n * @param url A full URL to look up.\n */\n findOperationWithoutMethod(url: string): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n return findTargetPath(annotatedPaths);\n }\n\n /**\n * Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from\n * `findOperation` in that while this method will return an `Operation` instance,\n * `findOperation()` does not.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n getOperation(url: string, method: RMOAS.HttpMethods) {\n const op = this.findOperation(url, method);\n if (op === undefined) {\n return undefined;\n }\n\n return this.operation(op.url.nonNormalizedPath, method);\n }\n\n /**\n * Retrieve an operation in an OAS by an `operationId`.\n *\n * If an operation does not have an `operationId` one will be generated in place, using the\n * default behavior of `Operation.getOperationId()`, and then asserted against your query.\n *\n * Note that because `operationId`s are unique that uniqueness does include casing so the ID\n * you are looking for will be asserted as an exact match.\n *\n * @see {Operation.getOperationId()}\n * @param id The `operationId` to look up.\n */\n getOperationById(id: string) {\n let found: Operation | Webhook;\n\n Object.values(this.getPaths()).forEach(operations => {\n if (found) return;\n found = Object.values(operations).find(operation => operation.getOperationId() === id);\n });\n\n if (found) {\n return found;\n }\n\n Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {\n if (found) return;\n found = Object.values(webhooks).find(webhook => webhook.getOperationId() === id);\n });\n\n return found;\n }\n\n /**\n * With an object of user information, retrieve the appropriate API auth keys from the current\n * OAS definition.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\n getAuth(user: RMOAS.User, selectedApp?: number | string) {\n if (!this.api?.components?.securitySchemes) {\n return {};\n }\n\n return getAuth(this.api, user, selectedApp);\n }\n\n /**\n * Returns the `paths` object that exists in this API definition but with every `method` mapped\n * to an instance of the `Operation` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getPaths() {\n /**\n * Because a path doesn't need to contain a keyed-object of HTTP methods, we should exclude\n * anything from within the paths object that isn't a known HTTP method.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#fixed-fields-7}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-7}\n */\n const paths: Record<string, Record<RMOAS.HttpMethods, Operation | Webhook>> = {};\n\n Object.keys(this.api.paths ? this.api.paths : []).forEach(path => {\n // If this is a specification extension then we should ignore it.\n if (path.startsWith('x-')) {\n return;\n }\n\n paths[path] = {} as Record<RMOAS.HttpMethods, Operation | Webhook>;\n\n // Though this library is generally unaware of `$ref` pointers we're making a singular\n // exception with this accessor out of convenience.\n if ('$ref' in this.api.paths[path]) {\n this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);\n }\n\n Object.keys(this.api.paths[path]).forEach((method: RMOAS.HttpMethods) => {\n if (!supportedMethods.has(method)) return;\n\n paths[path][method] = this.operation(path, method);\n });\n });\n\n return paths;\n }\n\n /**\n * Returns the `webhooks` object that exists in this API definition but with every `method`\n * mapped to an instance of the `Webhook` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getWebhooks() {\n const webhooks: Record<string, Record<RMOAS.HttpMethods, Webhook>> = {};\n const api = this.api as OpenAPIV3_1.Document;\n\n Object.keys(api.webhooks ? api.webhooks : []).forEach(id => {\n webhooks[id] = {} as Record<RMOAS.HttpMethods, Webhook>;\n Object.keys(api.webhooks[id]).forEach((method: RMOAS.HttpMethods) => {\n webhooks[id][method] = this.operation(id, method, { isWebhook: true }) as Webhook;\n });\n });\n\n return webhooks;\n }\n\n /**\n * Return an array of all tag names that exist on this API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n * @param setIfMissing If a tag is not present on an operation that operations path will be added\n * into the list of tags returned.\n */\n getTags(setIfMissing = false) {\n const allTags = new Set<string>();\n\n const oasTags =\n this.api.tags?.map(tag => {\n return tag.name;\n }) || [];\n\n const disableTagSorting = getExtension('disable-tag-sorting', this.api);\n\n Object.entries(this.getPaths()).forEach(([path, operations]) => {\n Object.values(operations).forEach(operation => {\n const tags = operation.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {\n Object.values(webhooks).forEach(webhook => {\n const tags = webhook.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n // Tags that exist only on the endpoint\n const endpointTags: string[] = [];\n // Tags that the user has defined in the `tags` array\n const tagsArray: string[] = [];\n\n // Distinguish between which tags exist in the `tags` array and which tags\n // exist only at the endpoint level. For tags that exist only at the\n // endpoint level, we'll just tack that on to the end of the sorted tags.\n if (disableTagSorting) {\n return Array.from(allTags);\n }\n\n Array.from(allTags).forEach(tag => {\n if (oasTags.includes(tag)) {\n tagsArray.push(tag);\n } else {\n endpointTags.push(tag);\n }\n });\n\n let sortedTags = tagsArray.sort((a, b) => {\n return oasTags.indexOf(a) - oasTags.indexOf(b);\n });\n\n sortedTags = sortedTags.concat(endpointTags);\n\n return sortedTags;\n }\n\n /**\n * Determine if a given a custom specification extension exists within the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n hasExtension(extension: string) {\n return hasRootExtension(extension, this.api);\n }\n\n /**\n * Retrieve a custom specification extension off of the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n getExtension(extension: string | keyof Extensions, operation?: Operation) {\n return getExtension(extension, this.api, operation);\n }\n\n /**\n * Determine if a given OpenAPI custom extension is valid or not.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to validate.\n * @throws\n */\n validateExtension(extension: keyof Extensions) {\n if (this.hasExtension('x-readme')) {\n const data = this.getExtension('x-readme') as Extensions;\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n throw new TypeError('\"x-readme\" must be of type \"Object\"');\n }\n\n if (extension in data) {\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data[extension])) {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data[extension], `x-readme.${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data[extension] !== 'object') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data[extension] !== 'boolean') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n // If the extension isn't grouped under `x-readme`, we need to look for them with `x-` prefixes.\n if (this.hasExtension(`x-${extension}`)) {\n const data = this.getExtension(`x-${extension}`);\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data)) {\n throw new TypeError(`\"x-${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data, `x-${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data !== 'object') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data !== 'boolean') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n /**\n * Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n */\n validateExtensions() {\n Object.keys(extensionDefaults).forEach((extension: keyof Extensions) => {\n this.validateExtension(extension);\n });\n }\n\n /**\n * Retrieve any circular `$ref` pointers that maybe present within the API definition.\n *\n * This method requires that you first dereference the definition.\n *\n * @see Oas.dereference\n */\n getCircularReferences() {\n if (!this.dereferencing.complete) {\n throw new Error('#dereference() must be called first in order for this method to obtain circular references.');\n }\n\n return this.dereferencing.circularRefs;\n }\n\n /**\n * Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas\n * and circular structures.\n *\n */\n async dereference(\n opts: {\n /**\n * A callback method can be supplied to be called when dereferencing is complete. Used for\n * debugging that the multi-promise handling within this method works.\n *\n * @private\n */\n cb?: () => void;\n\n /**\n * Preserve component schema names within themselves as a `title`.\n */\n preserveRefAsJSONSchemaTitle?: boolean;\n } = { preserveRefAsJSONSchemaTitle: false },\n ) {\n if (this.dereferencing.complete) {\n return new Promise(resolve => {\n resolve(true);\n });\n }\n\n if (this.dereferencing.processing) {\n return new Promise((resolve, reject) => {\n this.promises.push({ resolve, reject });\n });\n }\n\n this.dereferencing.processing = true;\n\n const { api, promises } = this;\n\n // Because referencing will eliminate any lineage back to the original `$ref`, information that\n // we might need at some point, we should run through all available component schemas and denote\n // what their name is so that when dereferencing happens below those names will be preserved.\n if (api && api.components && api.components.schemas && typeof api.components.schemas === 'object') {\n Object.keys(api.components.schemas).forEach(schemaName => {\n // As of OpenAPI 3.1 component schemas can be primitives or arrays. If this happens then we\n // shouldn't try to add `title` or `x-readme-ref-name` properties because we can't. We'll\n // have some data loss on these schemas but as they aren't objects they likely won't be used\n // in ways that would require needing a `title` or `x-readme-ref-name` anyways.\n if (\n isPrimitive(api.components.schemas[schemaName]) ||\n Array.isArray(api.components.schemas[schemaName]) ||\n api.components.schemas[schemaName] === null\n ) {\n return;\n }\n\n if (opts.preserveRefAsJSONSchemaTitle) {\n // This may result in some data loss if there's already a `title` present, but in the case\n // where we want to generate code for the API definition (see http://npm.im/api), we'd\n // prefer to retain original reference name as a title for any generated types.\n (api.components.schemas[schemaName] as RMOAS.SchemaObject).title = schemaName;\n }\n\n (api.components.schemas[schemaName] as RMOAS.SchemaObject)['x-readme-ref-name'] = schemaName;\n });\n }\n\n const parser = new $RefParser();\n\n return parser\n .dereference(api || {}, {\n resolve: {\n // We shouldn't be resolving external pointers at this point so just ignore them.\n external: false,\n },\n dereference: {\n // If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise\n // `$ref‘ just won't exist. This allows us to do easy circular reference detection.\n circular: 'ignore',\n },\n })\n .then((dereferenced: RMOAS.OASDocument) => {\n let circularRefs: string[] = [];\n if (parser.$refs.circular) {\n circularRefs = parser.$refs.circularRefs.map(pointer => {\n // The circular $refs that are coming out of `json-schema-ref-parser` are prefixed\n // with the schema path (file path, url, whatever) that the schema exists in. Because\n // we don't care about this information for this reporting mechanism, and only the\n // $ref pointer, we're removing it.\n return `#${pointer.split('#')[1]}`;\n });\n }\n\n this.api = dereferenced;\n\n this.promises = promises;\n this.dereferencing = {\n processing: false,\n complete: true,\n circularRefs,\n };\n\n // Used for debugging that dereferencing promise awaiting works.\n if (opts.cb) {\n opts.cb();\n }\n })\n .then(() => {\n return this.promises.map(deferred => deferred.resolve());\n });\n }\n}\n","import type * as RMOAS from '../types.js';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\ntype authKey = unknown | { password: number | string; user: number | string } | null;\n\n/**\n * @param user User to retrieve retrieve an auth key for.\n * @param scheme The type of security scheme that we want a key for.\n */\nfunction getKey(user: RMOAS.User, scheme: RMOAS.KeyedSecuritySchemeObject): authKey {\n switch (scheme.type) {\n case 'oauth2':\n case 'apiKey':\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n\n case 'http':\n if (scheme.scheme === 'basic') {\n return user[scheme._key] || { user: user.user || null, pass: user.pass || null };\n }\n\n if (scheme.scheme === 'bearer') {\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n }\n return null;\n\n default:\n return null;\n }\n}\n\n/**\n * Retrieve auth keys for a specific security scheme for a given user for a specific \"app\" that\n * they have configured.\n *\n * For `scheme` we're typing it to a union of `SecurityScheme` and `any` because we have handling\n * and tests for an unknown or unrecognized `type` and though it's not possible with the\n * `SecurityScheme.type` to be unrecognized it may still be possible to get an unrecognized scheme\n * with this method in the wild as we have API definitions in our database that were ingested\n * before we had good validation in place.\n *\n * @param user User\n * @param scheme Security scheme to get auth keys for.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getByScheme(\n user: RMOAS.User,\n scheme = <RMOAS.KeyedSecuritySchemeObject>{},\n selectedApp?: number | string,\n): authKey {\n if (user?.keys && user.keys.length) {\n if (selectedApp) {\n return getKey(\n user.keys.find(key => key.name === selectedApp),\n scheme,\n );\n }\n\n return getKey(user.keys[0], scheme);\n }\n\n return getKey(user, scheme);\n}\n\n/**\n * Retrieve auth keys for an API definition from a given user for a specific \"app\" that they have\n * configured.\n *\n * @param api API definition\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getAuth(\n api: OpenAPIV3_1.Document | OpenAPIV3.Document,\n user: RMOAS.User,\n selectedApp?: number | string,\n) {\n return Object.keys(api?.components?.securitySchemes || {})\n .map(scheme => {\n return {\n [scheme]: getByScheme(\n user,\n {\n // This sucks but since we dereference we'll never have a `$ref` pointer here with a\n // `ReferenceObject` type.\n ...(api.components.securitySchemes[scheme] as RMOAS.SecuritySchemeObject),\n _key: scheme,\n },\n selectedApp,\n ),\n };\n })\n .reduce((prev, next) => Object.assign(prev, next), {});\n}\n","import type * as RMOAS from '../types.js';\n\n/**\n * Retrieve a user variable off of a given user.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user The user to get a user variable for.\n * @param property The name of the variable to retrieve.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport default function getUserVariable(user: RMOAS.User, property: string, selectedApp?: number | string) {\n let key = user;\n\n if ('keys' in user && Array.isArray(user.keys) && user.keys.length) {\n if (selectedApp) {\n key = user.keys.find(k => k.name === selectedApp);\n } else {\n key = user.keys[0];\n }\n }\n\n return key[property] || user[property] || null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,gBAAgB;AACvB,SAAS,cAAc,aAAa;;;ACGpC,SAAS,OAAO,MAAkB,QAAkD;AAClF,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,KAAK,OAAO,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,KAAK;AAAA,IAEpE,KAAK;AACH,UAAI,OAAO,WAAW,SAAS;AAC7B,eAAO,KAAK,OAAO,IAAI,KAAK,EAAE,MAAM,KAAK,QAAQ,MAAM,MAAM,KAAK,QAAQ,KAAK;AAAA,MACjF;AAEA,UAAI,OAAO,WAAW,UAAU;AAC9B,eAAO,KAAK,OAAO,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,KAAK;AAAA,MACpE;AACA,aAAO;AAAA,IAET;AACE,aAAO;AAAA,EACX;AACF;AAgBO,SAAS,YACd,MACA,SAA0C,CAAC,GAC3C,aACS;AACT,MAAI,MAAM,QAAQ,KAAK,KAAK,QAAQ;AAClC,QAAI,aAAa;AACf,aAAO;AAAA,QACL,KAAK,KAAK,KAAK,SAAO,IAAI,SAAS,WAAW;AAAA,QAC9C;AAAA,MACF;AAAA,IACF;AAEA,WAAO,OAAO,KAAK,KAAK,CAAC,GAAG,MAAM;AAAA,EACpC;AAEA,SAAO,OAAO,MAAM,MAAM;AAC5B;AAUO,SAAS,QACd,KACA,MACA,aACA;AACA,SAAO,OAAO,KAAK,KAAK,YAAY,mBAAmB,CAAC,CAAC,EACtD,IAAI,YAAU;AACb,WAAO;AAAA,MACL,CAAC,MAAM,GAAG;AAAA,QACR;AAAA,QACA;AAAA;AAAA;AAAA,UAGE,GAAI,IAAI,WAAW,gBAAgB,MAAM;AAAA,UACzC,MAAM;AAAA,QACR;AAAA,QACA;AAAA,MACF;AAAA,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|
+
var _chunkOEMVNKDJcjs = require('./chunk-OEMVNKDJ.cjs');
|
|
4
4
|
require('./chunk-3FVUMJJI.cjs');
|
|
5
5
|
require('./chunk-VIIXOUMH.cjs');
|
|
6
6
|
require('./chunk-OD3GKGB2.cjs');
|
|
@@ -8,7 +8,7 @@ require('./chunk-YHO3AOX6.cjs');
|
|
|
8
8
|
require('./chunk-G6ASGSM5.cjs');
|
|
9
9
|
|
|
10
10
|
|
|
11
|
-
exports.default =
|
|
11
|
+
exports.default = _chunkOEMVNKDJcjs.Oas;
|
|
12
12
|
|
|
13
13
|
module.exports = exports.default;
|
|
14
14
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/reducer/index.ts"],"names":[],"mappings":";;;;;AAEA,OAAO,iBAAiB;AACxB,SAAS,4BAA4B;AAgBrC,SAAS,YAAY,QAAa;AAChC,SAAO,MAAM,CAAC,aAAa,GAAG,MAAM;AACtC;AAUA,SAAS,mBAAmB,QAAiC,OAAoB,MAAiB;AAChG,MAAI;AACJ,MAAI,OAAO,SAAS;AAAU,iBAAa,YAAY,IAAI,QAAQ,KAAK,UAAU,CAAC,CAAC;AACpF,MAAI,eAAe,QAAW;AAI5B;AAAA,EACF;AAEA,cAAY,UAAU,EAAE,QAAQ,CAAC,EAAE,OAAO,QAAQ,MAAM;AAEtD,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB;AAAA,IACF;AAEA,UAAM,IAAI,OAAO;AACjB,uBAAmB,QAAQ,OAAO,OAAO;AAAA,EAC3C,CAAC;AACH;AAiBe,SAAR,QAAyB,YAAyB,OAAuB,CAAC,GAAG;AAElF,QAAM,aAAa,UAAU,OAAO,KAAK,KAAK,IAAI,SAAO,IAAI,YAAY,CAAC,IAAI,CAAC;AAC/E,QAAM,cACJ,WAAW,OACP,OAAO,QAAQ,KAAK,KAAK,EAAE,OAAO,CAAC,KAAwC,CAAC,KAAK,KAAK,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AAa,IAAI,SAAS,EAAE,GAAG;AAC5D,iBAAO,QAAQ,WAAW,aAAa,EAAE,SAAS;AAAA,QACpD;AAAA,MACF,CAAC;AAGD,UAAI,CAAC,OAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ;AAC1D,eAAO,QAAQ,WAAW,aAAa;AAAA,MACzC;AAAA,IACF,CAAC;AAGD,QAAI,CAAC,OAAO,KAAK,QAAQ,UAAU,EAAE,QAAQ;AAC3C,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAGA,MAAI,UAAU,SAAS;AACrB,YAAQ,KAAK,QAAQ,CAAC,KAAgB,MAAc;AAClD,UAAI,CAAC,SAAS,IAAI,IAAI,IAAI,GAAG;AAC3B,eAAO,QAAQ,KAAK,CAAC;AAAA,MACvB;AAAA,IACF,CAAC;AAGD,YAAQ,OAAO,QAAQ,KAAK,OAAO,OAAO;AAE1C,QAAI,CAAC,QAAQ,KAAK,QAAQ;AACxB,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import type { ComponentsObject, HttpMethods, OASDocument, TagObject } from '../types.js';\n\nimport jsonPointer from 'jsonpointer';\nimport { getAPIDefinitionType } from 'oas-normalize/lib/utils';\n\nimport { query } from '../analyzer/util.js';\n\ninterface ReducerOptions {\n /** A key-value object of path + method combinations to reduce by. */\n paths?: Record<string, string[] | '*'>;\n /** An array of tags in the OpenAPI definition to reduce by. */\n tags?: string[];\n}\n\n/**\n * Query a JSON Schema object for any `$ref` pointers. Return any pointers that were found.\n *\n * @param schema JSON Schema object to look for any `$ref` pointers within it.\n */\nfunction getUsedRefs(schema: any) {\n return query([\"$..['$ref']\"], schema);\n}\n\n/**\n * Recursively process a `$ref` pointer and accumulate any other `$ref` pointers that it or its\n * children use.\n *\n * @param schema JSON Schema object to look for and accumulate any `$ref` pointers that it may have.\n * @param $refs Known set of `$ref` pointers.\n * @param $ref `$ref` pointer to fetch a schema from out of the supplied schema.\n */\nfunction accumulateUsedRefs(schema: Record<string, unknown>, $refs: Set<string>, $ref: any): void {\n let $refSchema;\n if (typeof $ref === 'string') $refSchema = jsonPointer.get(schema, $ref.substring(1));\n if ($refSchema === undefined) {\n // If the schema we have wasn't fully dereferenced or bundled for whatever reason and this\n // `$ref` that we have doens't exist here we shouldn't try to search for more `$ref` pointers\n // in a schema that doesn't exist.\n return;\n }\n\n getUsedRefs($refSchema).forEach(({ value: currRef }) => {\n // If we've already processed this $ref don't send us into an infinite loop.\n if ($refs.has(currRef)) {\n return;\n }\n\n $refs.add(currRef);\n accumulateUsedRefs(schema, $refs, currRef);\n });\n}\n\n/**\n * With an array of tags or object of paths+method combinations, reduce an OpenAPI definition to a\n * new definition that just contains those tags or path + methods.\n *\n * @example <caption>Reduce by an array of tags only.</caption>\n * reducer(apiDefinition, { tags: ['pet'] })\n *\n * @example <caption>Reduce by a specific path and methods.</caption>\n * reducer(apiDefinition, { paths: { '/pet': ['get', 'post'] } })\n *\n * @example <caption>Reduce by a specific path and all methods it has.</caption>\n * reducer(apiDefinition, { paths: { '/pet': '*' } })\n *\n * @param definition A valid OpenAPI 3.x definition\n */\nexport default function reducer(definition: OASDocument, opts: ReducerOptions = {}) {\n // Convert tags and paths to lowercase since casing should not matter.\n const reduceTags = 'tags' in opts ? opts.tags.map(tag => tag.toLowerCase()) : [];\n const reducePaths =\n 'paths' in opts\n ? Object.entries(opts.paths).reduce((acc: Record<string, string[] | string>, [key, value]) => {\n const newKey = key.toLowerCase();\n const newValue = Array.isArray(value) ? value.map(v => v.toLowerCase()) : value.toLowerCase();\n acc[newKey] = newValue;\n return acc;\n }, {})\n : {};\n\n const $refs: Set<string> = new Set();\n const usedTags: Set<string> = new Set();\n\n if (getAPIDefinitionType(definition) !== 'openapi') {\n throw new Error('Sorry, only OpenAPI definitions are supported.');\n }\n\n // Stringify and parse so we get a full non-reference clone of the API definition to work with.\n const reduced = JSON.parse(JSON.stringify(definition)) as OASDocument;\n\n // Retain any root-level security definitions.\n if ('security' in reduced) {\n Object.values(reduced.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n\n if ('paths' in reduced) {\n Object.keys(reduced.paths).forEach(path => {\n const pathLC = path.toLowerCase();\n\n if (Object.keys(reducePaths).length) {\n if (!(pathLC in reducePaths)) {\n delete reduced.paths[path];\n return;\n }\n }\n\n Object.keys(reduced.paths[path]).forEach((method: HttpMethods | 'parameters') => {\n // If this method is `parameters` we should always retain it.\n if (method !== 'parameters') {\n if (Object.keys(reducePaths).length) {\n if (\n reducePaths[pathLC] !== '*' &&\n Array.isArray(reducePaths[pathLC]) &&\n !reducePaths[pathLC].includes(method)\n ) {\n delete reduced.paths[path][method];\n return;\n }\n }\n }\n\n const operation = reduced.paths[path][method];\n\n // If we're reducing by tags and this operation doesn't live in one of those, remove it.\n if (reduceTags.length) {\n if (!('tags' in operation)) {\n delete reduced.paths[path][method];\n return;\n } else if (!operation.tags.filter(tag => reduceTags.includes(tag.toLowerCase())).length) {\n delete reduced.paths[path][method];\n return;\n }\n }\n\n // Accumulate a list of used tags so we can filter out any ones that we don't need later.\n if ('tags' in operation) {\n operation.tags.forEach((tag: string) => {\n usedTags.add(tag);\n });\n }\n\n // Accumulate a list of $ref pointers that are used within this operation.\n getUsedRefs(operation).forEach(({ value: ref }) => {\n $refs.add(ref);\n });\n\n // Accumulate any used security schemas that we need to retain.\n if ('security' in operation) {\n Object.values(operation.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n });\n\n // If this path no longer has any methods, delete it.\n if (!Object.keys(reduced.paths[path]).length) {\n delete reduced.paths[path];\n }\n });\n\n // If we don't have any more paths after cleanup, throw an error because an OpenAPI file must\n // have at least one path.\n if (!Object.keys(reduced.paths).length) {\n throw new Error('All paths in the API definition were removed. Did you supply the right path name to reduce by?');\n }\n }\n\n // Recursively accumulate any components that are in use.\n $refs.forEach($ref => accumulateUsedRefs(reduced, $refs, $ref));\n\n // Remove any unused components.\n if ('components' in reduced) {\n Object.keys(reduced.components).forEach((componentType: keyof ComponentsObject) => {\n Object.keys(reduced.components[componentType]).forEach(component => {\n if (!$refs.has(`#/components/${componentType}/${component}`)) {\n delete reduced.components[componentType][component];\n }\n });\n\n // If this component group is now empty, delete it.\n if (!Object.keys(reduced.components[componentType]).length) {\n delete reduced.components[componentType];\n }\n });\n\n // If this path no longer has any components, delete it.\n if (!Object.keys(reduced.components).length) {\n delete reduced.components;\n }\n }\n\n // Remove any unused tags.\n if ('tags' in reduced) {\n reduced.tags.forEach((tag: TagObject, k: number) => {\n if (!usedTags.has(tag.name)) {\n delete reduced.tags[k];\n }\n });\n\n // Remove any now empty items from the tags array.\n reduced.tags = reduced.tags.filter(Boolean);\n\n if (!reduced.tags.length) {\n delete reduced.tags;\n }\n }\n\n return reduced;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/reducer/index.ts"],"names":[],"mappings":";;;;;AAEA,OAAO,iBAAiB;AACxB,SAAS,4BAA4B;AAgBrC,SAAS,YAAY,QAAa;AAChC,SAAO,MAAM,CAAC,aAAa,GAAG,MAAM;AACtC;AAUA,SAAS,mBAAmB,QAAiC,OAAoB,MAAiB;AAChG,MAAI;AACJ,MAAI,OAAO,SAAS;AAAU,iBAAa,YAAY,IAAI,QAAQ,KAAK,UAAU,CAAC,CAAC;AACpF,MAAI,eAAe,QAAW;AAI5B;AAAA,EACF;AAEA,cAAY,UAAU,EAAE,QAAQ,CAAC,EAAE,OAAO,QAAQ,MAAM;AAEtD,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB;AAAA,IACF;AAEA,UAAM,IAAI,OAAO;AACjB,uBAAmB,QAAQ,OAAO,OAAO;AAAA,EAC3C,CAAC;AACH;AAiBe,SAAR,QAAyB,YAAyB,OAAuB,CAAC,GAAG;AAElF,QAAM,aAAa,UAAU,OAAO,KAAK,KAAK,IAAI,SAAO,IAAI,YAAY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,CAAC,kBAA0C;AACjF,aAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ,eAAa;AAClE,YAAI,CAAC,MAAM,IAAI,gBAAgB,aAAa,IAAI,SAAS,EAAE,GAAG;AAC5D,iBAAO,QAAQ,WAAW,aAAa,EAAE,SAAS;AAAA,QACpD;AAAA,MACF,CAAC;AAGD,UAAI,CAAC,OAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ;AAC1D,eAAO,QAAQ,WAAW,aAAa;AAAA,MACzC;AAAA,IACF,CAAC;AAGD,QAAI,CAAC,OAAO,KAAK,QAAQ,UAAU,EAAE,QAAQ;AAC3C,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAGA,MAAI,UAAU,SAAS;AACrB,YAAQ,KAAK,QAAQ,CAAC,KAAgB,MAAc;AAClD,UAAI,CAAC,SAAS,IAAI,IAAI,IAAI,GAAG;AAC3B,eAAO,QAAQ,KAAK,CAAC;AAAA,MACvB;AAAA,IACF,CAAC;AAGD,YAAQ,OAAO,QAAQ,KAAK,OAAO,OAAO;AAE1C,QAAI,CAAC,QAAQ,KAAK,QAAQ;AACxB,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import type { ComponentsObject, HttpMethods, OASDocument, TagObject } from '../types.js';\n\nimport jsonPointer from 'jsonpointer';\nimport { getAPIDefinitionType } from 'oas-normalize/lib/utils';\n\nimport { query } from '../analyzer/util.js';\n\ninterface ReducerOptions {\n /** A key-value object of path + method combinations to reduce by. */\n paths?: Record<string, string[] | '*'>;\n /** An array of tags in the OpenAPI definition to reduce by. */\n tags?: string[];\n}\n\n/**\n * Query a JSON Schema object for any `$ref` pointers. Return any pointers that were found.\n *\n * @param schema JSON Schema object to look for any `$ref` pointers within it.\n */\nfunction getUsedRefs(schema: any) {\n return query([\"$..['$ref']\"], schema);\n}\n\n/**\n * Recursively process a `$ref` pointer and accumulate any other `$ref` pointers that it or its\n * children use.\n *\n * @param schema JSON Schema object to look for and accumulate any `$ref` pointers that it may have.\n * @param $refs Known set of `$ref` pointers.\n * @param $ref `$ref` pointer to fetch a schema from out of the supplied schema.\n */\nfunction accumulateUsedRefs(schema: Record<string, unknown>, $refs: Set<string>, $ref: any): void {\n let $refSchema;\n if (typeof $ref === 'string') $refSchema = jsonPointer.get(schema, $ref.substring(1));\n if ($refSchema === undefined) {\n // If the schema we have wasn't fully dereferenced or bundled for whatever reason and this\n // `$ref` that we have doesn't exist here we shouldn't try to search for more `$ref` pointers\n // in a schema that doesn't exist.\n return;\n }\n\n getUsedRefs($refSchema).forEach(({ value: currRef }) => {\n // If we've already processed this $ref don't send us into an infinite loop.\n if ($refs.has(currRef)) {\n return;\n }\n\n $refs.add(currRef);\n accumulateUsedRefs(schema, $refs, currRef);\n });\n}\n\n/**\n * With an array of tags or object of paths+method combinations, reduce an OpenAPI definition to a\n * new definition that just contains those tags or path + methods.\n *\n * @example <caption>Reduce by an array of tags only.</caption>\n * reducer(apiDefinition, { tags: ['pet'] })\n *\n * @example <caption>Reduce by a specific path and methods.</caption>\n * reducer(apiDefinition, { paths: { '/pet': ['get', 'post'] } })\n *\n * @example <caption>Reduce by a specific path and all methods it has.</caption>\n * reducer(apiDefinition, { paths: { '/pet': '*' } })\n *\n * @param definition A valid OpenAPI 3.x definition\n */\nexport default function reducer(definition: OASDocument, opts: ReducerOptions = {}) {\n // Convert tags and paths to lowercase since casing should not matter.\n const reduceTags = 'tags' in opts ? opts.tags.map(tag => tag.toLowerCase()) : [];\n const reducePaths =\n 'paths' in opts\n ? Object.entries(opts.paths).reduce((acc: Record<string, string[] | string>, [key, value]) => {\n const newKey = key.toLowerCase();\n const newValue = Array.isArray(value) ? value.map(v => v.toLowerCase()) : value.toLowerCase();\n acc[newKey] = newValue;\n return acc;\n }, {})\n : {};\n\n const $refs: Set<string> = new Set();\n const usedTags: Set<string> = new Set();\n\n if (getAPIDefinitionType(definition) !== 'openapi') {\n throw new Error('Sorry, only OpenAPI definitions are supported.');\n }\n\n // Stringify and parse so we get a full non-reference clone of the API definition to work with.\n const reduced = JSON.parse(JSON.stringify(definition)) as OASDocument;\n\n // Retain any root-level security definitions.\n if ('security' in reduced) {\n Object.values(reduced.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n\n if ('paths' in reduced) {\n Object.keys(reduced.paths).forEach(path => {\n const pathLC = path.toLowerCase();\n\n if (Object.keys(reducePaths).length) {\n if (!(pathLC in reducePaths)) {\n delete reduced.paths[path];\n return;\n }\n }\n\n Object.keys(reduced.paths[path]).forEach((method: HttpMethods | 'parameters') => {\n // If this method is `parameters` we should always retain it.\n if (method !== 'parameters') {\n if (Object.keys(reducePaths).length) {\n if (\n reducePaths[pathLC] !== '*' &&\n Array.isArray(reducePaths[pathLC]) &&\n !reducePaths[pathLC].includes(method)\n ) {\n delete reduced.paths[path][method];\n return;\n }\n }\n }\n\n const operation = reduced.paths[path][method];\n\n // If we're reducing by tags and this operation doesn't live in one of those, remove it.\n if (reduceTags.length) {\n if (!('tags' in operation)) {\n delete reduced.paths[path][method];\n return;\n } else if (!operation.tags.filter(tag => reduceTags.includes(tag.toLowerCase())).length) {\n delete reduced.paths[path][method];\n return;\n }\n }\n\n // Accumulate a list of used tags so we can filter out any ones that we don't need later.\n if ('tags' in operation) {\n operation.tags.forEach((tag: string) => {\n usedTags.add(tag);\n });\n }\n\n // Accumulate a list of $ref pointers that are used within this operation.\n getUsedRefs(operation).forEach(({ value: ref }) => {\n $refs.add(ref);\n });\n\n // Accumulate any used security schemas that we need to retain.\n if ('security' in operation) {\n Object.values(operation.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n });\n\n // If this path no longer has any methods, delete it.\n if (!Object.keys(reduced.paths[path]).length) {\n delete reduced.paths[path];\n }\n });\n\n // If we don't have any more paths after cleanup, throw an error because an OpenAPI file must\n // have at least one path.\n if (!Object.keys(reduced.paths).length) {\n throw new Error('All paths in the API definition were removed. Did you supply the right path name to reduce by?');\n }\n }\n\n // Recursively accumulate any components that are in use.\n $refs.forEach($ref => accumulateUsedRefs(reduced, $refs, $ref));\n\n // Remove any unused components.\n if ('components' in reduced) {\n Object.keys(reduced.components).forEach((componentType: keyof ComponentsObject) => {\n Object.keys(reduced.components[componentType]).forEach(component => {\n if (!$refs.has(`#/components/${componentType}/${component}`)) {\n delete reduced.components[componentType][component];\n }\n });\n\n // If this component group is now empty, delete it.\n if (!Object.keys(reduced.components[componentType]).length) {\n delete reduced.components[componentType];\n }\n });\n\n // If this path no longer has any components, delete it.\n if (!Object.keys(reduced.components).length) {\n delete reduced.components;\n }\n }\n\n // Remove any unused tags.\n if ('tags' in reduced) {\n reduced.tags.forEach((tag: TagObject, k: number) => {\n if (!usedTags.has(tag.name)) {\n delete reduced.tags[k];\n }\n });\n\n // Remove any now empty items from the tags array.\n reduced.tags = reduced.tags.filter(Boolean);\n\n if (!reduced.tags.length) {\n delete reduced.tags;\n }\n }\n\n return reduced;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/reducer/index.ts"],"sourcesContent":["import type { ComponentsObject, HttpMethods, OASDocument, TagObject } from '../types.js';\n\nimport jsonPointer from 'jsonpointer';\nimport { getAPIDefinitionType } from 'oas-normalize/lib/utils';\n\nimport { query } from '../analyzer/util.js';\n\ninterface ReducerOptions {\n /** A key-value object of path + method combinations to reduce by. */\n paths?: Record<string, string[] | '*'>;\n /** An array of tags in the OpenAPI definition to reduce by. */\n tags?: string[];\n}\n\n/**\n * Query a JSON Schema object for any `$ref` pointers. Return any pointers that were found.\n *\n * @param schema JSON Schema object to look for any `$ref` pointers within it.\n */\nfunction getUsedRefs(schema: any) {\n return query([\"$..['$ref']\"], schema);\n}\n\n/**\n * Recursively process a `$ref` pointer and accumulate any other `$ref` pointers that it or its\n * children use.\n *\n * @param schema JSON Schema object to look for and accumulate any `$ref` pointers that it may have.\n * @param $refs Known set of `$ref` pointers.\n * @param $ref `$ref` pointer to fetch a schema from out of the supplied schema.\n */\nfunction accumulateUsedRefs(schema: Record<string, unknown>, $refs: Set<string>, $ref: any): void {\n let $refSchema;\n if (typeof $ref === 'string') $refSchema = jsonPointer.get(schema, $ref.substring(1));\n if ($refSchema === undefined) {\n // If the schema we have wasn't fully dereferenced or bundled for whatever reason and this\n // `$ref` that we have doens't exist here we shouldn't try to search for more `$ref` pointers\n // in a schema that doesn't exist.\n return;\n }\n\n getUsedRefs($refSchema).forEach(({ value: currRef }) => {\n // If we've already processed this $ref don't send us into an infinite loop.\n if ($refs.has(currRef)) {\n return;\n }\n\n $refs.add(currRef);\n accumulateUsedRefs(schema, $refs, currRef);\n });\n}\n\n/**\n * With an array of tags or object of paths+method combinations, reduce an OpenAPI definition to a\n * new definition that just contains those tags or path + methods.\n *\n * @example <caption>Reduce by an array of tags only.</caption>\n * reducer(apiDefinition, { tags: ['pet'] })\n *\n * @example <caption>Reduce by a specific path and methods.</caption>\n * reducer(apiDefinition, { paths: { '/pet': ['get', 'post'] } })\n *\n * @example <caption>Reduce by a specific path and all methods it has.</caption>\n * reducer(apiDefinition, { paths: { '/pet': '*' } })\n *\n * @param definition A valid OpenAPI 3.x definition\n */\nexport default function reducer(definition: OASDocument, opts: ReducerOptions = {}) {\n // Convert tags and paths to lowercase since casing should not matter.\n const reduceTags = 'tags' in opts ? opts.tags.map(tag => tag.toLowerCase()) : [];\n const reducePaths =\n 'paths' in opts\n ? Object.entries(opts.paths).reduce((acc: Record<string, string[] | string>, [key, value]) => {\n const newKey = key.toLowerCase();\n const newValue = Array.isArray(value) ? value.map(v => v.toLowerCase()) : value.toLowerCase();\n acc[newKey] = newValue;\n return acc;\n }, {})\n : {};\n\n const $refs: Set<string> = new Set();\n const usedTags: Set<string> = new Set();\n\n if (getAPIDefinitionType(definition) !== 'openapi') {\n throw new Error('Sorry, only OpenAPI definitions are supported.');\n }\n\n // Stringify and parse so we get a full non-reference clone of the API definition to work with.\n const reduced = JSON.parse(JSON.stringify(definition)) as OASDocument;\n\n // Retain any root-level security definitions.\n if ('security' in reduced) {\n Object.values(reduced.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n\n if ('paths' in reduced) {\n Object.keys(reduced.paths).forEach(path => {\n const pathLC = path.toLowerCase();\n\n if (Object.keys(reducePaths).length) {\n if (!(pathLC in reducePaths)) {\n delete reduced.paths[path];\n return;\n }\n }\n\n Object.keys(reduced.paths[path]).forEach((method: HttpMethods | 'parameters') => {\n // If this method is `parameters` we should always retain it.\n if (method !== 'parameters') {\n if (Object.keys(reducePaths).length) {\n if (\n reducePaths[pathLC] !== '*' &&\n Array.isArray(reducePaths[pathLC]) &&\n !reducePaths[pathLC].includes(method)\n ) {\n delete reduced.paths[path][method];\n return;\n }\n }\n }\n\n const operation = reduced.paths[path][method];\n\n // If we're reducing by tags and this operation doesn't live in one of those, remove it.\n if (reduceTags.length) {\n if (!('tags' in operation)) {\n delete reduced.paths[path][method];\n return;\n } else if (!operation.tags.filter(tag => reduceTags.includes(tag.toLowerCase())).length) {\n delete reduced.paths[path][method];\n return;\n }\n }\n\n // Accumulate a list of used tags so we can filter out any ones that we don't need later.\n if ('tags' in operation) {\n operation.tags.forEach((tag: string) => {\n usedTags.add(tag);\n });\n }\n\n // Accumulate a list of $ref pointers that are used within this operation.\n getUsedRefs(operation).forEach(({ value: ref }) => {\n $refs.add(ref);\n });\n\n // Accumulate any used security schemas that we need to retain.\n if ('security' in operation) {\n Object.values(operation.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n });\n\n // If this path no longer has any methods, delete it.\n if (!Object.keys(reduced.paths[path]).length) {\n delete reduced.paths[path];\n }\n });\n\n // If we don't have any more paths after cleanup, throw an error because an OpenAPI file must\n // have at least one path.\n if (!Object.keys(reduced.paths).length) {\n throw new Error('All paths in the API definition were removed. Did you supply the right path name to reduce by?');\n }\n }\n\n // Recursively accumulate any components that are in use.\n $refs.forEach($ref => accumulateUsedRefs(reduced, $refs, $ref));\n\n // Remove any unused components.\n if ('components' in reduced) {\n Object.keys(reduced.components).forEach((componentType: keyof ComponentsObject) => {\n Object.keys(reduced.components[componentType]).forEach(component => {\n if (!$refs.has(`#/components/${componentType}/${component}`)) {\n delete reduced.components[componentType][component];\n }\n });\n\n // If this component group is now empty, delete it.\n if (!Object.keys(reduced.components[componentType]).length) {\n delete reduced.components[componentType];\n }\n });\n\n // If this path no longer has any components, delete it.\n if (!Object.keys(reduced.components).length) {\n delete reduced.components;\n }\n }\n\n // Remove any unused tags.\n if ('tags' in reduced) {\n reduced.tags.forEach((tag: TagObject, k: number) => {\n if (!usedTags.has(tag.name)) {\n delete reduced.tags[k];\n }\n });\n\n // Remove any now empty items from the tags array.\n reduced.tags = reduced.tags.filter(Boolean);\n\n if (!reduced.tags.length) {\n delete reduced.tags;\n }\n }\n\n return reduced;\n}\n"],"mappings":";;;;;AAEA,OAAO,iBAAiB;AACxB,SAAS,4BAA4B;AAgBrC,SAAS,YAAY,QAAa;AAChC,SAAO,MAAM,CAAC,aAAa,GAAG,MAAM;AACtC;AAUA,SAAS,mBAAmB,QAAiC,OAAoB,MAAiB;AAChG,MAAI;AACJ,MAAI,OAAO,SAAS;AAAU,iBAAa,YAAY,IAAI,QAAQ,KAAK,UAAU,CAAC,CAAC;AACpF,MAAI,eAAe,QAAW;AAI5B;AAAA,EACF;AAEA,cAAY,UAAU,EAAE,QAAQ,CAAC,EAAE,OAAO,QAAQ,MAAM;AAEtD,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB;AAAA,IACF;AAEA,UAAM,IAAI,OAAO;AACjB,uBAAmB,QAAQ,OAAO,OAAO;AAAA,EAC3C,CAAC;AACH;AAiBe,SAAR,QAAyB,YAAyB,OAAuB,CAAC,GAAG;AAElF,QAAM,aAAa,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S;AAC3B,WAAO,KAAK,QAAQ,UAAU,EAAE,QAAQ,CAAC,kBAA0C;AACjF,aAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ,eAAa;AAClE,YAAI,CAAC,MAAM,IAAI,gBAAgB,aAAa,IAAI,SAAS,EAAE,GAAG;AAC5D,iBAAO,QAAQ,WAAW,aAAa,EAAE,SAAS;AAAA,QACpD;AAAA,MACF,CAAC;AAGD,UAAI,CAAC,OAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ;AAC1D,eAAO,QAAQ,WAAW,aAAa;AAAA,MACzC;AAAA,IACF,CAAC;AAGD,QAAI,CAAC,OAAO,KAAK,QAAQ,UAAU,EAAE,QAAQ;AAC3C,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAGA,MAAI,UAAU,SAAS;AACrB,YAAQ,KAAK,QAAQ,CAAC,KAAgB,MAAc;AAClD,UAAI,CAAC,SAAS,IAAI,IAAI,IAAI,GAAG;AAC3B,eAAO,QAAQ,KAAK,CAAC;AAAA,MACvB;AAAA,IACF,CAAC;AAGD,YAAQ,OAAO,QAAQ,KAAK,OAAO,OAAO;AAE1C,QAAI,CAAC,QAAQ,KAAK,QAAQ;AACxB,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/reducer/index.ts"],"sourcesContent":["import type { ComponentsObject, HttpMethods, OASDocument, TagObject } from '../types.js';\n\nimport jsonPointer from 'jsonpointer';\nimport { getAPIDefinitionType } from 'oas-normalize/lib/utils';\n\nimport { query } from '../analyzer/util.js';\n\ninterface ReducerOptions {\n /** A key-value object of path + method combinations to reduce by. */\n paths?: Record<string, string[] | '*'>;\n /** An array of tags in the OpenAPI definition to reduce by. */\n tags?: string[];\n}\n\n/**\n * Query a JSON Schema object for any `$ref` pointers. Return any pointers that were found.\n *\n * @param schema JSON Schema object to look for any `$ref` pointers within it.\n */\nfunction getUsedRefs(schema: any) {\n return query([\"$..['$ref']\"], schema);\n}\n\n/**\n * Recursively process a `$ref` pointer and accumulate any other `$ref` pointers that it or its\n * children use.\n *\n * @param schema JSON Schema object to look for and accumulate any `$ref` pointers that it may have.\n * @param $refs Known set of `$ref` pointers.\n * @param $ref `$ref` pointer to fetch a schema from out of the supplied schema.\n */\nfunction accumulateUsedRefs(schema: Record<string, unknown>, $refs: Set<string>, $ref: any): void {\n let $refSchema;\n if (typeof $ref === 'string') $refSchema = jsonPointer.get(schema, $ref.substring(1));\n if ($refSchema === undefined) {\n // If the schema we have wasn't fully dereferenced or bundled for whatever reason and this\n // `$ref` that we have doesn't exist here we shouldn't try to search for more `$ref` pointers\n // in a schema that doesn't exist.\n return;\n }\n\n getUsedRefs($refSchema).forEach(({ value: currRef }) => {\n // If we've already processed this $ref don't send us into an infinite loop.\n if ($refs.has(currRef)) {\n return;\n }\n\n $refs.add(currRef);\n accumulateUsedRefs(schema, $refs, currRef);\n });\n}\n\n/**\n * With an array of tags or object of paths+method combinations, reduce an OpenAPI definition to a\n * new definition that just contains those tags or path + methods.\n *\n * @example <caption>Reduce by an array of tags only.</caption>\n * reducer(apiDefinition, { tags: ['pet'] })\n *\n * @example <caption>Reduce by a specific path and methods.</caption>\n * reducer(apiDefinition, { paths: { '/pet': ['get', 'post'] } })\n *\n * @example <caption>Reduce by a specific path and all methods it has.</caption>\n * reducer(apiDefinition, { paths: { '/pet': '*' } })\n *\n * @param definition A valid OpenAPI 3.x definition\n */\nexport default function reducer(definition: OASDocument, opts: ReducerOptions = {}) {\n // Convert tags and paths to lowercase since casing should not matter.\n const reduceTags = 'tags' in opts ? opts.tags.map(tag => tag.toLowerCase()) : [];\n const reducePaths =\n 'paths' in opts\n ? Object.entries(opts.paths).reduce((acc: Record<string, string[] | string>, [key, value]) => {\n const newKey = key.toLowerCase();\n const newValue = Array.isArray(value) ? value.map(v => v.toLowerCase()) : value.toLowerCase();\n acc[newKey] = newValue;\n return acc;\n }, {})\n : {};\n\n const $refs: Set<string> = new Set();\n const usedTags: Set<string> = new Set();\n\n if (getAPIDefinitionType(definition) !== 'openapi') {\n throw new Error('Sorry, only OpenAPI definitions are supported.');\n }\n\n // Stringify and parse so we get a full non-reference clone of the API definition to work with.\n const reduced = JSON.parse(JSON.stringify(definition)) as OASDocument;\n\n // Retain any root-level security definitions.\n if ('security' in reduced) {\n Object.values(reduced.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n\n if ('paths' in reduced) {\n Object.keys(reduced.paths).forEach(path => {\n const pathLC = path.toLowerCase();\n\n if (Object.keys(reducePaths).length) {\n if (!(pathLC in reducePaths)) {\n delete reduced.paths[path];\n return;\n }\n }\n\n Object.keys(reduced.paths[path]).forEach((method: HttpMethods | 'parameters') => {\n // If this method is `parameters` we should always retain it.\n if (method !== 'parameters') {\n if (Object.keys(reducePaths).length) {\n if (\n reducePaths[pathLC] !== '*' &&\n Array.isArray(reducePaths[pathLC]) &&\n !reducePaths[pathLC].includes(method)\n ) {\n delete reduced.paths[path][method];\n return;\n }\n }\n }\n\n const operation = reduced.paths[path][method];\n\n // If we're reducing by tags and this operation doesn't live in one of those, remove it.\n if (reduceTags.length) {\n if (!('tags' in operation)) {\n delete reduced.paths[path][method];\n return;\n } else if (!operation.tags.filter(tag => reduceTags.includes(tag.toLowerCase())).length) {\n delete reduced.paths[path][method];\n return;\n }\n }\n\n // Accumulate a list of used tags so we can filter out any ones that we don't need later.\n if ('tags' in operation) {\n operation.tags.forEach((tag: string) => {\n usedTags.add(tag);\n });\n }\n\n // Accumulate a list of $ref pointers that are used within this operation.\n getUsedRefs(operation).forEach(({ value: ref }) => {\n $refs.add(ref);\n });\n\n // Accumulate any used security schemas that we need to retain.\n if ('security' in operation) {\n Object.values(operation.security).forEach(sec => {\n Object.keys(sec).forEach(scheme => {\n $refs.add(`#/components/securitySchemes/${scheme}`);\n });\n });\n }\n });\n\n // If this path no longer has any methods, delete it.\n if (!Object.keys(reduced.paths[path]).length) {\n delete reduced.paths[path];\n }\n });\n\n // If we don't have any more paths after cleanup, throw an error because an OpenAPI file must\n // have at least one path.\n if (!Object.keys(reduced.paths).length) {\n throw new Error('All paths in the API definition were removed. Did you supply the right path name to reduce by?');\n }\n }\n\n // Recursively accumulate any components that are in use.\n $refs.forEach($ref => accumulateUsedRefs(reduced, $refs, $ref));\n\n // Remove any unused components.\n if ('components' in reduced) {\n Object.keys(reduced.components).forEach((componentType: keyof ComponentsObject) => {\n Object.keys(reduced.components[componentType]).forEach(component => {\n if (!$refs.has(`#/components/${componentType}/${component}`)) {\n delete reduced.components[componentType][component];\n }\n });\n\n // If this component group is now empty, delete it.\n if (!Object.keys(reduced.components[componentType]).length) {\n delete reduced.components[componentType];\n }\n });\n\n // If this path no longer has any components, delete it.\n if (!Object.keys(reduced.components).length) {\n delete reduced.components;\n }\n }\n\n // Remove any unused tags.\n if ('tags' in reduced) {\n reduced.tags.forEach((tag: TagObject, k: number) => {\n if (!usedTags.has(tag.name)) {\n delete reduced.tags[k];\n }\n });\n\n // Remove any now empty items from the tags array.\n reduced.tags = reduced.tags.filter(Boolean);\n\n if (!reduced.tags.length) {\n delete reduced.tags;\n }\n }\n\n return reduced;\n}\n"],"mappings":";;;;;AAEA,OAAO,iBAAiB;AACxB,SAAS,4BAA4B;AAgBrC,SAAS,YAAY,QAAa;AAChC,SAAO,MAAM,CAAC,aAAa,GAAG,MAAM;AACtC;AAUA,SAAS,mBAAmB,QAAiC,OAAoB,MAAiB;AAChG,MAAI;AACJ,MAAI,OAAO,SAAS;AAAU,iBAAa,YAAY,IAAI,QAAQ,KAAK,UAAU,CAAC,CAAC;AACpF,MAAI,eAAe,QAAW;AAI5B;AAAA,EACF;AAEA,cAAY,UAAU,EAAE,QAAQ,CAAC,EAAE,OAAO,QAAQ,MAAM;AAEtD,QAAI,MAAM,IAAI,OAAO,GAAG;AACtB;AAAA,IACF;AAEA,UAAM,IAAI,OAAO;AAC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AAM,gGAAgG;AAAA,IAClH;AAAA,EACF;AAGA,QAAM,QAAQ,UAAQ,mBAAmB,SAAS,OAAO,IAAI,CAAC;AAG9D,MAAI,gBAAgB,SAAS;AAC3B,WAAO,KAAK,QAAQ,UAAU,EAAE,QAAQ,CAAC,kBAA0C;AACjF,aAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ,eAAa;AAClE,YAAI,CAAC,MAAM,IAAI,gBAAgB,aAAa,IAAI,SAAS,EAAE,GAAG;AAC5D,iBAAO,QAAQ,WAAW,aAAa,EAAE,SAAS;AAAA,QACpD;AAAA,MACF,CAAC;AAGD,UAAI,CAAC,OAAO,KAAK,QAAQ,WAAW,aAAa,CAAC,EAAE,QAAQ;AAC1D,eAAO,QAAQ,WAAW,aAAa;AAAA,MACzC;AAAA,IACF,CAAC;AAGD,QAAI,CAAC,OAAO,KAAK,QAAQ,UAAU,EAAE,QAAQ;AAC3C,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAGA,MAAI,UAAU,SAAS;AACrB,YAAQ,KAAK,QAAQ,CAAC,KAAgB,MAAc;AAClD,UAAI,CAAC,SAAS,IAAI,IAAI,IAAI,GAAG;AAC3B,eAAO,QAAQ,KAAK,CAAC;AAAA,MACvB;AAAA,IACF,CAAC;AAGD,YAAQ,OAAO,QAAQ,KAAK,OAAO,OAAO;AAE1C,QAAI,CAAC,QAAQ,KAAK,QAAQ;AACxB,aAAO,QAAQ;AAAA,IACjB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oas",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "25.0.0",
|
|
4
4
|
"description": "Comprehensive tooling for working with OpenAPI definitions",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "ReadMe <support@readme.io> (https://readme.com)",
|
|
@@ -94,9 +94,9 @@
|
|
|
94
94
|
"jsonpath-plus": "^9.0.0",
|
|
95
95
|
"jsonpointer": "^5.0.0",
|
|
96
96
|
"memoizee": "^0.4.16",
|
|
97
|
-
"oas-normalize": "^11.1.
|
|
97
|
+
"oas-normalize": "^11.1.2",
|
|
98
98
|
"openapi-types": "^12.1.1",
|
|
99
|
-
"path-to-regexp": "^
|
|
99
|
+
"path-to-regexp": "^8.1.0",
|
|
100
100
|
"remove-undefined-objects": "^5.0.0"
|
|
101
101
|
},
|
|
102
102
|
"devDependencies": {
|
|
@@ -111,5 +111,5 @@
|
|
|
111
111
|
"vitest": "^1.4.0"
|
|
112
112
|
},
|
|
113
113
|
"prettier": "@readme/eslint-config/prettier",
|
|
114
|
-
"gitHead": "
|
|
114
|
+
"gitHead": "42c2a5d5696a0189c275bb70ce69513a77c53d21"
|
|
115
115
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/lib/get-auth.ts","../src/lib/get-user-variable.ts"],"sourcesContent":["import type { Extensions } from './extensions.js';\nimport type * as RMOAS from './types.js';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { Match, ParamData } from 'path-to-regexp';\n\nimport $RefParser from '@readme/json-schema-ref-parser';\nimport { pathToRegexp, match } from 'path-to-regexp';\n\nimport {\n CODE_SAMPLES,\n HEADERS,\n OAUTH_OPTIONS,\n PARAMETER_ORDERING,\n SAMPLES_LANGUAGES,\n extensionDefaults,\n getExtension,\n hasRootExtension,\n validateParameterOrdering,\n} from './extensions.js';\nimport { getAuth } from './lib/get-auth.js';\nimport getUserVariable from './lib/get-user-variable.js';\nimport { isPrimitive } from './lib/helpers.js';\nimport { Operation, Webhook } from './operation/index.js';\nimport { findSchemaDefinition, supportedMethods } from './utils.js';\n\ninterface PathMatch {\n match?: Match<ParamData>;\n operation: RMOAS.PathsObject;\n url: {\n method?: RMOAS.HttpMethods;\n nonNormalizedPath: string;\n origin: string;\n path: string;\n slugs: Record<string, string>;\n };\n}\ntype PathMatches = PathMatch[];\n\nconst SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\\]]+)}/g;\n\nfunction ensureProtocol(url: string) {\n // Add protocol to urls starting with // e.g. //example.com\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (url.match(/^\\/\\//)) {\n return `https:${url}`;\n }\n\n // Add protocol to urls with no // within them\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (!url.match(/\\/\\//)) {\n return `https://${url}`;\n }\n\n return url;\n}\n\nfunction stripTrailingSlash(url: string) {\n if (url[url.length - 1] === '/') {\n return url.slice(0, -1);\n }\n\n return url;\n}\n\n/**\n * Normalize a OpenAPI server URL by ensuring that it has a proper HTTP protocol and doesn't have a\n * trailing slash.\n *\n * @param api The API definition that we're processing.\n * @param selected The index of the `servers` array in the API definition that we want to normalize.\n */\nfunction normalizedUrl(api: RMOAS.OASDocument, selected: number) {\n const exampleDotCom = 'https://example.com';\n let url;\n try {\n url = api.servers[selected].url;\n // This is to catch the case where servers = [{}]\n if (!url) throw new Error('no url');\n\n // Stripping the '/' off the end\n url = stripTrailingSlash(url);\n\n // Check if the URL is just a path a missing an origin, for example `/api/v3`. If so, then make\n // `example.com` the origin to avoid it becoming something invalid like `https:///api/v3`.\n // RM-1044\n if (url.startsWith('/') && !url.startsWith('//')) {\n const urlWithOrigin = new URL(exampleDotCom);\n urlWithOrigin.pathname = url;\n url = urlWithOrigin.href;\n }\n } catch (e) {\n url = exampleDotCom;\n }\n\n return ensureProtocol(url);\n}\n\n/**\n * With a URL that may contain server variables, transform those server variables into regex that\n * we can query against.\n *\n * For example, when given `https://{region}.node.example.com/v14` this will return back:\n *\n * https://([-_a-zA-Z0-9:.[\\\\]]+).node.example.com/v14\n *\n * @param url URL to transform\n */\nfunction transformUrlIntoRegex(url: string) {\n return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, '([-_a-zA-Z0-9:.[\\\\]]+)'));\n}\n\n/**\n * Normalize a path so that we can use it with `path-to-regexp` to do operation lookups.\n *\n * @param path Path to normalize.\n */\nfunction normalizePath(path: string) {\n return (\n path\n // This regex transforms `{pathParam}` into `:pathParam` so we can regex against it. We're\n // also handling quirks here like if there's an optional proceeding or trailing curly bracket\n // (`{{pathParam}` or `{pathParam}}`) as any unescaped curlys, which would be present in\n // `:pathParam}`, will throw a regex exception.\n .replace(/({?){(.*?)}(}?)/g, (str, ...args) => {\n // If a path contains a path parameter with hyphens, like `:dlc-release`, when it's regexd\n // with `path-to-regexp` it match against the `:dlc` portion of the parameter, breaking all\n // matching against the full path.\n //\n // For example on `/games/:game/dlc/:dlc-release` the regex that's actually used to search\n // against a path like `/games/destiny-2/dlc/witch-queen` is the following:\n // /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))-release[\\/#\\?]?$/i\n //\n // However if `:dlc-release` is rewritten to `:dlcrelease` we end up with a functional\n // regex: /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))[\\/#\\?]?$/i.\n return `:${args[1].replace('-', '')}`;\n })\n\n // In addition to transforming `{pathParam}` into `:pathParam` we also need to escape cases\n // where a non-variabled colon is next to a variabled-colon because if we don't then\n // `path-to-regexp` won't be able to correct identify where the variable starts.\n //\n // For example if the URL is `/post/:param1::param2` we'll be escaping it to\n // `/post/:param1\\::param2`.\n .replace(/::/, '\\\\::')\n\n // We also need to escape question marks too because they're treated as regex modifiers.\n .split('?')[0]\n );\n}\n\n/**\n * Generate path matches for a given path and origin on a set of OpenAPI path objects.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathsObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject}\n * @param paths The OpenAPI Paths Object to process.\n * @param pathName Path to look for a match.\n * @param origin The origin that we're matching against.\n */\nfunction generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin: string) {\n const prunedPathName = pathName.split('?')[0];\n return Object.keys(paths)\n .map(path => {\n const cleanedPath = normalizePath(path);\n\n let matchResult: PathMatch['match'];\n try {\n const matchStatement = match(cleanedPath, { decode: decodeURIComponent });\n matchResult = matchStatement(prunedPathName);\n } catch (err) {\n // If path matching fails for whatever reason (maybe they have a malformed path parameter)\n // then we shouldn't also fail.\n return;\n }\n\n const slugs: Record<string, string> = {};\n\n if (matchResult && Object.keys(matchResult.params).length) {\n Object.keys(matchResult.params).forEach(param => {\n slugs[`:${param}`] = (matchResult.params as Record<string, string>)[param];\n });\n }\n\n // eslint-disable-next-line consistent-return\n return {\n url: {\n origin,\n path: cleanedPath.replace(/\\\\::/, '::'),\n nonNormalizedPath: path,\n slugs,\n },\n operation: paths[path],\n match: matchResult,\n };\n })\n .filter(Boolean)\n .filter(p => p.match) as PathMatches;\n}\n\n/**\n * @param pathMatches Array of path matches to filter down.\n * @param targetMethod HTTP method to look for.\n * @returns Filtered down path matches.\n */\nfunction filterPathMethods(pathMatches: PathMatches, targetMethod: RMOAS.HttpMethods) {\n const regExp = pathToRegexp(targetMethod);\n return pathMatches\n .map(p => {\n const captures = Object.keys(p.operation).filter(r => regExp.exec(r));\n\n if (captures.length) {\n const method = captures[0];\n p.url.method = method.toUpperCase() as RMOAS.HttpMethods;\n\n return {\n url: p.url,\n operation: p.operation[method],\n };\n }\n\n return false;\n })\n .filter(Boolean) as { operation: RMOAS.OperationObject; url: PathMatch['url'] }[];\n}\n\n/**\n * @param pathMatches URL and PathsObject matches to narrow down to find a target path.\n * @returns An object containing matches that were discovered in the API definition.\n */\nfunction findTargetPath(pathMatches: { operation: RMOAS.PathsObject; url: PathMatch['url'] }[]) {\n let minCount = Object.keys(pathMatches[0].url.slugs).length;\n let operation;\n\n for (let m = 0; m < pathMatches.length; m += 1) {\n const selection = pathMatches[m];\n const paramCount = Object.keys(selection.url.slugs).length;\n if (paramCount <= minCount) {\n minCount = paramCount;\n operation = selection;\n }\n }\n\n return operation;\n}\n\nexport default class Oas {\n /**\n * An OpenAPI API Definition.\n */\n api: RMOAS.OASDocument;\n\n /**\n * The current user that we should use when pulling auth tokens from security schemes.\n */\n user: RMOAS.User;\n\n /**\n * Internal storage array that the library utilizes to keep track of the times the\n * {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all\n * end up returning the same data set once the initial dereference call completed.\n */\n protected promises: {\n reject: any;\n resolve: any;\n }[];\n\n /**\n * Internal storage array that the library utilizes to keep track of its `dereferencing` state so\n * it doesn't initiate multiple dereferencing processes.\n */\n protected dereferencing: {\n circularRefs: string[];\n complete: boolean;\n processing: boolean;\n };\n\n /**\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n constructor(oas: RMOAS.OASDocument | string, user?: RMOAS.User) {\n if (typeof oas === 'string') {\n oas = JSON.parse(oas) as RMOAS.OASDocument;\n }\n // @todo throw an exception here instead of allowing an empty oas\n this.api = oas;\n this.user = user || {};\n\n this.promises = [];\n this.dereferencing = {\n processing: false,\n complete: false,\n circularRefs: [],\n };\n }\n\n /**\n * This will initialize a new instance of the `Oas` class. This method is useful if you're using\n * Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type\n * that object to an `OASDocument` for you.\n *\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n static init(oas: Record<string, unknown> | RMOAS.OASDocument, user?: RMOAS.User) {\n return new Oas(oas as RMOAS.OASDocument, user);\n }\n\n /**\n * Retrieve the OpenAPI version that this API definition is targeted for.\n */\n getVersion() {\n if (this.api.openapi) {\n return this.api.openapi;\n }\n\n throw new Error('Unable to recognize what specification version this API definition conforms to.');\n }\n\n /**\n * Retrieve the current OpenAPI API Definition.\n *\n */\n getDefinition() {\n return this.api;\n }\n\n url(selected = 0, variables?: RMOAS.ServerVariable) {\n const url = normalizedUrl(this.api, selected);\n return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();\n }\n\n variables(selected = 0) {\n let variables;\n try {\n variables = this.api.servers[selected].variables;\n if (!variables) throw new Error('no variables');\n } catch (e) {\n variables = {};\n }\n\n return variables;\n }\n\n defaultVariables(selected = 0) {\n const variables = this.variables(selected);\n const defaults: RMOAS.ServerVariable = {};\n\n Object.keys(variables).forEach(key => {\n defaults[key] = getUserVariable(this.user, key) || variables[key].default || '';\n });\n\n return defaults;\n }\n\n splitUrl(selected = 0): (\n | {\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'text';\n value: string;\n }\n | {\n /**\n * An optional description for the server variable.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n description?: string;\n\n /**\n * An enumeration of string values to be used if the substitution options are from a limited set.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n enum?: string[];\n\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'variable';\n value: string;\n }\n )[] {\n const url = normalizedUrl(this.api, selected);\n const variables = this.variables(selected);\n\n return url\n .split(/({.+?})/)\n .filter(Boolean)\n .map((part, i) => {\n const isVariable = part.match(/[{}]/);\n const value = part.replace(/[{}]/g, '');\n // To ensure unique keys, we're going to create a key\n // with the value concatenated to its index.\n const key = `${value}-${i}`;\n\n if (!isVariable) {\n return {\n type: 'text',\n value,\n key,\n };\n }\n\n const variable = variables?.[value];\n\n return {\n type: 'variable',\n value,\n key,\n description: variable?.description,\n enum: variable?.enum,\n };\n });\n }\n\n /**\n * With a fully composed server URL, run through our list of known OAS servers and return back\n * which server URL was selected along with any contained server variables split out.\n *\n * For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,\n * and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the\n * following:\n *\n * { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }\n *\n * Re-supplying this data to `oas.url()` should return the same URL you passed into this method.\n *\n * @param baseUrl A given URL to extract server variables out of.\n */\n splitVariables(baseUrl: string) {\n const matchedServer = (this.api.servers || [])\n .map((server, i) => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(baseUrl);\n if (!found) {\n return false;\n }\n\n // While it'd be nice to use named regex groups to extract path parameters from the URL and\n // match them up with the variables that we have present in it, JS unfortunately doesn't\n // support having the groups duplicated. So instead of doing that we need to re-regex the\n // server URL, this time splitting on the path parameters -- this way we'll be able to\n // extract the parameter names and match them up with the matched server that we obtained\n // above.\n const variables: Record<string, number | string> = {};\n Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {\n variables[variable[1]] = found[y + 1];\n });\n\n return {\n selected: i,\n variables,\n };\n })\n .filter(Boolean);\n\n return matchedServer.length ? matchedServer[0] : false;\n }\n\n /**\n * Replace templated variables with supplied data in a given URL.\n *\n * There are a couple ways that this will utilize variable data:\n *\n * - Supplying a `variables` object. If this is supplied, this data will always take priority.\n * This incoming `variables` object can be two formats:\n * `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is\n * present, that will take precedence over the latter.\n * - If the supplied `variables` object is empty or does not match the current template name,\n * we fallback to the data stored in `this.user` and attempt to match against that.\n * See `getUserVariable` for some more information on how this data is pulled from `this.user`.\n *\n * If no variables supplied match up with the template name, the template name will instead be\n * used as the variable data.\n *\n * @param url A URL to swap variables into.\n * @param variables An object containing variables to swap into the URL.\n */\n replaceUrl(url: string, variables: RMOAS.ServerVariable = {}) {\n // When we're constructing URLs, server URLs with trailing slashes cause problems with doing\n // lookups, so if we have one here on, slice it off.\n return stripTrailingSlash(\n url.replace(SERVER_VARIABLE_REGEX, (original: string, key: string) => {\n if (key in variables) {\n const data = variables[key];\n if (typeof data === 'object') {\n if (!Array.isArray(data) && data !== null && 'default' in data) {\n return data.default as string;\n }\n } else {\n return data as string;\n }\n }\n\n const userVariable = getUserVariable(this.user, key);\n if (userVariable) {\n return userVariable as string;\n }\n\n return original;\n }),\n );\n }\n\n /**\n * Retrieve an Operation of Webhook class instance for a given path and method.\n *\n * @param path Path to lookup and retrieve.\n * @param method HTTP Method to retrieve on the path.\n */\n operation(\n path: string,\n method: RMOAS.HttpMethods,\n opts: {\n /**\n * If you prefer to first look for a webhook with this path and method.\n */\n isWebhook?: boolean;\n } = {},\n ) {\n // If we're unable to locate an operation for this path+method combination within the API\n // definition, we should still set an empty schema on the operation in the `Operation` class\n // because if we don't trying to use any of the accessors on that class are going to fail as\n // `schema` will be `undefined`.\n let operation: RMOAS.OperationObject = {\n parameters: [],\n };\n\n if (opts.isWebhook) {\n const api = this.api as OpenAPIV3_1.Document;\n // Typecasting this to a `PathsObject` because we don't have `$ref` pointers here.\n if ((api?.webhooks[path] as RMOAS.PathsObject)?.[method]) {\n operation = (api.webhooks[path] as RMOAS.PathsObject)[method] as RMOAS.OperationObject;\n return new Webhook(api, path, method, operation);\n }\n }\n\n if (this?.api?.paths?.[path]?.[method]) {\n operation = this.api.paths[path][method];\n }\n\n return new Operation(this.api, path, method, operation);\n }\n\n findOperationMatches(url: string): PathMatches {\n const { origin, hostname } = new URL(url);\n const originRegExp = new RegExp(origin, 'i');\n const { servers, paths } = this.api;\n\n let pathName;\n let targetServer;\n let matchedServer;\n\n if (!servers || !servers.length) {\n // If this API definition doesn't have any servers set up let's treat it as if it were\n // https://example.com because that's the default origin we add in `normalizedUrl` under the\n // same circumstances. Without this we won't be able to match paths within what is otherwise\n // a valid OpenAPI definition.\n matchedServer = {\n url: 'https://example.com',\n };\n } else {\n matchedServer = servers.find(s => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n if (!matchedServer) {\n const hostnameRegExp = new RegExp(hostname);\n matchedServer = servers.find(s => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n }\n }\n\n // If we **still** haven't found a matching server, then the OAS server URL might have server\n // variables and we should loosen it up with regex to try to discover a matching path.\n //\n // For example if an OAS has `https://{region}.node.example.com/v14` set as its server URL, and\n // the `this.user` object has a `region` value of `us`, if we're trying to locate an operation\n // for https://eu.node.example.com/v14/api/esm we won't be able to because normally the users\n // `region` of `us` will be transposed in and we'll be trying to locate `eu.node.example.com`\n // in `us.node.example.com` -- which won't work.\n //\n // So what this does is transform `https://{region}.node.example.com/v14` into\n // `https://([-_a-zA-Z0-9[\\\\]]+).node.example.com/v14`, and from there we'll be able to match\n // https://eu.node.example.com/v14/api/esm and ultimately find the operation matches for\n // `/api/esm`.\n if (!matchedServer) {\n const matchedServerAndPath = servers\n .map(server => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(url);\n if (!found) {\n return undefined;\n }\n\n return {\n matchedServer: server,\n pathName: url.split(new RegExp(rgx)).slice(-1).pop(),\n };\n })\n .filter(Boolean);\n\n if (!matchedServerAndPath.length) {\n return undefined;\n }\n\n pathName = matchedServerAndPath[0].pathName;\n targetServer = {\n ...matchedServerAndPath[0].matchedServer,\n };\n } else {\n // Instead of setting `url` directly against `matchedServer` we need to set it to an\n // intermediary object as directly modifying `matchedServer.url` will in turn update\n // `this.servers[idx].url` which we absolutely do not want to happen.\n targetServer = {\n ...matchedServer,\n url: this.replaceUrl(matchedServer.url, matchedServer.variables || {}),\n };\n\n [, pathName] = url.split(new RegExp(targetServer.url, 'i'));\n }\n\n if (pathName === undefined) return undefined;\n if (pathName === '') pathName = '/';\n const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);\n if (!annotatedPaths.length) return undefined;\n\n return annotatedPaths;\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object\n * containing a `url` object and another one for `operation`. This differs from `getOperation()`\n * in that it does not return an instance of the `Operation` class.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n findOperation(url: string, method: RMOAS.HttpMethods): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n\n const matches = filterPathMethods(annotatedPaths, method) as {\n operation: RMOAS.PathsObject;\n url: PathMatch['url']; // @fixme this should actually be an `OperationObject`.\n }[];\n if (!matches.length) return undefined;\n return findTargetPath(matches);\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an\n * object containing a `url` object and another one for `operation`.\n *\n * @param url A full URL to look up.\n */\n findOperationWithoutMethod(url: string): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n return findTargetPath(annotatedPaths);\n }\n\n /**\n * Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from\n * `findOperation` in that while this method will return an `Operation` instance,\n * `findOperation()` does not.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n getOperation(url: string, method: RMOAS.HttpMethods) {\n const op = this.findOperation(url, method);\n if (op === undefined) {\n return undefined;\n }\n\n return this.operation(op.url.nonNormalizedPath, method);\n }\n\n /**\n * Retrieve an operation in an OAS by an `operationId`.\n *\n * If an operation does not have an `operationId` one will be generated in place, using the\n * default behavior of `Operation.getOperationId()`, and then asserted against your query.\n *\n * Note that because `operationId`s are unique that uniqueness does include casing so the ID\n * you are looking for will be asserted as an exact match.\n *\n * @see {Operation.getOperationId()}\n * @param id The `operationId` to look up.\n */\n getOperationById(id: string) {\n let found: Operation | Webhook;\n\n Object.values(this.getPaths()).forEach(operations => {\n if (found) return;\n found = Object.values(operations).find(operation => operation.getOperationId() === id);\n });\n\n if (found) {\n return found;\n }\n\n Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {\n if (found) return;\n found = Object.values(webhooks).find(webhook => webhook.getOperationId() === id);\n });\n\n return found;\n }\n\n /**\n * With an object of user information, retrieve the appropriate API auth keys from the current\n * OAS definition.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\n getAuth(user: RMOAS.User, selectedApp?: number | string) {\n if (!this.api?.components?.securitySchemes) {\n return {};\n }\n\n return getAuth(this.api, user, selectedApp);\n }\n\n /**\n * Returns the `paths` object that exists in this API definition but with every `method` mapped\n * to an instance of the `Operation` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getPaths() {\n /**\n * Because a path doesn't need to contain a keyed-object of HTTP methods, we should exclude\n * anything from within the paths object that isn't a known HTTP method.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#fixed-fields-7}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-7}\n */\n const paths: Record<string, Record<RMOAS.HttpMethods, Operation | Webhook>> = {};\n\n Object.keys(this.api.paths ? this.api.paths : []).forEach(path => {\n // If this is a specification extension then we should ignore it.\n if (path.startsWith('x-')) {\n return;\n }\n\n paths[path] = {} as Record<RMOAS.HttpMethods, Operation | Webhook>;\n\n // Though this library is generally unaware of `$ref` pointers we're making a singular\n // exception with this accessor out of convenience.\n if ('$ref' in this.api.paths[path]) {\n this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);\n }\n\n Object.keys(this.api.paths[path]).forEach((method: RMOAS.HttpMethods) => {\n if (!supportedMethods.has(method)) return;\n\n paths[path][method] = this.operation(path, method);\n });\n });\n\n return paths;\n }\n\n /**\n * Returns the `webhooks` object that exists in this API definition but with every `method`\n * mapped to an instance of the `Webhook` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getWebhooks() {\n const webhooks: Record<string, Record<RMOAS.HttpMethods, Webhook>> = {};\n const api = this.api as OpenAPIV3_1.Document;\n\n Object.keys(api.webhooks ? api.webhooks : []).forEach(id => {\n webhooks[id] = {} as Record<RMOAS.HttpMethods, Webhook>;\n Object.keys(api.webhooks[id]).forEach((method: RMOAS.HttpMethods) => {\n webhooks[id][method] = this.operation(id, method, { isWebhook: true }) as Webhook;\n });\n });\n\n return webhooks;\n }\n\n /**\n * Return an array of all tag names that exist on this API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n * @param setIfMissing If a tag is not present on an operation that operations path will be added\n * into the list of tags returned.\n */\n getTags(setIfMissing = false) {\n const allTags = new Set<string>();\n\n const oasTags =\n this.api.tags?.map(tag => {\n return tag.name;\n }) || [];\n\n const disableTagSorting = getExtension('disable-tag-sorting', this.api);\n\n Object.entries(this.getPaths()).forEach(([path, operations]) => {\n Object.values(operations).forEach(operation => {\n const tags = operation.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {\n Object.values(webhooks).forEach(webhook => {\n const tags = webhook.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n // Tags that exist only on the endpoint\n const endpointTags: string[] = [];\n // Tags that the user has defined in the `tags` array\n const tagsArray: string[] = [];\n\n // Distinguish between which tags exist in the `tags` array and which tags\n // exist only at the endpoint level. For tags that exist only at the\n // endpoint level, we'll just tack that on to the end of the sorted tags.\n if (disableTagSorting) {\n return Array.from(allTags);\n }\n\n Array.from(allTags).forEach(tag => {\n if (oasTags.includes(tag)) {\n tagsArray.push(tag);\n } else {\n endpointTags.push(tag);\n }\n });\n\n let sortedTags = tagsArray.sort((a, b) => {\n return oasTags.indexOf(a) - oasTags.indexOf(b);\n });\n\n sortedTags = sortedTags.concat(endpointTags);\n\n return sortedTags;\n }\n\n /**\n * Determine if a given a custom specification extension exists within the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n hasExtension(extension: string) {\n return hasRootExtension(extension, this.api);\n }\n\n /**\n * Retrieve a custom specification extension off of the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n getExtension(extension: string | keyof Extensions, operation?: Operation) {\n return getExtension(extension, this.api, operation);\n }\n\n /**\n * Determine if a given OpenAPI custom extension is valid or not.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to validate.\n * @throws\n */\n validateExtension(extension: keyof Extensions) {\n if (this.hasExtension('x-readme')) {\n const data = this.getExtension('x-readme') as Extensions;\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n throw new TypeError('\"x-readme\" must be of type \"Object\"');\n }\n\n if (extension in data) {\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data[extension])) {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data[extension], `x-readme.${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data[extension] !== 'object') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data[extension] !== 'boolean') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n // If the extension isn't grouped under `x-readme`, we need to look for them with `x-` prefixes.\n if (this.hasExtension(`x-${extension}`)) {\n const data = this.getExtension(`x-${extension}`);\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data)) {\n throw new TypeError(`\"x-${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data, `x-${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data !== 'object') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data !== 'boolean') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n /**\n * Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n */\n validateExtensions() {\n Object.keys(extensionDefaults).forEach((extension: keyof Extensions) => {\n this.validateExtension(extension);\n });\n }\n\n /**\n * Retrieve any circular `$ref` pointers that maybe present within the API definition.\n *\n * This method requires that you first dereference the definition.\n *\n * @see Oas.dereference\n */\n getCircularReferences() {\n if (!this.dereferencing.complete) {\n throw new Error('#dereference() must be called first in order for this method to obtain circular references.');\n }\n\n return this.dereferencing.circularRefs;\n }\n\n /**\n * Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas\n * and circular structures.\n *\n */\n async dereference(\n opts: {\n /**\n * A callback method can be supplied to be called when dereferencing is complete. Used for\n * debugging that the multi-promise handling within this method works.\n *\n * @private\n */\n cb?: () => void;\n\n /**\n * Preserve component schema names within themselves as a `title`.\n */\n preserveRefAsJSONSchemaTitle?: boolean;\n } = { preserveRefAsJSONSchemaTitle: false },\n ) {\n if (this.dereferencing.complete) {\n return new Promise(resolve => {\n resolve(true);\n });\n }\n\n if (this.dereferencing.processing) {\n return new Promise((resolve, reject) => {\n this.promises.push({ resolve, reject });\n });\n }\n\n this.dereferencing.processing = true;\n\n const { api, promises } = this;\n\n // Because referencing will eliminate any lineage back to the original `$ref`, information that\n // we might need at some point, we should run through all available component schemas and denote\n // what their name is so that when dereferencing happens below those names will be preserved.\n if (api && api.components && api.components.schemas && typeof api.components.schemas === 'object') {\n Object.keys(api.components.schemas).forEach(schemaName => {\n // As of OpenAPI 3.1 component schemas can be primitives or arrays. If this happens then we\n // shouldn't try to add `title` or `x-readme-ref-name` properties because we can't. We'll\n // have some data loss on these schemas but as they aren't objects they likely won't be used\n // in ways that would require needing a `title` or `x-readme-ref-name` anyways.\n if (\n isPrimitive(api.components.schemas[schemaName]) ||\n Array.isArray(api.components.schemas[schemaName]) ||\n api.components.schemas[schemaName] === null\n ) {\n return;\n }\n\n if (opts.preserveRefAsJSONSchemaTitle) {\n // This may result in some data loss if there's already a `title` present, but in the case\n // where we want to generate code for the API definition (see http://npm.im/api), we'd\n // prefer to retain original reference name as a title for any generated types.\n (api.components.schemas[schemaName] as RMOAS.SchemaObject).title = schemaName;\n }\n\n (api.components.schemas[schemaName] as RMOAS.SchemaObject)['x-readme-ref-name'] = schemaName;\n });\n }\n\n const parser = new $RefParser();\n\n return parser\n .dereference(api || {}, {\n resolve: {\n // We shouldn't be resolving external pointers at this point so just ignore them.\n external: false,\n },\n dereference: {\n // If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise\n // `$ref‘ just won't exist. This allows us to do easy circular reference detection.\n circular: 'ignore',\n },\n })\n .then((dereferenced: RMOAS.OASDocument) => {\n let circularRefs: string[] = [];\n if (parser.$refs.circular) {\n circularRefs = parser.$refs.circularRefs.map(pointer => {\n // The circular $refs that are coming out of `json-schema-ref-parser` are prefixed\n // with the schema path (file path, url, whatever) that the schema exists in. Because\n // we don't care about this information for this reporting mechanism, and only the\n // $ref pointer, we're removing it.\n return `#${pointer.split('#')[1]}`;\n });\n }\n\n this.api = dereferenced;\n\n this.promises = promises;\n this.dereferencing = {\n processing: false,\n complete: true,\n circularRefs,\n };\n\n // Used for debugging that dereferencing promise awaiting works.\n if (opts.cb) {\n opts.cb();\n }\n })\n .then(() => {\n return this.promises.map(deferred => deferred.resolve());\n });\n }\n}\n","import type * as RMOAS from '../types.js';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\ntype authKey = unknown | { password: number | string; user: number | string } | null;\n\n/**\n * @param user User to retrieve retrieve an auth key for.\n * @param scheme The type of security scheme that we want a key for.\n */\nfunction getKey(user: RMOAS.User, scheme: RMOAS.KeyedSecuritySchemeObject): authKey {\n switch (scheme.type) {\n case 'oauth2':\n case 'apiKey':\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n\n case 'http':\n if (scheme.scheme === 'basic') {\n return user[scheme._key] || { user: user.user || null, pass: user.pass || null };\n }\n\n if (scheme.scheme === 'bearer') {\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n }\n return null;\n\n default:\n return null;\n }\n}\n\n/**\n * Retrieve auth keys for a specific security scheme for a given user for a specific \"app\" that\n * they have configured.\n *\n * For `scheme` we're typing it to a union of `SecurityScheme` and `any` because we have handling\n * and tests for an unknown or unrecognized `type` and though it's not possible with the\n * `SecurityScheme.type` to be unrecognized it may still be possible to get an unrecognized scheme\n * with this method in the wild as we have API definitions in our database that were ingested\n * before we had good validation in place.\n *\n * @param user User\n * @param scheme Security scheme to get auth keys for.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getByScheme(\n user: RMOAS.User,\n scheme = <RMOAS.KeyedSecuritySchemeObject>{},\n selectedApp?: number | string,\n): authKey {\n if (user?.keys && user.keys.length) {\n if (selectedApp) {\n return getKey(\n user.keys.find(key => key.name === selectedApp),\n scheme,\n );\n }\n\n return getKey(user.keys[0], scheme);\n }\n\n return getKey(user, scheme);\n}\n\n/**\n * Retrieve auth keys for an API definition from a given user for a specific \"app\" that they have\n * configured.\n *\n * @param api API definition\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getAuth(\n api: OpenAPIV3_1.Document | OpenAPIV3.Document,\n user: RMOAS.User,\n selectedApp?: number | string,\n) {\n return Object.keys(api?.components?.securitySchemes || {})\n .map(scheme => {\n return {\n [scheme]: getByScheme(\n user,\n {\n // This sucks but since we dereference we'll never have a `$ref` pointer here with a\n // `ReferenceObject` type.\n ...(api.components.securitySchemes[scheme] as RMOAS.SecuritySchemeObject),\n _key: scheme,\n },\n selectedApp,\n ),\n };\n })\n .reduce((prev, next) => Object.assign(prev, next), {});\n}\n","import type * as RMOAS from '../types.js';\n\n/**\n * Retrieve a user variable off of a given user.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user The user to get a user variable for.\n * @param property The name of the variable to retrieve.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport default function getUserVariable(user: RMOAS.User, property: string, selectedApp?: number | string) {\n let key = user;\n\n if ('keys' in user && Array.isArray(user.keys) && user.keys.length) {\n if (selectedApp) {\n key = user.keys.find(k => k.name === selectedApp);\n } else {\n key = user.keys[0];\n }\n }\n\n return key[property] || user[property] || null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAKA,OAAO,gBAAgB;AACvB,SAAS,cAAc,aAAa;;;ACGpC,SAAS,OAAO,MAAkB,QAAkD;AAClF,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,KAAK,OAAO,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,KAAK;AAAA,IAEpE,KAAK;AACH,UAAI,OAAO,WAAW,SAAS;AAC7B,eAAO,KAAK,OAAO,IAAI,KAAK,EAAE,MAAM,KAAK,QAAQ,MAAM,MAAM,KAAK,QAAQ,KAAK;AAAA,MACjF;AAEA,UAAI,OAAO,WAAW,UAAU;AAC9B,eAAO,KAAK,OAAO,IAAI,KAAK,KAAK,UAAU,OAAO,WAAW,KAAK;AAAA,MACpE;AACA,aAAO;AAAA,IAET;AACE,aAAO;AAAA,EACX;AACF;AAgBO,SAAS,YACd,MACA,SAA0C,CAAC,GAC3C,aACS;AACT,MAAI,MAAM,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AAChB,WAAK,gBAAgB;AAAA,QACnB,YAAY;AAAA,QACZ,UAAU;AAAA,QACV;AAAA,MACF;AAGA,UAAI,KAAK,IAAI;AACX,aAAK,GAAG;AAAA,MACV;AAAA,IACF,CAAC,EACA,KAAK,MAAM;AACV,aAAO,KAAK,SAAS,IAAI,cAAY,SAAS,QAAQ,CAAC;AAAA,IACzD,CAAC;AAAA,EACL;AACF","sourcesContent":["import type { Extensions } from './extensions.js';\nimport type * as RMOAS from './types.js';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { Match, ParamData } from 'path-to-regexp';\n\nimport $RefParser from '@readme/json-schema-ref-parser';\nimport { pathToRegexp, match } from 'path-to-regexp';\n\nimport {\n CODE_SAMPLES,\n HEADERS,\n OAUTH_OPTIONS,\n PARAMETER_ORDERING,\n SAMPLES_LANGUAGES,\n extensionDefaults,\n getExtension,\n hasRootExtension,\n validateParameterOrdering,\n} from './extensions.js';\nimport { getAuth } from './lib/get-auth.js';\nimport getUserVariable from './lib/get-user-variable.js';\nimport { isPrimitive } from './lib/helpers.js';\nimport { Operation, Webhook } from './operation/index.js';\nimport { findSchemaDefinition, supportedMethods } from './utils.js';\n\ninterface PathMatch {\n match?: Match<ParamData>;\n operation: RMOAS.PathsObject;\n url: {\n method?: RMOAS.HttpMethods;\n nonNormalizedPath: string;\n origin: string;\n path: string;\n slugs: Record<string, string>;\n };\n}\ntype PathMatches = PathMatch[];\n\nconst SERVER_VARIABLE_REGEX = /{([-_a-zA-Z0-9:.[\\]]+)}/g;\n\nfunction ensureProtocol(url: string) {\n // Add protocol to urls starting with // e.g. //example.com\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (url.match(/^\\/\\//)) {\n return `https:${url}`;\n }\n\n // Add protocol to urls with no // within them\n // This is because httpsnippet throws a HARError when it doesnt have a protocol\n if (!url.match(/\\/\\//)) {\n return `https://${url}`;\n }\n\n return url;\n}\n\nfunction stripTrailingSlash(url: string) {\n if (url[url.length - 1] === '/') {\n return url.slice(0, -1);\n }\n\n return url;\n}\n\n/**\n * Normalize a OpenAPI server URL by ensuring that it has a proper HTTP protocol and doesn't have a\n * trailing slash.\n *\n * @param api The API definition that we're processing.\n * @param selected The index of the `servers` array in the API definition that we want to normalize.\n */\nfunction normalizedUrl(api: RMOAS.OASDocument, selected: number) {\n const exampleDotCom = 'https://example.com';\n let url;\n try {\n url = api.servers[selected].url;\n // This is to catch the case where servers = [{}]\n if (!url) throw new Error('no url');\n\n // Stripping the '/' off the end\n url = stripTrailingSlash(url);\n\n // Check if the URL is just a path a missing an origin, for example `/api/v3`. If so, then make\n // `example.com` the origin to avoid it becoming something invalid like `https:///api/v3`.\n // RM-1044\n if (url.startsWith('/') && !url.startsWith('//')) {\n const urlWithOrigin = new URL(exampleDotCom);\n urlWithOrigin.pathname = url;\n url = urlWithOrigin.href;\n }\n } catch (e) {\n url = exampleDotCom;\n }\n\n return ensureProtocol(url);\n}\n\n/**\n * With a URL that may contain server variables, transform those server variables into regex that\n * we can query against.\n *\n * For example, when given `https://{region}.node.example.com/v14` this will return back:\n *\n * https://([-_a-zA-Z0-9:.[\\\\]]+).node.example.com/v14\n *\n * @param url URL to transform\n */\nfunction transformUrlIntoRegex(url: string) {\n return stripTrailingSlash(url.replace(SERVER_VARIABLE_REGEX, '([-_a-zA-Z0-9:.[\\\\]]+)'));\n}\n\n/**\n * Normalize a path so that we can use it with `path-to-regexp` to do operation lookups.\n *\n * @param path Path to normalize.\n */\nfunction normalizePath(path: string) {\n return (\n path\n // This regex transforms `{pathParam}` into `:pathParam` so we can regex against it. We're\n // also handling quirks here like if there's an optional proceeding or trailing curly bracket\n // (`{{pathParam}` or `{pathParam}}`) as any unescaped curlys, which would be present in\n // `:pathParam}`, will throw a regex exception.\n .replace(/({?){(.*?)}(}?)/g, (str, ...args) => {\n // If a path contains a path parameter with hyphens, like `:dlc-release`, when it's regexd\n // with `path-to-regexp` it match against the `:dlc` portion of the parameter, breaking all\n // matching against the full path.\n //\n // For example on `/games/:game/dlc/:dlc-release` the regex that's actually used to search\n // against a path like `/games/destiny-2/dlc/witch-queen` is the following:\n // /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))-release[\\/#\\?]?$/i\n //\n // However if `:dlc-release` is rewritten to `:dlcrelease` we end up with a functional\n // regex: /^\\/games(?:\\/([^\\/#\\?]+?))\\/dlc(?:\\/([^\\/#\\?]+?))[\\/#\\?]?$/i.\n return `:${args[1].replace('-', '')}`;\n })\n\n // In addition to transforming `{pathParam}` into `:pathParam` we also need to escape cases\n // where a non-variabled colon is next to a variabled-colon because if we don't then\n // `path-to-regexp` won't be able to correct identify where the variable starts.\n //\n // For example if the URL is `/post/:param1::param2` we'll be escaping it to\n // `/post/:param1\\::param2`.\n .replace(/::/, '\\\\::')\n\n // We also need to escape question marks too because they're treated as regex modifiers.\n .split('?')[0]\n );\n}\n\n/**\n * Generate path matches for a given path and origin on a set of OpenAPI path objects.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#pathsObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#pathsObject}\n * @param paths The OpenAPI Paths Object to process.\n * @param pathName Path to look for a match.\n * @param origin The origin that we're matching against.\n */\nfunction generatePathMatches(paths: RMOAS.PathsObject, pathName: string, origin: string) {\n const prunedPathName = pathName.split('?')[0];\n return Object.keys(paths)\n .map(path => {\n const cleanedPath = normalizePath(path);\n\n let matchResult: PathMatch['match'];\n try {\n const matchStatement = match(cleanedPath, { decode: decodeURIComponent });\n matchResult = matchStatement(prunedPathName);\n } catch (err) {\n // If path matching fails for whatever reason (maybe they have a malformed path parameter)\n // then we shouldn't also fail.\n return;\n }\n\n const slugs: Record<string, string> = {};\n\n if (matchResult && Object.keys(matchResult.params).length) {\n Object.keys(matchResult.params).forEach(param => {\n slugs[`:${param}`] = (matchResult.params as Record<string, string>)[param];\n });\n }\n\n // eslint-disable-next-line consistent-return\n return {\n url: {\n origin,\n path: cleanedPath.replace(/\\\\::/, '::'),\n nonNormalizedPath: path,\n slugs,\n },\n operation: paths[path],\n match: matchResult,\n };\n })\n .filter(Boolean)\n .filter(p => p.match) as PathMatches;\n}\n\n/**\n * @param pathMatches Array of path matches to filter down.\n * @param targetMethod HTTP method to look for.\n * @returns Filtered down path matches.\n */\nfunction filterPathMethods(pathMatches: PathMatches, targetMethod: RMOAS.HttpMethods) {\n const regExp = pathToRegexp(targetMethod);\n return pathMatches\n .map(p => {\n const captures = Object.keys(p.operation).filter(r => regExp.exec(r));\n\n if (captures.length) {\n const method = captures[0];\n p.url.method = method.toUpperCase() as RMOAS.HttpMethods;\n\n return {\n url: p.url,\n operation: p.operation[method],\n };\n }\n\n return false;\n })\n .filter(Boolean) as { operation: RMOAS.OperationObject; url: PathMatch['url'] }[];\n}\n\n/**\n * @param pathMatches URL and PathsObject matches to narrow down to find a target path.\n * @returns An object containing matches that were discovered in the API definition.\n */\nfunction findTargetPath(pathMatches: { operation: RMOAS.PathsObject; url: PathMatch['url'] }[]) {\n let minCount = Object.keys(pathMatches[0].url.slugs).length;\n let operation;\n\n for (let m = 0; m < pathMatches.length; m += 1) {\n const selection = pathMatches[m];\n const paramCount = Object.keys(selection.url.slugs).length;\n if (paramCount <= minCount) {\n minCount = paramCount;\n operation = selection;\n }\n }\n\n return operation;\n}\n\nexport default class Oas {\n /**\n * An OpenAPI API Definition.\n */\n api: RMOAS.OASDocument;\n\n /**\n * The current user that we should use when pulling auth tokens from security schemes.\n */\n user: RMOAS.User;\n\n /**\n * Internal storage array that the library utilizes to keep track of the times the\n * {@see Oas.dereference} has been called so that if you initiate multiple promises they'll all\n * end up returning the same data set once the initial dereference call completed.\n */\n protected promises: {\n reject: any;\n resolve: any;\n }[];\n\n /**\n * Internal storage array that the library utilizes to keep track of its `dereferencing` state so\n * it doesn't initiate multiple dereferencing processes.\n */\n protected dereferencing: {\n circularRefs: string[];\n complete: boolean;\n processing: boolean;\n };\n\n /**\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n constructor(oas: RMOAS.OASDocument | string, user?: RMOAS.User) {\n if (typeof oas === 'string') {\n oas = JSON.parse(oas) as RMOAS.OASDocument;\n }\n // @todo throw an exception here instead of allowing an empty oas\n this.api = oas;\n this.user = user || {};\n\n this.promises = [];\n this.dereferencing = {\n processing: false,\n complete: false,\n circularRefs: [],\n };\n }\n\n /**\n * This will initialize a new instance of the `Oas` class. This method is useful if you're using\n * Typescript and are attempting to supply an untyped JSON object into `Oas` as it will force-type\n * that object to an `OASDocument` for you.\n *\n * @param oas An OpenAPI definition.\n * @param user The information about a user that we should use when pulling auth tokens from\n * security schemes.\n */\n static init(oas: Record<string, unknown> | RMOAS.OASDocument, user?: RMOAS.User) {\n return new Oas(oas as RMOAS.OASDocument, user);\n }\n\n /**\n * Retrieve the OpenAPI version that this API definition is targeted for.\n */\n getVersion() {\n if (this.api.openapi) {\n return this.api.openapi;\n }\n\n throw new Error('Unable to recognize what specification version this API definition conforms to.');\n }\n\n /**\n * Retrieve the current OpenAPI API Definition.\n *\n */\n getDefinition() {\n return this.api;\n }\n\n url(selected = 0, variables?: RMOAS.ServerVariable) {\n const url = normalizedUrl(this.api, selected);\n return this.replaceUrl(url, variables || this.defaultVariables(selected)).trim();\n }\n\n variables(selected = 0) {\n let variables;\n try {\n variables = this.api.servers[selected].variables;\n if (!variables) throw new Error('no variables');\n } catch (e) {\n variables = {};\n }\n\n return variables;\n }\n\n defaultVariables(selected = 0) {\n const variables = this.variables(selected);\n const defaults: RMOAS.ServerVariable = {};\n\n Object.keys(variables).forEach(key => {\n defaults[key] = getUserVariable(this.user, key) || variables[key].default || '';\n });\n\n return defaults;\n }\n\n splitUrl(selected = 0): (\n | {\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'text';\n value: string;\n }\n | {\n /**\n * An optional description for the server variable.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n description?: string;\n\n /**\n * An enumeration of string values to be used if the substitution options are from a limited set.\n *\n * @see {@link https://spec.openapis.org/oas/v3.1.0#fixed-fields-4}\n */\n enum?: string[];\n\n /**\n * A unique key, where the `value` is concatenated to its index\n */\n key: string;\n type: 'variable';\n value: string;\n }\n )[] {\n const url = normalizedUrl(this.api, selected);\n const variables = this.variables(selected);\n\n return url\n .split(/({.+?})/)\n .filter(Boolean)\n .map((part, i) => {\n const isVariable = part.match(/[{}]/);\n const value = part.replace(/[{}]/g, '');\n // To ensure unique keys, we're going to create a key\n // with the value concatenated to its index.\n const key = `${value}-${i}`;\n\n if (!isVariable) {\n return {\n type: 'text',\n value,\n key,\n };\n }\n\n const variable = variables?.[value];\n\n return {\n type: 'variable',\n value,\n key,\n description: variable?.description,\n enum: variable?.enum,\n };\n });\n }\n\n /**\n * With a fully composed server URL, run through our list of known OAS servers and return back\n * which server URL was selected along with any contained server variables split out.\n *\n * For example, if you have an OAS server URL of `https://{name}.example.com:{port}/{basePath}`,\n * and pass in `https://buster.example.com:3000/pet` to this function, you'll get back the\n * following:\n *\n * { selected: 0, variables: { name: 'buster', port: 3000, basePath: 'pet' } }\n *\n * Re-supplying this data to `oas.url()` should return the same URL you passed into this method.\n *\n * @param baseUrl A given URL to extract server variables out of.\n */\n splitVariables(baseUrl: string) {\n const matchedServer = (this.api.servers || [])\n .map((server, i) => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(baseUrl);\n if (!found) {\n return false;\n }\n\n // While it'd be nice to use named regex groups to extract path parameters from the URL and\n // match them up with the variables that we have present in it, JS unfortunately doesn't\n // support having the groups duplicated. So instead of doing that we need to re-regex the\n // server URL, this time splitting on the path parameters -- this way we'll be able to\n // extract the parameter names and match them up with the matched server that we obtained\n // above.\n const variables: Record<string, number | string> = {};\n Array.from(server.url.matchAll(SERVER_VARIABLE_REGEX)).forEach((variable, y) => {\n variables[variable[1]] = found[y + 1];\n });\n\n return {\n selected: i,\n variables,\n };\n })\n .filter(Boolean);\n\n return matchedServer.length ? matchedServer[0] : false;\n }\n\n /**\n * Replace templated variables with supplied data in a given URL.\n *\n * There are a couple ways that this will utilize variable data:\n *\n * - Supplying a `variables` object. If this is supplied, this data will always take priority.\n * This incoming `variables` object can be two formats:\n * `{ variableName: { default: 'value' } }` and `{ variableName: 'value' }`. If the former is\n * present, that will take precedence over the latter.\n * - If the supplied `variables` object is empty or does not match the current template name,\n * we fallback to the data stored in `this.user` and attempt to match against that.\n * See `getUserVariable` for some more information on how this data is pulled from `this.user`.\n *\n * If no variables supplied match up with the template name, the template name will instead be\n * used as the variable data.\n *\n * @param url A URL to swap variables into.\n * @param variables An object containing variables to swap into the URL.\n */\n replaceUrl(url: string, variables: RMOAS.ServerVariable = {}) {\n // When we're constructing URLs, server URLs with trailing slashes cause problems with doing\n // lookups, so if we have one here on, slice it off.\n return stripTrailingSlash(\n url.replace(SERVER_VARIABLE_REGEX, (original: string, key: string) => {\n if (key in variables) {\n const data = variables[key];\n if (typeof data === 'object') {\n if (!Array.isArray(data) && data !== null && 'default' in data) {\n return data.default as string;\n }\n } else {\n return data as string;\n }\n }\n\n const userVariable = getUserVariable(this.user, key);\n if (userVariable) {\n return userVariable as string;\n }\n\n return original;\n }),\n );\n }\n\n /**\n * Retrieve an Operation of Webhook class instance for a given path and method.\n *\n * @param path Path to lookup and retrieve.\n * @param method HTTP Method to retrieve on the path.\n */\n operation(\n path: string,\n method: RMOAS.HttpMethods,\n opts: {\n /**\n * If you prefer to first look for a webhook with this path and method.\n */\n isWebhook?: boolean;\n } = {},\n ) {\n // If we're unable to locate an operation for this path+method combination within the API\n // definition, we should still set an empty schema on the operation in the `Operation` class\n // because if we don't trying to use any of the accessors on that class are going to fail as\n // `schema` will be `undefined`.\n let operation: RMOAS.OperationObject = {\n parameters: [],\n };\n\n if (opts.isWebhook) {\n const api = this.api as OpenAPIV3_1.Document;\n // Typecasting this to a `PathsObject` because we don't have `$ref` pointers here.\n if ((api?.webhooks[path] as RMOAS.PathsObject)?.[method]) {\n operation = (api.webhooks[path] as RMOAS.PathsObject)[method] as RMOAS.OperationObject;\n return new Webhook(api, path, method, operation);\n }\n }\n\n if (this?.api?.paths?.[path]?.[method]) {\n operation = this.api.paths[path][method];\n }\n\n return new Operation(this.api, path, method, operation);\n }\n\n findOperationMatches(url: string): PathMatches {\n const { origin, hostname } = new URL(url);\n const originRegExp = new RegExp(origin, 'i');\n const { servers, paths } = this.api;\n\n let pathName;\n let targetServer;\n let matchedServer;\n\n if (!servers || !servers.length) {\n // If this API definition doesn't have any servers set up let's treat it as if it were\n // https://example.com because that's the default origin we add in `normalizedUrl` under the\n // same circumstances. Without this we won't be able to match paths within what is otherwise\n // a valid OpenAPI definition.\n matchedServer = {\n url: 'https://example.com',\n };\n } else {\n matchedServer = servers.find(s => originRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n if (!matchedServer) {\n const hostnameRegExp = new RegExp(hostname);\n matchedServer = servers.find(s => hostnameRegExp.exec(this.replaceUrl(s.url, s.variables || {})));\n }\n }\n\n // If we **still** haven't found a matching server, then the OAS server URL might have server\n // variables and we should loosen it up with regex to try to discover a matching path.\n //\n // For example if an OAS has `https://{region}.node.example.com/v14` set as its server URL, and\n // the `this.user` object has a `region` value of `us`, if we're trying to locate an operation\n // for https://eu.node.example.com/v14/api/esm we won't be able to because normally the users\n // `region` of `us` will be transposed in and we'll be trying to locate `eu.node.example.com`\n // in `us.node.example.com` -- which won't work.\n //\n // So what this does is transform `https://{region}.node.example.com/v14` into\n // `https://([-_a-zA-Z0-9[\\\\]]+).node.example.com/v14`, and from there we'll be able to match\n // https://eu.node.example.com/v14/api/esm and ultimately find the operation matches for\n // `/api/esm`.\n if (!matchedServer) {\n const matchedServerAndPath = servers\n .map(server => {\n const rgx = transformUrlIntoRegex(server.url);\n const found = new RegExp(rgx).exec(url);\n if (!found) {\n return undefined;\n }\n\n return {\n matchedServer: server,\n pathName: url.split(new RegExp(rgx)).slice(-1).pop(),\n };\n })\n .filter(Boolean);\n\n if (!matchedServerAndPath.length) {\n return undefined;\n }\n\n pathName = matchedServerAndPath[0].pathName;\n targetServer = {\n ...matchedServerAndPath[0].matchedServer,\n };\n } else {\n // Instead of setting `url` directly against `matchedServer` we need to set it to an\n // intermediary object as directly modifying `matchedServer.url` will in turn update\n // `this.servers[idx].url` which we absolutely do not want to happen.\n targetServer = {\n ...matchedServer,\n url: this.replaceUrl(matchedServer.url, matchedServer.variables || {}),\n };\n\n [, pathName] = url.split(new RegExp(targetServer.url, 'i'));\n }\n\n if (pathName === undefined) return undefined;\n if (pathName === '') pathName = '/';\n const annotatedPaths = generatePathMatches(paths, pathName, targetServer.url);\n if (!annotatedPaths.length) return undefined;\n\n return annotatedPaths;\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL and HTTP method. Will return an object\n * containing a `url` object and another one for `operation`. This differs from `getOperation()`\n * in that it does not return an instance of the `Operation` class.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n findOperation(url: string, method: RMOAS.HttpMethods): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n\n const matches = filterPathMethods(annotatedPaths, method) as {\n operation: RMOAS.PathsObject;\n url: PathMatch['url']; // @fixme this should actually be an `OperationObject`.\n }[];\n if (!matches.length) return undefined;\n return findTargetPath(matches);\n }\n\n /**\n * Discover an operation in an OAS from a fully-formed URL without an HTTP method. Will return an\n * object containing a `url` object and another one for `operation`.\n *\n * @param url A full URL to look up.\n */\n findOperationWithoutMethod(url: string): PathMatch {\n const annotatedPaths = this.findOperationMatches(url);\n if (!annotatedPaths) {\n return undefined;\n }\n return findTargetPath(annotatedPaths);\n }\n\n /**\n * Retrieve an operation in an OAS from a fully-formed URL and HTTP method. Differs from\n * `findOperation` in that while this method will return an `Operation` instance,\n * `findOperation()` does not.\n *\n * @param url A full URL to look up.\n * @param method The cooresponding HTTP method to look up.\n */\n getOperation(url: string, method: RMOAS.HttpMethods) {\n const op = this.findOperation(url, method);\n if (op === undefined) {\n return undefined;\n }\n\n return this.operation(op.url.nonNormalizedPath, method);\n }\n\n /**\n * Retrieve an operation in an OAS by an `operationId`.\n *\n * If an operation does not have an `operationId` one will be generated in place, using the\n * default behavior of `Operation.getOperationId()`, and then asserted against your query.\n *\n * Note that because `operationId`s are unique that uniqueness does include casing so the ID\n * you are looking for will be asserted as an exact match.\n *\n * @see {Operation.getOperationId()}\n * @param id The `operationId` to look up.\n */\n getOperationById(id: string) {\n let found: Operation | Webhook;\n\n Object.values(this.getPaths()).forEach(operations => {\n if (found) return;\n found = Object.values(operations).find(operation => operation.getOperationId() === id);\n });\n\n if (found) {\n return found;\n }\n\n Object.entries(this.getWebhooks()).forEach(([, webhooks]) => {\n if (found) return;\n found = Object.values(webhooks).find(webhook => webhook.getOperationId() === id);\n });\n\n return found;\n }\n\n /**\n * With an object of user information, retrieve the appropriate API auth keys from the current\n * OAS definition.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\n getAuth(user: RMOAS.User, selectedApp?: number | string) {\n if (!this.api?.components?.securitySchemes) {\n return {};\n }\n\n return getAuth(this.api, user, selectedApp);\n }\n\n /**\n * Returns the `paths` object that exists in this API definition but with every `method` mapped\n * to an instance of the `Operation` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getPaths() {\n /**\n * Because a path doesn't need to contain a keyed-object of HTTP methods, we should exclude\n * anything from within the paths object that isn't a known HTTP method.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#fixed-fields-7}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#fixed-fields-7}\n */\n const paths: Record<string, Record<RMOAS.HttpMethods, Operation | Webhook>> = {};\n\n Object.keys(this.api.paths ? this.api.paths : []).forEach(path => {\n // If this is a specification extension then we should ignore it.\n if (path.startsWith('x-')) {\n return;\n }\n\n paths[path] = {} as Record<RMOAS.HttpMethods, Operation | Webhook>;\n\n // Though this library is generally unaware of `$ref` pointers we're making a singular\n // exception with this accessor out of convenience.\n if ('$ref' in this.api.paths[path]) {\n this.api.paths[path] = findSchemaDefinition(this.api.paths[path].$ref, this.api);\n }\n\n Object.keys(this.api.paths[path]).forEach((method: RMOAS.HttpMethods) => {\n if (!supportedMethods.has(method)) return;\n\n paths[path][method] = this.operation(path, method);\n });\n });\n\n return paths;\n }\n\n /**\n * Returns the `webhooks` object that exists in this API definition but with every `method`\n * mapped to an instance of the `Webhook` class.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n */\n getWebhooks() {\n const webhooks: Record<string, Record<RMOAS.HttpMethods, Webhook>> = {};\n const api = this.api as OpenAPIV3_1.Document;\n\n Object.keys(api.webhooks ? api.webhooks : []).forEach(id => {\n webhooks[id] = {} as Record<RMOAS.HttpMethods, Webhook>;\n Object.keys(api.webhooks[id]).forEach((method: RMOAS.HttpMethods) => {\n webhooks[id][method] = this.operation(id, method, { isWebhook: true }) as Webhook;\n });\n });\n\n return webhooks;\n }\n\n /**\n * Return an array of all tag names that exist on this API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#oasObject}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#openapi-object}\n * @param setIfMissing If a tag is not present on an operation that operations path will be added\n * into the list of tags returned.\n */\n getTags(setIfMissing = false) {\n const allTags = new Set<string>();\n\n const oasTags =\n this.api.tags?.map(tag => {\n return tag.name;\n }) || [];\n\n const disableTagSorting = getExtension('disable-tag-sorting', this.api);\n\n Object.entries(this.getPaths()).forEach(([path, operations]) => {\n Object.values(operations).forEach(operation => {\n const tags = operation.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n Object.entries(this.getWebhooks()).forEach(([path, webhooks]) => {\n Object.values(webhooks).forEach(webhook => {\n const tags = webhook.getTags();\n if (setIfMissing && !tags.length) {\n allTags.add(path);\n return;\n }\n\n tags.forEach(tag => {\n allTags.add(tag.name);\n });\n });\n });\n\n // Tags that exist only on the endpoint\n const endpointTags: string[] = [];\n // Tags that the user has defined in the `tags` array\n const tagsArray: string[] = [];\n\n // Distinguish between which tags exist in the `tags` array and which tags\n // exist only at the endpoint level. For tags that exist only at the\n // endpoint level, we'll just tack that on to the end of the sorted tags.\n if (disableTagSorting) {\n return Array.from(allTags);\n }\n\n Array.from(allTags).forEach(tag => {\n if (oasTags.includes(tag)) {\n tagsArray.push(tag);\n } else {\n endpointTags.push(tag);\n }\n });\n\n let sortedTags = tagsArray.sort((a, b) => {\n return oasTags.indexOf(a) - oasTags.indexOf(b);\n });\n\n sortedTags = sortedTags.concat(endpointTags);\n\n return sortedTags;\n }\n\n /**\n * Determine if a given a custom specification extension exists within the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n hasExtension(extension: string) {\n return hasRootExtension(extension, this.api);\n }\n\n /**\n * Retrieve a custom specification extension off of the API definition.\n *\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to lookup.\n */\n getExtension(extension: string | keyof Extensions, operation?: Operation) {\n return getExtension(extension, this.api, operation);\n }\n\n /**\n * Determine if a given OpenAPI custom extension is valid or not.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n * @param extension Specification extension to validate.\n * @throws\n */\n validateExtension(extension: keyof Extensions) {\n if (this.hasExtension('x-readme')) {\n const data = this.getExtension('x-readme') as Extensions;\n if (typeof data !== 'object' || Array.isArray(data) || data === null) {\n throw new TypeError('\"x-readme\" must be of type \"Object\"');\n }\n\n if (extension in data) {\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data[extension])) {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data[extension], `x-readme.${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data[extension] !== 'object') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data[extension] !== 'boolean') {\n throw new TypeError(`\"x-readme.${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n // If the extension isn't grouped under `x-readme`, we need to look for them with `x-` prefixes.\n if (this.hasExtension(`x-${extension}`)) {\n const data = this.getExtension(`x-${extension}`);\n if ([CODE_SAMPLES, HEADERS, PARAMETER_ORDERING, SAMPLES_LANGUAGES].includes(extension)) {\n if (!Array.isArray(data)) {\n throw new TypeError(`\"x-${extension}\" must be of type \"Array\"`);\n }\n\n if (extension === PARAMETER_ORDERING) {\n validateParameterOrdering(data, `x-${extension}`);\n }\n } else if (extension === OAUTH_OPTIONS) {\n if (typeof data !== 'object') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Object\"`);\n }\n } else if (typeof data !== 'boolean') {\n throw new TypeError(`\"x-${extension}\" must be of type \"Boolean\"`);\n }\n }\n }\n\n /**\n * Validate all of our custom or known OpenAPI extensions, throwing exceptions when necessary.\n *\n * @see {@link https://docs.readme.com/docs/openapi-extensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#specificationExtensions}\n * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions}\n */\n validateExtensions() {\n Object.keys(extensionDefaults).forEach((extension: keyof Extensions) => {\n this.validateExtension(extension);\n });\n }\n\n /**\n * Retrieve any circular `$ref` pointers that maybe present within the API definition.\n *\n * This method requires that you first dereference the definition.\n *\n * @see Oas.dereference\n */\n getCircularReferences() {\n if (!this.dereferencing.complete) {\n throw new Error('#dereference() must be called first in order for this method to obtain circular references.');\n }\n\n return this.dereferencing.circularRefs;\n }\n\n /**\n * Dereference the current OAS definition so it can be parsed free of worries of `$ref` schemas\n * and circular structures.\n *\n */\n async dereference(\n opts: {\n /**\n * A callback method can be supplied to be called when dereferencing is complete. Used for\n * debugging that the multi-promise handling within this method works.\n *\n * @private\n */\n cb?: () => void;\n\n /**\n * Preserve component schema names within themselves as a `title`.\n */\n preserveRefAsJSONSchemaTitle?: boolean;\n } = { preserveRefAsJSONSchemaTitle: false },\n ) {\n if (this.dereferencing.complete) {\n return new Promise(resolve => {\n resolve(true);\n });\n }\n\n if (this.dereferencing.processing) {\n return new Promise((resolve, reject) => {\n this.promises.push({ resolve, reject });\n });\n }\n\n this.dereferencing.processing = true;\n\n const { api, promises } = this;\n\n // Because referencing will eliminate any lineage back to the original `$ref`, information that\n // we might need at some point, we should run through all available component schemas and denote\n // what their name is so that when dereferencing happens below those names will be preserved.\n if (api && api.components && api.components.schemas && typeof api.components.schemas === 'object') {\n Object.keys(api.components.schemas).forEach(schemaName => {\n // As of OpenAPI 3.1 component schemas can be primitives or arrays. If this happens then we\n // shouldn't try to add `title` or `x-readme-ref-name` properties because we can't. We'll\n // have some data loss on these schemas but as they aren't objects they likely won't be used\n // in ways that would require needing a `title` or `x-readme-ref-name` anyways.\n if (\n isPrimitive(api.components.schemas[schemaName]) ||\n Array.isArray(api.components.schemas[schemaName]) ||\n api.components.schemas[schemaName] === null\n ) {\n return;\n }\n\n if (opts.preserveRefAsJSONSchemaTitle) {\n // This may result in some data loss if there's already a `title` present, but in the case\n // where we want to generate code for the API definition (see http://npm.im/api), we'd\n // prefer to retain original reference name as a title for any generated types.\n (api.components.schemas[schemaName] as RMOAS.SchemaObject).title = schemaName;\n }\n\n (api.components.schemas[schemaName] as RMOAS.SchemaObject)['x-readme-ref-name'] = schemaName;\n });\n }\n\n const parser = new $RefParser();\n\n return parser\n .dereference(api || {}, {\n resolve: {\n // We shouldn't be resolving external pointers at this point so just ignore them.\n external: false,\n },\n dereference: {\n // If circular `$refs` are ignored they'll remain in the OAS as `$ref: String`, otherwise\n // `$ref‘ just won't exist. This allows us to do easy circular reference detection.\n circular: 'ignore',\n },\n })\n .then((dereferenced: RMOAS.OASDocument) => {\n let circularRefs: string[] = [];\n if (parser.$refs.circular) {\n circularRefs = parser.$refs.circularRefs.map(pointer => {\n // The circular $refs that are coming out of `json-schema-ref-parser` are prefixed\n // with the schema path (file path, url, whatever) that the schema exists in. Because\n // we don't care about this information for this reporting mechanism, and only the\n // $ref pointer, we're removing it.\n return `#${pointer.split('#')[1]}`;\n });\n }\n\n this.api = dereferenced;\n\n this.promises = promises;\n this.dereferencing = {\n processing: false,\n complete: true,\n circularRefs,\n };\n\n // Used for debugging that dereferencing promise awaiting works.\n if (opts.cb) {\n opts.cb();\n }\n })\n .then(() => {\n return this.promises.map(deferred => deferred.resolve());\n });\n }\n}\n","import type * as RMOAS from '../types.js';\nimport type { OpenAPIV3, OpenAPIV3_1 } from 'openapi-types';\n\ntype authKey = unknown | { password: number | string; user: number | string } | null;\n\n/**\n * @param user User to retrieve retrieve an auth key for.\n * @param scheme The type of security scheme that we want a key for.\n */\nfunction getKey(user: RMOAS.User, scheme: RMOAS.KeyedSecuritySchemeObject): authKey {\n switch (scheme.type) {\n case 'oauth2':\n case 'apiKey':\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n\n case 'http':\n if (scheme.scheme === 'basic') {\n return user[scheme._key] || { user: user.user || null, pass: user.pass || null };\n }\n\n if (scheme.scheme === 'bearer') {\n return user[scheme._key] || user.apiKey || scheme['x-default'] || null;\n }\n return null;\n\n default:\n return null;\n }\n}\n\n/**\n * Retrieve auth keys for a specific security scheme for a given user for a specific \"app\" that\n * they have configured.\n *\n * For `scheme` we're typing it to a union of `SecurityScheme` and `any` because we have handling\n * and tests for an unknown or unrecognized `type` and though it's not possible with the\n * `SecurityScheme.type` to be unrecognized it may still be possible to get an unrecognized scheme\n * with this method in the wild as we have API definitions in our database that were ingested\n * before we had good validation in place.\n *\n * @param user User\n * @param scheme Security scheme to get auth keys for.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getByScheme(\n user: RMOAS.User,\n scheme = <RMOAS.KeyedSecuritySchemeObject>{},\n selectedApp?: number | string,\n): authKey {\n if (user?.keys && user.keys.length) {\n if (selectedApp) {\n return getKey(\n user.keys.find(key => key.name === selectedApp),\n scheme,\n );\n }\n\n return getKey(user.keys[0], scheme);\n }\n\n return getKey(user, scheme);\n}\n\n/**\n * Retrieve auth keys for an API definition from a given user for a specific \"app\" that they have\n * configured.\n *\n * @param api API definition\n * @param user User\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport function getAuth(\n api: OpenAPIV3_1.Document | OpenAPIV3.Document,\n user: RMOAS.User,\n selectedApp?: number | string,\n) {\n return Object.keys(api?.components?.securitySchemes || {})\n .map(scheme => {\n return {\n [scheme]: getByScheme(\n user,\n {\n // This sucks but since we dereference we'll never have a `$ref` pointer here with a\n // `ReferenceObject` type.\n ...(api.components.securitySchemes[scheme] as RMOAS.SecuritySchemeObject),\n _key: scheme,\n },\n selectedApp,\n ),\n };\n })\n .reduce((prev, next) => Object.assign(prev, next), {});\n}\n","import type * as RMOAS from '../types.js';\n\n/**\n * Retrieve a user variable off of a given user.\n *\n * @see {@link https://docs.readme.com/docs/passing-data-to-jwt}\n * @param user The user to get a user variable for.\n * @param property The name of the variable to retrieve.\n * @param selectedApp The user app to retrieve an auth key for.\n */\nexport default function getUserVariable(user: RMOAS.User, property: string, selectedApp?: number | string) {\n let key = user;\n\n if ('keys' in user && Array.isArray(user.keys) && user.keys.length) {\n if (selectedApp) {\n key = user.keys.find(k => k.name === selectedApp);\n } else {\n key = user.keys[0];\n }\n }\n\n return key[property] || user[property] || null;\n}\n"]}
|