oas-normalize 11.1.4 → 12.1.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 CHANGED
@@ -5,7 +5,7 @@
5
5
  </p>
6
6
 
7
7
  <p align="center">
8
- Tooling for converting, validating, and parsing OpenAPI, Swagger, and Postman API definitions
8
+ Tooling for converting, validating, and parsing OpenAPI, Swagger, and Postman API definitions.
9
9
  </p>
10
10
 
11
11
  <p align="center">
@@ -27,126 +27,154 @@ npm install oas-normalize
27
27
 
28
28
  ## Usage
29
29
 
30
- ```javascript
30
+ ```ts
31
31
  import OASNormalize from 'oas-normalize';
32
- // const { default: OASNormalize } = require('oas-normalize'); // If you're using CJS.
33
32
 
34
33
  const oas = new OASNormalize(
35
34
  'https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml',
36
- // ...or a string, path, JSON blob, whatever you've got.
35
+ // ...or a JSON object, YAML, a file path, stringified JSON, whatever you have.
37
36
  );
38
37
 
39
- oas
38
+ await oas
40
39
  .validate()
41
- .then(definition => {
42
- // Definition will always be JSON, and valid.
43
- console.log(definition);
40
+ .then(() => {
41
+ // The API definition is valid!
44
42
  })
45
43
  .catch(err => {
46
- console.log(err);
44
+ console.error(err);
47
45
  });
48
46
  ```
49
47
 
50
- ### `#bundle()`
48
+ > [!WARNING]
49
+ > Support for Postman collections is experimental. If you've supplied a Postman collection to the library, it will **always** be converted to OpenAPI, using [`@readme/postman-to-openapi`](https://npm.im/@readme/postman-to-openapi) before doing any bundling, validating, etc.
51
50
 
52
- > **Note**
53
- >
54
- > Because Postman collections don't support `$ref` pointers, this method will automatically upconvert a Postman collection to OpenAPI if supplied one.
51
+ ### `.load()`
52
+
53
+ Load and retrive the API definition that `oas-normalize` was initialized with. Every method of `oas-normalize` utilizes this internally however if you would like to retrieve the original API _definition_ supplied (for example if all you had was a URL, a file path, or a buffer), you can use `.load()` to automatically resolve and return its contents.
54
+
55
+ ```ts
56
+ const file = await oas.load();
57
+ console.log(file);
58
+ ```
59
+
60
+ ### `.bundle()`
55
61
 
56
62
  Bundle up the given API definition, resolving any external `$ref` pointers in the process.
57
63
 
58
- ```js
59
- await oas.bundle().then(definition => {
60
- console.log(definition);
61
- });
64
+ ```ts
65
+ const definition = await oas.bundle();
66
+ console.log(definition);
62
67
  ```
63
68
 
64
- ### `#deref()`
69
+ ### `.convert()`
65
70
 
66
- > **Note**
67
- >
68
- > Because Postman collections don't support `$ref` pointers, this method will automatically upconvert a Postman collection to OpenAPI if supplied one.
71
+ Convert a given API definition into an OpenAPI definition JSON object.
72
+
73
+ ```ts
74
+ await oas
75
+ .convert()
76
+ .then(definition => {
77
+ // Definition will always be an OpenAPI JSON object, regardless if a
78
+ // Swagger definition, Postman collection, or even YAML was supplied.
79
+ console.log(definition);
80
+ })
81
+ .catch(err => {
82
+ console.error(err);
83
+ });
84
+ ```
85
+
86
+ ### `.deref()`
69
87
 
70
88
  Dereference the given API definition, resolving all `$ref` pointers in the process.
71
89
 
72
- ```js
73
- await oas.deref().then(definition => {
74
- console.log(definition);
75
- });
90
+ ```ts
91
+ const definition = await oas.bundle();
92
+ console.log(definition);
76
93
  ```
77
94
 
78
- ### `#validate({ convertToLatest?: boolean })`
95
+ ### `.validate()`
79
96
 
80
- Validate and optionally convert to OpenAPI, a given API definition. This supports Swagger 2.0, OpenAPI 3.x API definitions as well as Postman 2.x collections.
97
+ Validate a given API definition. This supports Swagger 2.0 and OpenAPI 3.x API definitions, as well as Postman 2.x collections.
81
98
 
82
- Please note that if you've supplied a Postman collection to the library it will **always** be converted to OpenAPI, using [@readme/postman-to-openapi](https://npm.im/@readme/postman-to-openapi), and we will only validate resulting OpenAPI definition.
83
-
84
- ```js
85
- await oas.validate().then(definition => {
86
- console.log(definition);
87
- });
99
+ ```ts
100
+ try {
101
+ await oas.validate();
102
+ // The API definition is valid!
103
+ } catch (err) {
104
+ console.error(err);
105
+ }
88
106
  ```
89
107
 
90
- #### Options
108
+ #### Error Handling
91
109
 
92
- <!-- prettier-ignore-start -->
93
- | Option | Type | Description |
94
- | :--- | :--- | :--- |
95
- | `convertToLatest` | Boolean | By default `#validate` will not upconvert Swagger API definitions to OpenAPI so if you wish for this to happen, supply `true`. |
96
- <!-- prettier-ignore-end -->
110
+ All thrown validation error messages that direct the user to the line(s) where their errors are present:
97
111
 
98
- #### Error Handling
112
+ ```
113
+ OpenAPI schema validation failed.
99
114
 
100
- For validation errors, when available, you'll get back an object:
101
-
102
- ```js
103
- {
104
- "details": [
105
- // Ajv pathing errors. For example:
106
- /* {
107
- "instancePath": "/components/securitySchemes/tlsAuth",
108
- "schemaPath": "#/properties/securitySchemes/patternProperties/%5E%5Ba-zA-Z0-9%5C.%5C-_%5D%2B%24/oneOf",
109
- "keyword": "oneOf",
110
- "params": { "passingSchemas": null },
111
- "message": "must match exactly one schema in oneOf"
112
- }, */
113
- ]
114
- }
115
+ REQUIRED must have required property 'url'
116
+
117
+ 7 | },
118
+ 8 | "servers": [
119
+ > 9 | {
120
+ | ^ ☹️ url is missing here!
121
+ 10 | "urll": "http://petstore.swagger.io/v2"
122
+ 11 | }
123
+ 12 | ],
115
124
  ```
116
125
 
117
- `message` is almost always there, but `path` is less dependable.
126
+ However if you would like to programatically access this information the `SyntaxError` error that is thrown contains a `details` array of [AJV](https://npm.im/ajv) errors:
127
+
128
+ ```json
129
+ [
130
+ {
131
+ "instancePath": "/servers/0",
132
+ "schemaPath": "#/required",
133
+ "keyword": "required",
134
+ "params": { "missingProperty": "url" },
135
+ "message": "must have required property 'url'",
136
+ },
137
+ {
138
+ "instancePath": "/servers/0",
139
+ "schemaPath": "#/additionalProperties",
140
+ "keyword": "additionalProperties",
141
+ "params": { "additionalProperty": "urll" },
142
+ "message": "must NOT have additional properties",
143
+ },
144
+ ];
145
+ ```
118
146
 
119
- ### `#version()`
147
+ ### `.version()`
120
148
 
121
149
  Load and retrieve version information about a supplied API definition.
122
150
 
123
- ```js
124
- await oas.version().then(({ specification, version }) => {
125
- console.log(specification); // openapi
126
- console.log(version); // 3.1.0
127
- });
151
+ ```ts
152
+ const { specification, version } = await oas.version();
153
+
154
+ console.log(specification); // openapi
155
+ console.log(version); // 3.1.0
128
156
  ```
129
157
 
130
158
  ### Options
131
159
 
132
160
  ##### Enable local paths
133
161
 
134
- For security reasons, you need to opt into allowing fetching by a local path. To enable it supply the `enablePaths` option to the class instance:
162
+ For security reasons, you need to opt into allowing fetching by a local path. To enable this supply the `enablePaths` option to the class instance:
135
163
 
136
- ```js
164
+ ```ts
137
165
  const oas = new OASNormalize('./petstore.json', { enablePaths: true });
138
166
  ```
139
167
 
140
168
  ##### Colorized errors
141
169
 
142
- If you wish errors from `.validate()` to be styled and colorized, supply `colorizeErrors: true` to your instance of `OASNormalize`:
170
+ If you wish errors from `.validate()` to be styled and colorized, supply `colorizeErrors: true` to the class instance:
143
171
 
144
- ```js
172
+ ```ts
145
173
  const oas = new OASNormalize('https://example.com/petstore.json', {
146
174
  colorizeErrors: true,
147
175
  });
148
176
  ```
149
177
 
150
- Error messages will look like such:
178
+ When enabled thrown validation error messages will now resemble the following:
151
179
 
152
180
  <img src="https://user-images.githubusercontent.com/33762/137796648-7e1157c2-cee4-466e-9129-dd2a743dd163.png" width="600" />
@@ -3,11 +3,24 @@ var _jsyaml = require('js-yaml'); var _jsyaml2 = _interopRequireDefault(_jsyaml)
3
3
  function isBuffer(obj) {
4
4
  return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && !!obj.constructor.isBuffer(obj);
5
5
  }
6
- function normalizeURL(url) {
7
- if (url.startsWith("https://github.com/") && url.includes("/blob/")) {
8
- return url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/");
6
+ function prepareURL(url) {
7
+ const options = {};
8
+ const u = new URL(url);
9
+ if (u.username || u.password) {
10
+ options.headers = {
11
+ Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`
12
+ };
13
+ u.username = "";
14
+ u.password = "";
9
15
  }
10
- return url;
16
+ if (u.host === "github.com" && u.pathname.includes("/blob/")) {
17
+ u.host = "raw.githubusercontent.com";
18
+ u.pathname = u.pathname.replace("/blob/", "/");
19
+ }
20
+ return {
21
+ url: u.toString(),
22
+ options
23
+ };
11
24
  }
12
25
  function getType(obj) {
13
26
  if (isBuffer(obj)) {
@@ -67,5 +80,5 @@ function getAPIDefinitionType(schema) {
67
80
 
68
81
 
69
82
 
70
- exports.isBuffer = isBuffer; exports.normalizeURL = normalizeURL; exports.getType = getType; exports.isOpenAPI = isOpenAPI; exports.isPostman = isPostman; exports.isSwagger = isSwagger; exports.stringToJSON = stringToJSON; exports.isAPIDefinition = isAPIDefinition; exports.getAPIDefinitionType = getAPIDefinitionType;
71
- //# sourceMappingURL=chunk-K75HC34M.cjs.map
83
+ exports.isBuffer = isBuffer; exports.prepareURL = prepareURL; exports.getType = getType; exports.isOpenAPI = isOpenAPI; exports.isPostman = isPostman; exports.isSwagger = isSwagger; exports.stringToJSON = stringToJSON; exports.isAPIDefinition = isAPIDefinition; exports.getAPIDefinitionType = getAPIDefinitionType;
84
+ //# sourceMappingURL=chunk-GZL345SR.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-GZL345SR.cjs","../src/lib/utils.ts"],"names":[],"mappings":"AAAA;ACAA,iFAAkC;AAM3B,SAAS,QAAA,CAAS,GAAA,EAAU;AACjC,EAAA,OACE,IAAA,GAAO,KAAA,GACP,GAAA,CAAI,YAAA,GAAe,KAAA,GACnB,OAAO,GAAA,CAAI,WAAA,CAAY,SAAA,IAAa,WAAA,GACpC,CAAC,CAAC,GAAA,CAAI,WAAA,CAAY,QAAA,CAAS,GAAG,CAAA;AAElC;AAMO,SAAS,UAAA,CAAW,GAAA,EAAa;AACtC,EAAA,MAAM,QAAA,EAAuB,CAAC,CAAA;AAC9B,EAAA,MAAM,EAAA,EAAI,IAAI,GAAA,CAAI,GAAG,CAAA;AAIrB,EAAA,GAAA,CAAI,CAAA,CAAE,SAAA,GAAY,CAAA,CAAE,QAAA,EAAU;AAC5B,IAAA,OAAA,CAAQ,QAAA,EAAU;AAAA,MAChB,aAAA,EAAe,CAAA,MAAA,EAAS,IAAA,CAAK,CAAA,EAAA;AAC/B,IAAA;AAEa,IAAA;AACA,IAAA;AACf,EAAA;AAGiC,EAAA;AACtB,IAAA;AACuB,IAAA;AAClC,EAAA;AAEO,EAAA;AACW,IAAA;AAChB,IAAA;AACF,EAAA;AACF;AAMkC;AACb,EAAA;AACV,IAAA;AACiB,EAAA;AACjB,IAAA;AACiB,EAAA;AACD,IAAA;AACd,MAAA;AACmB,IAAA;AAEnB,MAAA;AACoB,IAAA;AACpB,MAAA;AACT,IAAA;AAEO,IAAA;AACT,EAAA;AAEO,EAAA;AACT;AAM2D;AACzC,EAAA;AAClB;AAaoE;AACjC,EAAA;AACnC;AAM2D;AACzC,EAAA;AAClB;AAMgG;AAC9D,EAAA;AACvB,IAAA;AACyB,EAAA;AAER,IAAA;AAC1B,EAAA;AAE2B,EAAA;AAC7B;AAMiE;AACnC,EAAA;AAC9B;AAMqC;AACZ,EAAA;AACd,IAAA;AACqB,EAAA;AACrB,IAAA;AACqB,EAAA;AACrB,IAAA;AACT,EAAA;AAEO,EAAA;AACT;ADpEoC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-GZL345SR.cjs","sourcesContent":[null,"import YAML, { JSON_SCHEMA } from 'js-yaml';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any) {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Deconstruct a URL into a payload for a `fetch` request.\n *\n */\nexport function prepareURL(url: string) {\n const options: RequestInit = {};\n const u = new URL(url);\n\n // `fetch` doesn't support supplying basic auth credentials in the URL so we need to move them\n // into a header.\n if (u.username || u.password) {\n options.headers = {\n Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`,\n };\n\n u.username = '';\n u.password = '';\n }\n\n // Transform GitHub sources into their raw content URLs.\n if (u.host === 'github.com' && u.pathname.includes('/blob/')) {\n u.host = 'raw.githubusercontent.com';\n u.pathname = u.pathname.replace('/blob/', '/');\n }\n\n return {\n url: u.toString(),\n options,\n };\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any) {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>) {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>) {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>) {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>) {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"]}
@@ -3,11 +3,24 @@ import YAML, { JSON_SCHEMA } from "js-yaml";
3
3
  function isBuffer(obj) {
4
4
  return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && !!obj.constructor.isBuffer(obj);
5
5
  }
6
- function normalizeURL(url) {
7
- if (url.startsWith("https://github.com/") && url.includes("/blob/")) {
8
- return url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/");
6
+ function prepareURL(url) {
7
+ const options = {};
8
+ const u = new URL(url);
9
+ if (u.username || u.password) {
10
+ options.headers = {
11
+ Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`
12
+ };
13
+ u.username = "";
14
+ u.password = "";
9
15
  }
10
- return url;
16
+ if (u.host === "github.com" && u.pathname.includes("/blob/")) {
17
+ u.host = "raw.githubusercontent.com";
18
+ u.pathname = u.pathname.replace("/blob/", "/");
19
+ }
20
+ return {
21
+ url: u.toString(),
22
+ options
23
+ };
11
24
  }
12
25
  function getType(obj) {
13
26
  if (isBuffer(obj)) {
@@ -59,7 +72,7 @@ function getAPIDefinitionType(schema) {
59
72
 
60
73
  export {
61
74
  isBuffer,
62
- normalizeURL,
75
+ prepareURL,
63
76
  getType,
64
77
  isOpenAPI,
65
78
  isPostman,
@@ -68,4 +81,4 @@ export {
68
81
  isAPIDefinition,
69
82
  getAPIDefinitionType
70
83
  };
71
- //# sourceMappingURL=chunk-XOS5M44Y.js.map
84
+ //# sourceMappingURL=chunk-J322YOXV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/utils.ts"],"sourcesContent":["import YAML, { JSON_SCHEMA } from 'js-yaml';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any) {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Deconstruct a URL into a payload for a `fetch` request.\n *\n */\nexport function prepareURL(url: string) {\n const options: RequestInit = {};\n const u = new URL(url);\n\n // `fetch` doesn't support supplying basic auth credentials in the URL so we need to move them\n // into a header.\n if (u.username || u.password) {\n options.headers = {\n Authorization: `Basic ${btoa(`${u.username}:${u.password}`)}`,\n };\n\n u.username = '';\n u.password = '';\n }\n\n // Transform GitHub sources into their raw content URLs.\n if (u.host === 'github.com' && u.pathname.includes('/blob/')) {\n u.host = 'raw.githubusercontent.com';\n u.pathname = u.pathname.replace('/blob/', '/');\n }\n\n return {\n url: u.toString(),\n options,\n };\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any) {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>) {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>) {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>) {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>) {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"],"mappings":";AAAA,OAAO,QAAQ,mBAAmB;AAM3B,SAAS,SAAS,KAAU;AACjC,SACE,OAAO,QACP,IAAI,eAAe,QACnB,OAAO,IAAI,YAAY,aAAa,cACpC,CAAC,CAAC,IAAI,YAAY,SAAS,GAAG;AAElC;AAMO,SAAS,WAAW,KAAa;AACtC,QAAM,UAAuB,CAAC;AAC9B,QAAM,IAAI,IAAI,IAAI,GAAG;AAIrB,MAAI,EAAE,YAAY,EAAE,UAAU;AAC5B,YAAQ,UAAU;AAAA,MAChB,eAAe,SAAS,KAAK,GAAG,EAAE,QAAQ,IAAI,EAAE,QAAQ,EAAE,CAAC;AAAA,IAC7D;AAEA,MAAE,WAAW;AACb,MAAE,WAAW;AAAA,EACf;AA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WAAW,UAAU,MAAM,GAAG;AAC5B,WAAO;AAAA,EACT;AAEA,SAAO;AACT;","names":[]}
package/dist/index.cjs CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkK75HC34Mcjs = require('./chunk-K75HC34M.cjs');
9
+ var _chunkGZL345SRcjs = require('./chunk-GZL345SR.cjs');
10
10
 
11
11
  // src/index.ts
12
12
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
@@ -21,7 +21,7 @@ var OASNormalize = class _OASNormalize {
21
21
  enablePaths: false,
22
22
  ...opts
23
23
  };
24
- this.type = _chunkK75HC34Mcjs.getType.call(void 0, this.file);
24
+ this.type = _chunkGZL345SRcjs.getType.call(void 0, this.file);
25
25
  this.cache = {
26
26
  load: false,
27
27
  bundle: false,
@@ -29,14 +29,15 @@ var OASNormalize = class _OASNormalize {
29
29
  };
30
30
  }
31
31
  /**
32
- * @private
32
+ * Load and return the API definition that `oas-normalize` was initialized with.
33
+ *
33
34
  */
34
35
  async load() {
35
- if (this.cache.load) return Promise.resolve(this.cache.load);
36
+ if (this.cache.load) return this.cache.load;
36
37
  const resolve = (obj) => {
37
- const ret = _chunkK75HC34Mcjs.stringToJSON.call(void 0, obj);
38
+ const ret = _chunkGZL345SRcjs.stringToJSON.call(void 0, obj);
38
39
  this.cache.load = ret;
39
- return Promise.resolve(ret);
40
+ return ret;
40
41
  };
41
42
  switch (this.type) {
42
43
  case "json":
@@ -46,24 +47,22 @@ var OASNormalize = class _OASNormalize {
46
47
  case "buffer":
47
48
  return resolve(this.file.toString());
48
49
  case "url":
49
- const resp = await fetch(_chunkK75HC34Mcjs.normalizeURL.call(void 0, this.file)).then((res) => res.text());
50
+ const { url, options } = _chunkGZL345SRcjs.prepareURL.call(void 0, this.file);
51
+ const resp = await fetch(url, options).then((res) => res.text());
50
52
  return resolve(resp);
51
53
  case "path":
52
54
  if (!this.opts.enablePaths) {
53
- return Promise.reject(new Error("Use `opts.enablePaths` to enable accessing local files."));
55
+ throw new Error("Use `opts.enablePaths` to enable accessing local files.");
54
56
  }
55
57
  const contents = _fs2.default.readFileSync(this.file).toString();
56
58
  if (!contents.trim()) {
57
- return Promise.reject(new Error("No file contents found."));
59
+ throw new Error("No file contents found.");
58
60
  }
59
61
  return resolve(contents);
60
62
  default:
61
- return Promise.reject(new Error("Could not load this file."));
63
+ throw new Error("Could not load this file.");
62
64
  }
63
65
  }
64
- /**
65
- * @private
66
- */
67
66
  static async convertPostmanToOpenAPI(schema) {
68
67
  return _postmantoopenapi2.default.call(void 0, JSON.stringify(schema), void 0, { outputFormat: "json", replaceVars: true }).then(
69
68
  JSON.parse
@@ -74,9 +73,9 @@ var OASNormalize = class _OASNormalize {
74
73
  *
75
74
  */
76
75
  async bundle() {
77
- if (this.cache.bundle) return Promise.resolve(this.cache.bundle);
76
+ if (this.cache.bundle) return this.cache.bundle;
78
77
  return this.load().then((schema) => {
79
- if (_chunkK75HC34Mcjs.isPostman.call(void 0, schema)) {
78
+ if (_chunkGZL345SRcjs.isPostman.call(void 0, schema)) {
80
79
  return _OASNormalize.convertPostmanToOpenAPI(schema);
81
80
  }
82
81
  return schema;
@@ -90,9 +89,9 @@ var OASNormalize = class _OASNormalize {
90
89
  *
91
90
  */
92
91
  async deref() {
93
- if (this.cache.deref) return Promise.resolve(this.cache.deref);
92
+ if (this.cache.deref) return this.cache.deref;
94
93
  return this.load().then((schema) => {
95
- if (_chunkK75HC34Mcjs.isPostman.call(void 0, schema)) {
94
+ if (_chunkGZL345SRcjs.isPostman.call(void 0, schema)) {
96
95
  return _OASNormalize.convertPostmanToOpenAPI(schema);
97
96
  }
98
97
  return schema;
@@ -102,37 +101,54 @@ var OASNormalize = class _OASNormalize {
102
101
  });
103
102
  }
104
103
  /**
105
- * Validate, and potentially convert to OpenAPI, a given API definition.
104
+ * Convert a given API definition to OpenAPI if it is not already.
106
105
  *
107
106
  */
108
- async validate(opts = { convertToLatest: false }) {
109
- const convertToLatest = opts.convertToLatest;
107
+ async convert() {
108
+ if (this.cache.convert) return this.cache.convert;
109
+ return this.load().then(async (schema) => {
110
+ return _chunkGZL345SRcjs.isPostman.call(void 0, schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
111
+ }).then(async (schema) => {
112
+ if (!_chunkGZL345SRcjs.isSwagger.call(void 0, schema) && !_chunkGZL345SRcjs.isOpenAPI.call(void 0, schema)) {
113
+ throw new Error("The supplied API definition is unsupported.");
114
+ } else if (_chunkGZL345SRcjs.isOpenAPI.call(void 0, schema)) {
115
+ return schema;
116
+ }
117
+ const baseVersion = parseInt(schema.swagger, 10);
118
+ if (baseVersion === 1) {
119
+ throw new Error("Swagger v1.2 is unsupported.");
120
+ }
121
+ return _swagger2openapi2.default.convertObj(schema, { anchors: true }).then((options) => options.openapi);
122
+ });
123
+ }
124
+ /**
125
+ * Validate a given API definition.
126
+ *
127
+ * If supplied a Postman collection it will be converted to OpenAPI first and then run through
128
+ * standard OpenAPI validation.
129
+ *
130
+ */
131
+ async validate(opts = {}) {
110
132
  const parserOptions = opts.parser || {};
111
133
  if (!parserOptions.validate) {
112
134
  parserOptions.validate = {};
113
135
  }
114
136
  parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;
115
137
  return this.load().then(async (schema) => {
116
- if (!_chunkK75HC34Mcjs.isPostman.call(void 0, schema)) {
117
- return schema;
118
- }
119
- return _OASNormalize.convertPostmanToOpenAPI(schema);
138
+ return _chunkGZL345SRcjs.isPostman.call(void 0, schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
120
139
  }).then(async (schema) => {
121
- if (!_chunkK75HC34Mcjs.isSwagger.call(void 0, schema) && !_chunkK75HC34Mcjs.isOpenAPI.call(void 0, schema)) {
122
- return Promise.reject(new Error("The supplied API definition is unsupported."));
123
- } else if (_chunkK75HC34Mcjs.isSwagger.call(void 0, schema)) {
140
+ if (!_chunkGZL345SRcjs.isSwagger.call(void 0, schema) && !_chunkGZL345SRcjs.isOpenAPI.call(void 0, schema)) {
141
+ throw new Error("The supplied API definition is unsupported.");
142
+ } else if (_chunkGZL345SRcjs.isSwagger.call(void 0, schema)) {
124
143
  const baseVersion = parseInt(schema.swagger, 10);
125
144
  if (baseVersion === 1) {
126
- return Promise.reject(new Error("Swagger v1.2 is unsupported."));
145
+ throw new Error("Swagger v1.2 is unsupported.");
127
146
  }
128
147
  }
129
148
  const clonedSchema = JSON.parse(JSON.stringify(schema));
130
149
  return _openapiparser2.default.validate(clonedSchema, parserOptions).then(() => {
131
- if (!convertToLatest || _chunkK75HC34Mcjs.isOpenAPI.call(void 0, schema)) {
132
- return schema;
133
- }
134
- return _swagger2openapi2.default.convertObj(schema, { anchors: true }).then((options) => options.openapi);
135
- }).catch((err) => Promise.reject(err));
150
+ return true;
151
+ });
136
152
  });
137
153
  }
138
154
  /**
@@ -141,7 +157,7 @@ var OASNormalize = class _OASNormalize {
141
157
  */
142
158
  async version() {
143
159
  return this.load().then((schema) => {
144
- switch (_chunkK75HC34Mcjs.getAPIDefinitionType.call(void 0, schema)) {
160
+ switch (_chunkGZL345SRcjs.getAPIDefinitionType.call(void 0, schema)) {
145
161
  case "openapi":
146
162
  return {
147
163
  specification: "openapi",
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","../src/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAAA;AACA;AACA;ACPA,gEAAe;AAEf,qHAA0B;AAC1B,kIAA6B;AAC7B,oHAAsB;AAItB,IAAqB,aAAA,EAArB,MAAqB,cAAa;AAAA,EAahC,WAAA,CAAY,IAAA,EAAW,IAAA,EAAgB;AACrC,IAAA,IAAA,CAAK,KAAA,EAAO,IAAA;AACZ,IAAA,IAAA,CAAK,KAAA,EAAO;AAAA,MACV,cAAA,EAAgB,KAAA;AAAA,MAChB,WAAA,EAAa,KAAA;AAAA,MACb,GAAG;AAAA,IACL,CAAA;AAEA,IAAA,IAAA,CAAK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C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AACF,CAAA;AD5EA;AACE;AACF,+BAAA","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","sourcesContent":[null,"import type { Options } from './lib/types.js';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport openapiParser from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * @private\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return Promise.resolve(this.cache.load);\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return Promise.resolve(ret);\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const resp = await fetch(utils.normalizeURL(this.file)).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n return Promise.reject(new Error('Use `opts.enablePaths` to enable accessing local files.'));\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n return Promise.reject(new Error('No file contents found.'));\n }\n return resolve(contents);\n\n default:\n return Promise.reject(new Error('Could not load this file.'));\n }\n }\n\n /**\n * @private\n */\n static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle() {\n if (this.cache.bundle) return Promise.resolve(this.cache.bundle);\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.bundle(schema))\n .then(bundle => {\n this.cache.bundle = bundle;\n return bundle;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref() {\n if (this.cache.deref) return Promise.resolve(this.cache.deref);\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Validate, and potentially convert to OpenAPI, a given API definition.\n *\n */\n async validate(\n opts: {\n /**\n * Automatically convert the supplied API definition to the latest version of OpenAPI.\n */\n convertToLatest?: boolean;\n parser?: openapiParser.Options;\n } = { convertToLatest: false },\n ): Promise<OpenAPI.Document> {\n const convertToLatest = opts.convertToLatest;\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) {\n parserOptions.validate = {};\n }\n\n parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n if (!utils.isPostman(schema)) {\n return schema;\n }\n\n return OASNormalize.convertPostmanToOpenAPI(schema);\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n return Promise.reject(new Error('The supplied API definition is unsupported.'));\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n return Promise.reject(new Error('Swagger v1.2 is unsupported.'));\n }\n }\n\n /**\n * `openapiParser.validate()` dereferences schemas at the same time as validation and does\n * not give us an option to disable this. Since all we already have a dereferencing method\n * on this library and our `validate()` method here just needs to tell us if the definition\n * is valid or not we need to clone it before passing it over to `openapi-parser` so as to\n * not run into pass-by-reference problems.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n return openapiParser\n .validate(clonedSchema, parserOptions)\n .then(() => {\n if (!convertToLatest || utils.isOpenAPI(schema)) {\n return schema;\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n })\n .catch(err => Promise.reject(err));\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Unknown file detected.');\n }\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","../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,GAAU;AAChC,MAAA,OAAA,CAAc,oDAAA,MAA2B,CAAA,EAAG;AAAA,QAC1C,KAAK,SAAA;AACH,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf,OAAA,EAAU,MAAA,CAAyC;AAAA,UACrD,CAAA;AAAA,QAEF,KAAK,SAAA;AACH,UAAA,IAAI,QAAA,EAAU,SAAA;AACd,UAAA,GAAA,iBAAK,MAAA,2BAAQ,IAAA,6BAAiC,QAAA,EAAQ;AAIpD,YAAA,MAAM,MAAA,EAAA,iBAAS,MAAA,6BAAQ,MAAA,CAAA,CAAgC,MAAA,CAAO,KAAA;AAAA,cAC5D;AAAA,YACF,CAAA;AAEA,YAAA,GAAA,CAAI,KAAA,EAAO;AACT,cAAA,QAAA,EAAU,KAAA,CAAM,CAAC,CAAA;AAAA,YACnB;AAAA,UACF;AAEA,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf;AAAA,UACF,CAAA;AAAA,QAEF,KAAK,SAAA;AACH,UAAA,OAAO;AAAA,YACL,aAAA,EAAe,SAAA;AAAA,YACf,OAAA,EAAU,MAAA,CAAyC;AAAA,UACrD,CAAA;AAAA,QAEF,OAAA;AACE,UAAA,MAAM,IAAI,KAAA,CAAM,wBAAwB,CAAA;AAAA,MAC5C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AACF,CAAA;AD9EA;AACE;AACF,+BAAA","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/index.cjs","sourcesContent":[null,"import type { Options } from './lib/types.js';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport openapiParser from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n convert?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * Load and return the API definition that `oas-normalize` was initialized with.\n *\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return this.cache.load;\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return ret;\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const { url, options } = utils.prepareURL(this.file);\n const resp = await fetch(url, options).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n throw new Error('Use `opts.enablePaths` to enable accessing local files.');\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n throw new Error('No file contents found.');\n }\n return resolve(contents);\n\n default:\n throw new Error('Could not load this file.');\n }\n }\n\n private static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle() {\n if (this.cache.bundle) return this.cache.bundle;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.bundle(schema))\n .then(bundle => {\n this.cache.bundle = bundle;\n return bundle;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref() {\n if (this.cache.deref) return this.cache.deref;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Convert a given API definition to OpenAPI if it is not already.\n *\n */\n async convert(): Promise<OpenAPI.Document> {\n if (this.cache.convert) return this.cache.convert;\n\n return this.load()\n .then(async schema => {\n // If we have a Postman collection we need to convert it to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isOpenAPI(schema)) {\n return schema;\n }\n\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n });\n }\n\n /**\n * Validate a given API definition.\n *\n * If supplied a Postman collection it will be converted to OpenAPI first and then run through\n * standard OpenAPI validation.\n *\n */\n async validate(\n opts: {\n parser?: openapiParser.Options;\n } = {},\n ): Promise<true> {\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) {\n parserOptions.validate = {};\n }\n\n parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n // Because we don't have something akin to `openapi-parser` for Postman collections we just\n // always convert them to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n }\n\n /**\n * `openapiParser.validate()` dereferences schemas at the same time as validation, mutating\n * the supplied parameter in the process, and does not give us an option to disable this.\n * As we already have a dereferencing method on this library, and this method just needs to\n * tell us if the API definition is valid or not, we need to clone the schema before\n * supplying it to `openapi-parser`.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n return openapiParser.validate(clonedSchema, parserOptions).then(() => {\n // The API definition, whatever its format or specification, is valid.\n return true;\n });\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Unknown file detected.');\n }\n });\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -6,6 +6,7 @@ import { getType } from './lib/utils.cjs';
6
6
  declare class OASNormalize {
7
7
  cache: {
8
8
  bundle?: OpenAPI.Document | false;
9
+ convert?: OpenAPI.Document | false;
9
10
  deref?: OpenAPI.Document | false;
10
11
  load?: Record<string, unknown> | false;
11
12
  };
@@ -14,13 +15,11 @@ declare class OASNormalize {
14
15
  type: ReturnType<typeof getType>;
15
16
  constructor(file: any, opts?: Options);
16
17
  /**
17
- * @private
18
+ * Load and return the API definition that `oas-normalize` was initialized with.
19
+ *
18
20
  */
19
21
  load(): Promise<Record<string, unknown>>;
20
- /**
21
- * @private
22
- */
23
- static convertPostmanToOpenAPI(schema: any): Promise<any>;
22
+ private static convertPostmanToOpenAPI;
24
23
  /**
25
24
  * Bundle up the given API definition, resolving any external `$ref` pointers in the process.
26
25
  *
@@ -32,16 +31,20 @@ declare class OASNormalize {
32
31
  */
33
32
  deref(): Promise<OpenAPI.Document<{}>>;
34
33
  /**
35
- * Validate, and potentially convert to OpenAPI, a given API definition.
34
+ * Convert a given API definition to OpenAPI if it is not already.
35
+ *
36
+ */
37
+ convert(): Promise<OpenAPI.Document>;
38
+ /**
39
+ * Validate a given API definition.
40
+ *
41
+ * If supplied a Postman collection it will be converted to OpenAPI first and then run through
42
+ * standard OpenAPI validation.
36
43
  *
37
44
  */
38
45
  validate(opts?: {
39
- /**
40
- * Automatically convert the supplied API definition to the latest version of OpenAPI.
41
- */
42
- convertToLatest?: boolean;
43
46
  parser?: openapiParser.Options;
44
- }): Promise<OpenAPI.Document>;
47
+ }): Promise<true>;
45
48
  /**
46
49
  * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.
47
50
  *
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ import { getType } from './lib/utils.js';
6
6
  declare class OASNormalize {
7
7
  cache: {
8
8
  bundle?: OpenAPI.Document | false;
9
+ convert?: OpenAPI.Document | false;
9
10
  deref?: OpenAPI.Document | false;
10
11
  load?: Record<string, unknown> | false;
11
12
  };
@@ -14,13 +15,11 @@ declare class OASNormalize {
14
15
  type: ReturnType<typeof getType>;
15
16
  constructor(file: any, opts?: Options);
16
17
  /**
17
- * @private
18
+ * Load and return the API definition that `oas-normalize` was initialized with.
19
+ *
18
20
  */
19
21
  load(): Promise<Record<string, unknown>>;
20
- /**
21
- * @private
22
- */
23
- static convertPostmanToOpenAPI(schema: any): Promise<any>;
22
+ private static convertPostmanToOpenAPI;
24
23
  /**
25
24
  * Bundle up the given API definition, resolving any external `$ref` pointers in the process.
26
25
  *
@@ -32,16 +31,20 @@ declare class OASNormalize {
32
31
  */
33
32
  deref(): Promise<OpenAPI.Document<{}>>;
34
33
  /**
35
- * Validate, and potentially convert to OpenAPI, a given API definition.
34
+ * Convert a given API definition to OpenAPI if it is not already.
35
+ *
36
+ */
37
+ convert(): Promise<OpenAPI.Document>;
38
+ /**
39
+ * Validate a given API definition.
40
+ *
41
+ * If supplied a Postman collection it will be converted to OpenAPI first and then run through
42
+ * standard OpenAPI validation.
36
43
  *
37
44
  */
38
45
  validate(opts?: {
39
- /**
40
- * Automatically convert the supplied API definition to the latest version of OpenAPI.
41
- */
42
- convertToLatest?: boolean;
43
46
  parser?: openapiParser.Options;
44
- }): Promise<OpenAPI.Document>;
47
+ }): Promise<true>;
45
48
  /**
46
49
  * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.
47
50
  *
package/dist/index.js CHANGED
@@ -4,9 +4,9 @@ import {
4
4
  isOpenAPI,
5
5
  isPostman,
6
6
  isSwagger,
7
- normalizeURL,
7
+ prepareURL,
8
8
  stringToJSON
9
- } from "./chunk-XOS5M44Y.js";
9
+ } from "./chunk-J322YOXV.js";
10
10
 
11
11
  // src/index.ts
12
12
  import fs from "node:fs";
@@ -29,14 +29,15 @@ var OASNormalize = class _OASNormalize {
29
29
  };
30
30
  }
31
31
  /**
32
- * @private
32
+ * Load and return the API definition that `oas-normalize` was initialized with.
33
+ *
33
34
  */
34
35
  async load() {
35
- if (this.cache.load) return Promise.resolve(this.cache.load);
36
+ if (this.cache.load) return this.cache.load;
36
37
  const resolve = (obj) => {
37
38
  const ret = stringToJSON(obj);
38
39
  this.cache.load = ret;
39
- return Promise.resolve(ret);
40
+ return ret;
40
41
  };
41
42
  switch (this.type) {
42
43
  case "json":
@@ -46,24 +47,22 @@ var OASNormalize = class _OASNormalize {
46
47
  case "buffer":
47
48
  return resolve(this.file.toString());
48
49
  case "url":
49
- const resp = await fetch(normalizeURL(this.file)).then((res) => res.text());
50
+ const { url, options } = prepareURL(this.file);
51
+ const resp = await fetch(url, options).then((res) => res.text());
50
52
  return resolve(resp);
51
53
  case "path":
52
54
  if (!this.opts.enablePaths) {
53
- return Promise.reject(new Error("Use `opts.enablePaths` to enable accessing local files."));
55
+ throw new Error("Use `opts.enablePaths` to enable accessing local files.");
54
56
  }
55
57
  const contents = fs.readFileSync(this.file).toString();
56
58
  if (!contents.trim()) {
57
- return Promise.reject(new Error("No file contents found."));
59
+ throw new Error("No file contents found.");
58
60
  }
59
61
  return resolve(contents);
60
62
  default:
61
- return Promise.reject(new Error("Could not load this file."));
63
+ throw new Error("Could not load this file.");
62
64
  }
63
65
  }
64
- /**
65
- * @private
66
- */
67
66
  static async convertPostmanToOpenAPI(schema) {
68
67
  return postmanToOpenAPI(JSON.stringify(schema), void 0, { outputFormat: "json", replaceVars: true }).then(
69
68
  JSON.parse
@@ -74,7 +73,7 @@ var OASNormalize = class _OASNormalize {
74
73
  *
75
74
  */
76
75
  async bundle() {
77
- if (this.cache.bundle) return Promise.resolve(this.cache.bundle);
76
+ if (this.cache.bundle) return this.cache.bundle;
78
77
  return this.load().then((schema) => {
79
78
  if (isPostman(schema)) {
80
79
  return _OASNormalize.convertPostmanToOpenAPI(schema);
@@ -90,7 +89,7 @@ var OASNormalize = class _OASNormalize {
90
89
  *
91
90
  */
92
91
  async deref() {
93
- if (this.cache.deref) return Promise.resolve(this.cache.deref);
92
+ if (this.cache.deref) return this.cache.deref;
94
93
  return this.load().then((schema) => {
95
94
  if (isPostman(schema)) {
96
95
  return _OASNormalize.convertPostmanToOpenAPI(schema);
@@ -102,37 +101,54 @@ var OASNormalize = class _OASNormalize {
102
101
  });
103
102
  }
104
103
  /**
105
- * Validate, and potentially convert to OpenAPI, a given API definition.
104
+ * Convert a given API definition to OpenAPI if it is not already.
105
+ *
106
+ */
107
+ async convert() {
108
+ if (this.cache.convert) return this.cache.convert;
109
+ return this.load().then(async (schema) => {
110
+ return isPostman(schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
111
+ }).then(async (schema) => {
112
+ if (!isSwagger(schema) && !isOpenAPI(schema)) {
113
+ throw new Error("The supplied API definition is unsupported.");
114
+ } else if (isOpenAPI(schema)) {
115
+ return schema;
116
+ }
117
+ const baseVersion = parseInt(schema.swagger, 10);
118
+ if (baseVersion === 1) {
119
+ throw new Error("Swagger v1.2 is unsupported.");
120
+ }
121
+ return converter.convertObj(schema, { anchors: true }).then((options) => options.openapi);
122
+ });
123
+ }
124
+ /**
125
+ * Validate a given API definition.
126
+ *
127
+ * If supplied a Postman collection it will be converted to OpenAPI first and then run through
128
+ * standard OpenAPI validation.
106
129
  *
107
130
  */
108
- async validate(opts = { convertToLatest: false }) {
109
- const convertToLatest = opts.convertToLatest;
131
+ async validate(opts = {}) {
110
132
  const parserOptions = opts.parser || {};
111
133
  if (!parserOptions.validate) {
112
134
  parserOptions.validate = {};
113
135
  }
114
136
  parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;
115
137
  return this.load().then(async (schema) => {
116
- if (!isPostman(schema)) {
117
- return schema;
118
- }
119
- return _OASNormalize.convertPostmanToOpenAPI(schema);
138
+ return isPostman(schema) ? _OASNormalize.convertPostmanToOpenAPI(schema) : schema;
120
139
  }).then(async (schema) => {
121
140
  if (!isSwagger(schema) && !isOpenAPI(schema)) {
122
- return Promise.reject(new Error("The supplied API definition is unsupported."));
141
+ throw new Error("The supplied API definition is unsupported.");
123
142
  } else if (isSwagger(schema)) {
124
143
  const baseVersion = parseInt(schema.swagger, 10);
125
144
  if (baseVersion === 1) {
126
- return Promise.reject(new Error("Swagger v1.2 is unsupported."));
145
+ throw new Error("Swagger v1.2 is unsupported.");
127
146
  }
128
147
  }
129
148
  const clonedSchema = JSON.parse(JSON.stringify(schema));
130
149
  return openapiParser.validate(clonedSchema, parserOptions).then(() => {
131
- if (!convertToLatest || isOpenAPI(schema)) {
132
- return schema;
133
- }
134
- return converter.convertObj(schema, { anchors: true }).then((options) => options.openapi);
135
- }).catch((err) => Promise.reject(err));
150
+ return true;
151
+ });
136
152
  });
137
153
  }
138
154
  /**
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Options } from './lib/types.js';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport openapiParser from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * @private\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return Promise.resolve(this.cache.load);\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return Promise.resolve(ret);\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const resp = await fetch(utils.normalizeURL(this.file)).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n return Promise.reject(new Error('Use `opts.enablePaths` to enable accessing local files.'));\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n return Promise.reject(new Error('No file contents found.'));\n }\n return resolve(contents);\n\n default:\n return Promise.reject(new Error('Could not load this file.'));\n }\n }\n\n /**\n * @private\n */\n static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle() {\n if (this.cache.bundle) return Promise.resolve(this.cache.bundle);\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.bundle(schema))\n .then(bundle => {\n this.cache.bundle = bundle;\n return bundle;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref() {\n if (this.cache.deref) return Promise.resolve(this.cache.deref);\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Validate, and potentially convert to OpenAPI, a given API definition.\n *\n */\n async validate(\n opts: {\n /**\n * Automatically convert the supplied API definition to the latest version of OpenAPI.\n */\n convertToLatest?: boolean;\n parser?: openapiParser.Options;\n } = { convertToLatest: false },\n ): Promise<OpenAPI.Document> {\n const convertToLatest = opts.convertToLatest;\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) {\n parserOptions.validate = {};\n }\n\n parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n if (!utils.isPostman(schema)) {\n return schema;\n }\n\n return OASNormalize.convertPostmanToOpenAPI(schema);\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n return Promise.reject(new Error('The supplied API definition is unsupported.'));\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n return Promise.reject(new Error('Swagger v1.2 is unsupported.'));\n }\n }\n\n /**\n * `openapiParser.validate()` dereferences schemas at the same time as validation and does\n * not give us an option to disable this. Since all we already have a dereferencing method\n * on this library and our `validate()` method here just needs to tell us if the definition\n * is valid or not we need to clone it before passing it over to `openapi-parser` so as to\n * not run into pass-by-reference problems.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n return openapiParser\n .validate(clonedSchema, parserOptions)\n .then(() => {\n if (!convertToLatest || utils.isOpenAPI(schema)) {\n return schema;\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n })\n .catch(err => Promise.reject(err));\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification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F,KAAK;AACH,cAAI,UAAU;AACd,cAAK,QAAQ,MAAiC,QAAQ;AAIpD,kBAAM,SAAS,QAAQ,MAAgC,OAAO;AAAA,cAC5D;AAAA,YACF;AAEA,gBAAI,OAAO;AACT,wBAAU,MAAM,CAAC;AAAA,YACnB;AAAA,UACF;AAEA,iBAAO;AAAA,YACL,eAAe;AAAA,YACf;AAAA,UACF;AAAA,QAEF,KAAK;AACH,iBAAO;AAAA,YACL,eAAe;AAAA,YACf,SAAU,OAAyC;AAAA,UACrD;AAAA,QAEF;AACE,gBAAM,IAAI,MAAM,wBAAwB;AAAA,MAC5C;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Options } from './lib/types.js';\nimport type { OpenAPI, OpenAPIV2, OpenAPIV3 } from 'openapi-types';\n\nimport fs from 'node:fs';\n\nimport openapiParser from '@readme/openapi-parser';\nimport postmanToOpenAPI from '@readme/postman-to-openapi';\nimport converter from 'swagger2openapi';\n\nimport * as utils from './lib/utils.js';\n\nexport default class OASNormalize {\n cache: {\n bundle?: OpenAPI.Document | false;\n convert?: OpenAPI.Document | false;\n deref?: OpenAPI.Document | false;\n load?: Record<string, unknown> | false;\n };\n\n file: any;\n\n opts: Options;\n\n type: ReturnType<typeof utils.getType>;\n\n constructor(file: any, opts?: Options) {\n this.file = file;\n this.opts = {\n colorizeErrors: false,\n enablePaths: false,\n ...opts,\n };\n\n this.type = utils.getType(this.file);\n\n this.cache = {\n load: false,\n bundle: false,\n deref: false,\n };\n }\n\n /**\n * Load and return the API definition that `oas-normalize` was initialized with.\n *\n */\n async load(): Promise<Record<string, unknown>> {\n if (this.cache.load) return this.cache.load;\n\n const resolve = (obj: Parameters<typeof utils.stringToJSON>[0]) => {\n const ret = utils.stringToJSON(obj);\n this.cache.load = ret;\n return ret;\n };\n\n switch (this.type) {\n case 'json':\n case 'string-json':\n case 'string-yaml':\n return resolve(this.file);\n\n case 'buffer':\n return resolve(this.file.toString());\n\n case 'url':\n const { url, options } = utils.prepareURL(this.file);\n const resp = await fetch(url, options).then(res => res.text());\n return resolve(resp);\n\n case 'path':\n // Load a local file\n if (!this.opts.enablePaths) {\n throw new Error('Use `opts.enablePaths` to enable accessing local files.');\n }\n\n const contents = fs.readFileSync(this.file).toString();\n if (!contents.trim()) {\n throw new Error('No file contents found.');\n }\n return resolve(contents);\n\n default:\n throw new Error('Could not load this file.');\n }\n }\n\n private static async convertPostmanToOpenAPI(schema: any) {\n return postmanToOpenAPI(JSON.stringify(schema), undefined, { outputFormat: 'json', replaceVars: true }).then(\n JSON.parse,\n );\n }\n\n /**\n * Bundle up the given API definition, resolving any external `$ref` pointers in the process.\n *\n */\n async bundle() {\n if (this.cache.bundle) return this.cache.bundle;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to bundle we'll still\n // upconvert it to an OpenAPI definition file so our returned dataset is always one of\n // those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.bundle(schema))\n .then(bundle => {\n this.cache.bundle = bundle;\n return bundle;\n });\n }\n\n /**\n * Dereference the given API definition.\n *\n */\n async deref() {\n if (this.cache.deref) return this.cache.deref;\n\n return this.load()\n .then(schema => {\n // Though Postman collections don't support `$ref` pointers for us to dereference we'll\n // still upconvert it to an OpenAPI definition file so our returned dataset is always one\n // of those for a Postman dataset.\n if (utils.isPostman(schema)) {\n return OASNormalize.convertPostmanToOpenAPI(schema);\n }\n\n return schema;\n })\n .then(schema => openapiParser.dereference(schema))\n .then(dereferenced => {\n this.cache.deref = dereferenced;\n return dereferenced;\n });\n }\n\n /**\n * Convert a given API definition to OpenAPI if it is not already.\n *\n */\n async convert(): Promise<OpenAPI.Document> {\n if (this.cache.convert) return this.cache.convert;\n\n return this.load()\n .then(async schema => {\n // If we have a Postman collection we need to convert it to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isOpenAPI(schema)) {\n return schema;\n }\n\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n\n return converter\n .convertObj(schema, { anchors: true })\n .then((options: { openapi: OpenAPI.Document }) => options.openapi);\n });\n }\n\n /**\n * Validate a given API definition.\n *\n * If supplied a Postman collection it will be converted to OpenAPI first and then run through\n * standard OpenAPI validation.\n *\n */\n async validate(\n opts: {\n parser?: openapiParser.Options;\n } = {},\n ): Promise<true> {\n const parserOptions = opts.parser || {};\n if (!parserOptions.validate) {\n parserOptions.validate = {};\n }\n\n parserOptions.validate.colorizeErrors = this.opts.colorizeErrors;\n\n return this.load()\n .then(async schema => {\n // Because we don't have something akin to `openapi-parser` for Postman collections we just\n // always convert them to OpenAPI.\n return utils.isPostman(schema) ? OASNormalize.convertPostmanToOpenAPI(schema) : schema;\n })\n .then(async schema => {\n if (!utils.isSwagger(schema) && !utils.isOpenAPI(schema)) {\n throw new Error('The supplied API definition is unsupported.');\n } else if (utils.isSwagger(schema)) {\n const baseVersion = parseInt(schema.swagger, 10);\n if (baseVersion === 1) {\n throw new Error('Swagger v1.2 is unsupported.');\n }\n }\n\n /**\n * `openapiParser.validate()` dereferences schemas at the same time as validation, mutating\n * the supplied parameter in the process, and does not give us an option to disable this.\n * As we already have a dereferencing method on this library, and this method just needs to\n * tell us if the API definition is valid or not, we need to clone the schema before\n * supplying it to `openapi-parser`.\n */\n // eslint-disable-next-line try-catch-failsafe/json-parse\n const clonedSchema = JSON.parse(JSON.stringify(schema));\n\n return openapiParser.validate(clonedSchema, parserOptions).then(() => {\n // The API definition, whatever its format or specification, is valid.\n return true;\n });\n });\n }\n\n /**\n * Retrieve OpenAPI, Swagger, or Postman version information about the supplied API definition.\n *\n */\n async version(): Promise<{ specification: 'openapi' | 'postman' | 'swagger'; version: string | 'unknown' }> {\n return this.load().then(schema => {\n switch (utils.getAPIDefinitionType(schema)) {\n case 'openapi':\n return {\n specification: 'openapi',\n version: (schema as unknown as OpenAPIV3.Document).openapi,\n };\n\n case 'postman':\n let version = 'unknown';\n if ((schema?.info as Record<string, string>)?.schema) {\n // Though `info.schema` is required by the Postman spec there's no strictness to its\n // contents so we'll do our best to extract a version out of this schema URL that they\n // seem to usually match. If not we'll fallback to treating it as an `unknown` version.\n const match = (schema?.info as Record<string, string>).schema.match(\n /http(s?):\\/\\/schema.getpostman.com\\/json\\/collection\\/v([0-9.]+)\\//,\n );\n\n if (match) {\n version = match[2];\n }\n }\n\n return {\n specification: 'postman',\n version,\n };\n\n case 'swagger':\n return {\n specification: 'swagger',\n version: (schema as unknown as OpenAPIV2.Document).swagger,\n };\n\n default:\n throw new Error('Unknown file detected.');\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAGA,OAAO,QAAQ;AAEf,OAAO,mBAAmB;AAC1B,OAAO,sBAAsB;AAC7B,OAAO,eAAe;AAItB,IAAqB,eAArB,MAAqB,cAAa;AAAA,EAchC,YAAY,MAAW,MAAgB;AACrC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,MACV,gBAAgB;AAAA,MAChB,aAAa;AAAA,MACb,GAAG;AAAA,IACL;AAEA,SAAK,OAAa,QAAQ,KAAK,IAAI;AAEnC,SAAK,QAAQ;AAAA,MACX,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,OAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,OAAyC;AAC7C,QAAI,KAAK,MAAM,KAAM,QAAO,KAAK,MAAM;AAEvC,UAAM,UAAU,CAAC,QAAkD;AACjE,YAAM,MAAY,aAAa,GAAG;AAClC,WAAK,MAAM,OAAO;AAClB,aAAO;AAAA,IACT;AAEA,YAAQ,KAAK,MAAM;AAAA,MACjB,KAAK;AAAA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 var _chunkGZL345SRcjs = require('../chunk-GZL345SR.cjs');
12
12
 
13
13
 
14
14
 
@@ -19,5 +19,5 @@ var _chunkK75HC34Mcjs = require('../chunk-K75HC34M.cjs');
19
19
 
20
20
 
21
21
 
22
- exports.getAPIDefinitionType = _chunkK75HC34Mcjs.getAPIDefinitionType; exports.getType = _chunkK75HC34Mcjs.getType; exports.isAPIDefinition = _chunkK75HC34Mcjs.isAPIDefinition; exports.isBuffer = _chunkK75HC34Mcjs.isBuffer; exports.isOpenAPI = _chunkK75HC34Mcjs.isOpenAPI; exports.isPostman = _chunkK75HC34Mcjs.isPostman; exports.isSwagger = _chunkK75HC34Mcjs.isSwagger; exports.normalizeURL = _chunkK75HC34Mcjs.normalizeURL; exports.stringToJSON = _chunkK75HC34Mcjs.stringToJSON;
22
+ exports.getAPIDefinitionType = _chunkGZL345SRcjs.getAPIDefinitionType; exports.getType = _chunkGZL345SRcjs.getType; exports.isAPIDefinition = _chunkGZL345SRcjs.isAPIDefinition; exports.isBuffer = _chunkGZL345SRcjs.isBuffer; exports.isOpenAPI = _chunkGZL345SRcjs.isOpenAPI; exports.isPostman = _chunkGZL345SRcjs.isPostman; exports.isSwagger = _chunkGZL345SRcjs.isSwagger; exports.prepareURL = _chunkGZL345SRcjs.prepareURL; exports.stringToJSON = _chunkGZL345SRcjs.stringToJSON;
23
23
  //# sourceMappingURL=utils.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,geAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"}
1
+ {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,yDAA8B;AAC9B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,4dAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/lib/utils.cjs"}
@@ -4,9 +4,13 @@
4
4
  */
5
5
  declare function isBuffer(obj: any): boolean;
6
6
  /**
7
- * Converts GitHub blob URLs to raw URLs
7
+ * Deconstruct a URL into a payload for a `fetch` request.
8
+ *
8
9
  */
9
- declare function normalizeURL(url: string): string;
10
+ declare function prepareURL(url: string): {
11
+ url: string;
12
+ options: RequestInit;
13
+ };
10
14
  /**
11
15
  * Determine the type of a given variable. Returns `false` if unrecognized.
12
16
  *
@@ -50,4 +54,4 @@ declare function isAPIDefinition(schema: Record<string, unknown>): boolean;
50
54
  */
51
55
  declare function getAPIDefinitionType(schema: Record<string, unknown>): "openapi" | "postman" | "swagger" | "unknown";
52
56
 
53
- export { getAPIDefinitionType, getType, isAPIDefinition, isBuffer, isOpenAPI, isPostman, isSwagger, normalizeURL, stringToJSON };
57
+ export { getAPIDefinitionType, getType, isAPIDefinition, isBuffer, isOpenAPI, isPostman, isSwagger, prepareURL, stringToJSON };
@@ -4,9 +4,13 @@
4
4
  */
5
5
  declare function isBuffer(obj: any): boolean;
6
6
  /**
7
- * Converts GitHub blob URLs to raw URLs
7
+ * Deconstruct a URL into a payload for a `fetch` request.
8
+ *
8
9
  */
9
- declare function normalizeURL(url: string): string;
10
+ declare function prepareURL(url: string): {
11
+ url: string;
12
+ options: RequestInit;
13
+ };
10
14
  /**
11
15
  * Determine the type of a given variable. Returns `false` if unrecognized.
12
16
  *
@@ -50,4 +54,4 @@ declare function isAPIDefinition(schema: Record<string, unknown>): boolean;
50
54
  */
51
55
  declare function getAPIDefinitionType(schema: Record<string, unknown>): "openapi" | "postman" | "swagger" | "unknown";
52
56
 
53
- export { getAPIDefinitionType, getType, isAPIDefinition, isBuffer, isOpenAPI, isPostman, isSwagger, normalizeURL, stringToJSON };
57
+ export { getAPIDefinitionType, getType, isAPIDefinition, isBuffer, isOpenAPI, isPostman, isSwagger, prepareURL, stringToJSON };
package/dist/lib/utils.js CHANGED
@@ -6,9 +6,9 @@ import {
6
6
  isOpenAPI,
7
7
  isPostman,
8
8
  isSwagger,
9
- normalizeURL,
9
+ prepareURL,
10
10
  stringToJSON
11
- } from "../chunk-XOS5M44Y.js";
11
+ } from "../chunk-J322YOXV.js";
12
12
  export {
13
13
  getAPIDefinitionType,
14
14
  getType,
@@ -17,7 +17,7 @@ export {
17
17
  isOpenAPI,
18
18
  isPostman,
19
19
  isSwagger,
20
- normalizeURL,
20
+ prepareURL,
21
21
  stringToJSON
22
22
  };
23
23
  //# sourceMappingURL=utils.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oas-normalize",
3
- "version": "11.1.4",
3
+ "version": "12.1.0",
4
4
  "description": "Tooling for converting, validating, and parsing OpenAPI, Swagger, and Postman API definitions",
5
5
  "type": "module",
6
6
  "exports": {
@@ -53,6 +53,7 @@
53
53
  },
54
54
  "scripts": {
55
55
  "attw": "attw --pack --format table-flipped",
56
+ "bench": "echo 'Please run benchmarks from the root!' && exit 1",
56
57
  "build": "tsup",
57
58
  "lint": "npm run lint:types && npm run lint:js",
58
59
  "lint:js": "eslint . --ext .js,.ts --ignore-path ../../.gitignore",
@@ -63,7 +64,7 @@
63
64
  },
64
65
  "license": "MIT",
65
66
  "dependencies": {
66
- "@readme/openapi-parser": "^2.6.0",
67
+ "@readme/openapi-parser": "^2.7.0",
67
68
  "@readme/postman-to-openapi": "^4.1.0",
68
69
  "js-yaml": "^4.1.0",
69
70
  "openapi-types": "^12.1.3",
@@ -74,11 +75,11 @@
74
75
  "@types/js-yaml": "^4.0.9",
75
76
  "@types/swagger2openapi": "^7.0.4",
76
77
  "eslint": "^8.57.0",
77
- "nock": "^14.0.0-beta.12",
78
+ "nock": "^14.0.0",
78
79
  "tsup": "^8.0.2",
79
80
  "typescript": "^5.1.6",
80
- "vitest": "^2.1.3"
81
+ "vitest": "^3.0.4"
81
82
  },
82
83
  "prettier": "@readme/eslint-config/prettier",
83
- "gitHead": "d711a5f5b1fe655567e96e6940c52410dcb10e56"
84
+ "gitHead": "815ed445419978add2aaec344aa876f8914d9fb6"
84
85
  }
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-K75HC34M.cjs","../src/lib/utils.ts"],"names":[],"mappings":"AAAA;ACAA,iFAAkC;AAM3B,SAAS,QAAA,CAAS,GAAA,EAAU;AACjC,EAAA,OACE,IAAA,GAAO,KAAA,GACP,GAAA,CAAI,YAAA,GAAe,KAAA,GACnB,OAAO,GAAA,CAAI,WAAA,CAAY,SAAA,IAAa,WAAA,GACpC,CAAC,CAAC,GAAA,CAAI,WAAA,CAAY,QAAA,CAAS,GAAG,CAAA;AAElC;AAKO,SAAS,YAAA,CAAa,GAAA,EAAa;AACxC,EAAA,GAAA,CAAI,GAAA,CAAI,UAAA,CAAW,qBAAqB,EAAA,GAAK,GAAA,CAAI,QAAA,CAAS,QAAQ,CAAA,EAAG;AACnE,IAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,YAAA,EAAc,2BAA2B,CAAA,CAAE,OAAA,CAAQ,QAAA,EAAU,GAAG,CAAA;AAAA,EACrF;AACA,EAAA,OAAO,GAAA;AACT;AAMO,SAAS,OAAA,CAAQ,GAAA,EAAU;AAChC,EAAA,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,EAAG;AACjB,IAAA,OAAO,QAAA;AAAA,EACT,EAAA,KAAA,GAAA,CAAW,OAAO,IAAA,IAAQ,QAAA,EAAU;AAClC,IAAA,OAAO,MAAA;AAAA,EACT,EAAA,KAAA,GAAA,CAAW,OAAO,IAAA,IAAQ,QAAA,EAAU;AAClC,IAAA,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,MAAM,CAAA,EAAG;AACrB,MAAA,OAAO,aAAA;AAAA,IACT,E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;AAAA,EACT,EAAA,KAAA,GAAA,CAAW,SAAA,CAAU,MAAM,CAAA,EAAG;AAC5B,IAAA,OAAO,SAAA;AAAA,EACT,EAAA,KAAA,GAAA,CAAW,SAAA,CAAU,MAAM,CAAA,EAAG;AAC5B,IAAA,OAAO,SAAA;AAAA,EACT;AAEA,EAAA,OAAO,SAAA;AACT;AD5DA;AACA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,8TAAC","file":"/Users/erunion/code/readme/oas/packages/oas-normalize/dist/chunk-K75HC34M.cjs","sourcesContent":[null,"import YAML, { JSON_SCHEMA } from 'js-yaml';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any) {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Converts GitHub blob URLs to raw URLs\n */\nexport function normalizeURL(url: string) {\n if (url.startsWith('https://github.com/') && url.includes('/blob/')) {\n return url.replace('github.com', 'raw.githubusercontent.com').replace('/blob/', '/');\n }\n return url;\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any) {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>) {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>) {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>) {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>) {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman';\n } else if (isSwagger(schema)) {\n return 'swagger';\n }\n\n return 'unknown';\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/utils.ts"],"sourcesContent":["import YAML, { JSON_SCHEMA } from 'js-yaml';\n\n/**\n * Determine if a given variable is a `Buffer`.\n *\n */\nexport function isBuffer(obj: any) {\n return (\n obj != null &&\n obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' &&\n !!obj.constructor.isBuffer(obj)\n );\n}\n\n/**\n * Converts GitHub blob URLs to raw URLs\n */\nexport function normalizeURL(url: string) {\n if (url.startsWith('https://github.com/') && url.includes('/blob/')) {\n return url.replace('github.com', 'raw.githubusercontent.com').replace('/blob/', '/');\n }\n return url;\n}\n\n/**\n * Determine the type of a given variable. Returns `false` if unrecognized.\n *\n */\nexport function getType(obj: any) {\n if (isBuffer(obj)) {\n return 'buffer';\n } else if (typeof obj === 'object') {\n return 'json';\n } else if (typeof obj === 'string') {\n if (obj.match(/\\s*{/)) {\n return 'string-json';\n } else if (obj.match(/\\n/)) {\n // Not sure about this...\n return 'string-yaml';\n } else if (obj.substring(0, 4) === 'http') {\n return 'url';\n }\n\n return 'path';\n }\n\n return false;\n}\n\n/**\n * Determine if a given schema if an OpenAPI definition.\n *\n */\nexport function isOpenAPI(schema: Record<string, unknown>) {\n return !!schema.openapi;\n}\n\n/**\n * Determine if a given schema is a Postman collection.\n *\n * Unfortunately the Postman schema spec doesn't have anything like `openapi` or `swagger` for us\n * to look at but it does require that `info` and `item` be present and as `item` doesn't exist in\n * OpenAPI or Swagger we can use the combination of those two properties to determine if what we\n * have is a Postman collection.\n *\n * @see {@link https://schema.postman.com/json/collection/v2.0.0/collection.json}\n * @see {@link https://schema.postman.com/json/collection/v2.1.0/collection.json}\n */\nexport function isPostman(schema: Record<string, unknown>): boolean {\n return !!schema.info && !!schema.item;\n}\n\n/**\n * Determine if a given schema if an Swagger definition.\n *\n */\nexport function isSwagger(schema: Record<string, unknown>) {\n return !!schema.swagger;\n}\n\n/**\n * Convert a YAML blob or stringified JSON object into a JSON object.\n *\n */\nexport function stringToJSON(string: Record<string, unknown> | string): Record<string, unknown> {\n if (typeof string === 'object') {\n return string;\n } else if (string.match(/^\\s*{/)) {\n // eslint-disable-next-line try-catch-failsafe/json-parse\n return JSON.parse(string);\n }\n\n return YAML.load(string, { schema: JSON_SCHEMA }) as Record<string, unknown>;\n}\n\n/**\n * Determine if a given schema is an API definition that we can support.\n *\n */\nexport function isAPIDefinition(schema: Record<string, unknown>) {\n return isOpenAPI(schema) || isPostman(schema) || isSwagger(schema);\n}\n\n/**\n * Retrieve the type of API definition that a given schema is.\n *\n */\nexport function getAPIDefinitionType(schema: Record<string, unknown>) {\n if (isOpenAPI(schema)) {\n return 'openapi';\n } else if (isPostman(schema)) {\n return 'postman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