@hey-api/json-schema-ref-parser 1.2.3 → 1.3.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.
Files changed (92) hide show
  1. package/README.md +9 -84
  2. package/dist/index.d.mts +629 -0
  3. package/dist/index.d.mts.map +1 -0
  4. package/dist/index.mjs +1887 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/package.json +42 -78
  7. package/src/__tests__/bundle.test.ts +59 -0
  8. package/src/__tests__/index.test.ts +43 -0
  9. package/src/__tests__/pointer.test.ts +34 -0
  10. package/src/__tests__/utils.ts +3 -0
  11. package/{lib → src}/bundle.ts +143 -229
  12. package/{lib → src}/dereference.ts +20 -43
  13. package/{lib → src}/index.ts +103 -125
  14. package/{lib → src}/options.ts +13 -9
  15. package/{lib → src}/parse.ts +19 -15
  16. package/src/parsers/binary.ts +13 -0
  17. package/{lib → src}/parsers/json.ts +5 -6
  18. package/src/parsers/text.ts +21 -0
  19. package/{lib → src}/parsers/yaml.ts +9 -9
  20. package/{lib → src}/pointer.ts +42 -23
  21. package/{lib → src}/ref.ts +25 -21
  22. package/{lib → src}/refs.ts +23 -26
  23. package/{lib → src}/resolve-external.ts +91 -60
  24. package/{lib → src}/resolvers/file.ts +7 -10
  25. package/{lib → src}/resolvers/url.ts +12 -8
  26. package/{lib → src}/types/index.ts +9 -2
  27. package/src/util/convert-path-to-posix.ts +8 -0
  28. package/{lib → src}/util/errors.ts +38 -36
  29. package/{lib → src}/util/is-windows.ts +1 -1
  30. package/{lib → src}/util/plugins.ts +7 -8
  31. package/{lib → src}/util/url.ts +41 -42
  32. package/dist/lib/__tests__/bundle.test.d.ts +0 -1
  33. package/dist/lib/__tests__/bundle.test.js +0 -50
  34. package/dist/lib/__tests__/index.test.d.ts +0 -1
  35. package/dist/lib/__tests__/index.test.js +0 -43
  36. package/dist/lib/__tests__/pointer.test.d.ts +0 -1
  37. package/dist/lib/__tests__/pointer.test.js +0 -27
  38. package/dist/lib/bundle.d.ts +0 -26
  39. package/dist/lib/bundle.js +0 -600
  40. package/dist/lib/dereference.d.ts +0 -11
  41. package/dist/lib/dereference.js +0 -226
  42. package/dist/lib/index.d.ts +0 -92
  43. package/dist/lib/index.js +0 -525
  44. package/dist/lib/options.d.ts +0 -61
  45. package/dist/lib/options.js +0 -45
  46. package/dist/lib/parse.d.ts +0 -13
  47. package/dist/lib/parse.js +0 -87
  48. package/dist/lib/parsers/binary.d.ts +0 -2
  49. package/dist/lib/parsers/binary.js +0 -12
  50. package/dist/lib/parsers/json.d.ts +0 -2
  51. package/dist/lib/parsers/json.js +0 -38
  52. package/dist/lib/parsers/text.d.ts +0 -2
  53. package/dist/lib/parsers/text.js +0 -18
  54. package/dist/lib/parsers/yaml.d.ts +0 -2
  55. package/dist/lib/parsers/yaml.js +0 -28
  56. package/dist/lib/pointer.d.ts +0 -88
  57. package/dist/lib/pointer.js +0 -297
  58. package/dist/lib/ref.d.ts +0 -180
  59. package/dist/lib/ref.js +0 -226
  60. package/dist/lib/refs.d.ts +0 -127
  61. package/dist/lib/refs.js +0 -232
  62. package/dist/lib/resolve-external.d.ts +0 -13
  63. package/dist/lib/resolve-external.js +0 -151
  64. package/dist/lib/resolvers/file.d.ts +0 -6
  65. package/dist/lib/resolvers/file.js +0 -61
  66. package/dist/lib/resolvers/url.d.ts +0 -17
  67. package/dist/lib/resolvers/url.js +0 -62
  68. package/dist/lib/types/index.d.ts +0 -43
  69. package/dist/lib/types/index.js +0 -2
  70. package/dist/lib/util/convert-path-to-posix.d.ts +0 -1
  71. package/dist/lib/util/convert-path-to-posix.js +0 -14
  72. package/dist/lib/util/errors.d.ts +0 -56
  73. package/dist/lib/util/errors.js +0 -112
  74. package/dist/lib/util/is-windows.d.ts +0 -1
  75. package/dist/lib/util/is-windows.js +0 -6
  76. package/dist/lib/util/plugins.d.ts +0 -16
  77. package/dist/lib/util/plugins.js +0 -45
  78. package/dist/lib/util/url.d.ts +0 -79
  79. package/dist/lib/util/url.js +0 -285
  80. package/dist/vite.config.d.ts +0 -2
  81. package/dist/vite.config.js +0 -19
  82. package/lib/__tests__/bundle.test.ts +0 -52
  83. package/lib/__tests__/index.test.ts +0 -45
  84. package/lib/__tests__/pointer.test.ts +0 -26
  85. package/lib/__tests__/spec/circular-ref-with-description.json +0 -11
  86. package/lib/__tests__/spec/multiple-refs.json +0 -34
  87. package/lib/__tests__/spec/openapi-paths-ref.json +0 -46
  88. package/lib/__tests__/spec/path-parameter.json +0 -16
  89. package/lib/parsers/binary.ts +0 -13
  90. package/lib/parsers/text.ts +0 -21
  91. package/lib/util/convert-path-to-posix.ts +0 -11
  92. /package/{LICENSE → LICENSE.md} +0 -0
package/dist/lib/refs.js DELETED
@@ -1,232 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- const ono_1 = require("@jsdevtools/ono");
40
- const ref_js_1 = __importDefault(require("./ref.js"));
41
- const url = __importStar(require("./util/url.js"));
42
- const convert_path_to_posix_1 = __importDefault(require("./util/convert-path-to-posix"));
43
- /**
44
- * When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of $RefParser objects.
45
- *
46
- * This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References.
47
- *
48
- * See https://apitools.dev/json-schema-ref-parser/docs/refs.html
49
- */
50
- class $Refs {
51
- /**
52
- * Returns the paths/URLs of all the files in your schema (including the main schema file).
53
- *
54
- * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#pathstypes
55
- *
56
- * @param types (optional) Optionally only return certain types of paths ("file", "http", etc.)
57
- */
58
- paths(...types) {
59
- const paths = getPaths(this._$refs, types.flat());
60
- return paths.map((path) => {
61
- return (0, convert_path_to_posix_1.default)(path.decoded);
62
- });
63
- }
64
- /**
65
- * Returns a map of paths/URLs and their correspond values.
66
- *
67
- * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#valuestypes
68
- *
69
- * @param types (optional) Optionally only return values from certain locations ("file", "http", etc.)
70
- */
71
- values(...types) {
72
- const $refs = this._$refs;
73
- const paths = getPaths($refs, types.flat());
74
- return paths.reduce((obj, path) => {
75
- obj[(0, convert_path_to_posix_1.default)(path.decoded)] = $refs[path.encoded].value;
76
- return obj;
77
- }, {});
78
- }
79
- /**
80
- * Returns `true` if the given path exists in the schema; otherwise, returns `false`
81
- *
82
- * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#existsref
83
- *
84
- * @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
85
- */
86
- /**
87
- * Determines whether the given JSON reference exists.
88
- *
89
- * @param path - The path being resolved, optionally with a JSON pointer in the hash
90
- * @param [options]
91
- * @returns
92
- */
93
- exists(path, options) {
94
- try {
95
- this._resolve(path, "", options);
96
- return true;
97
- }
98
- catch {
99
- return false;
100
- }
101
- }
102
- /**
103
- * Resolves the given JSON reference and returns the resolved value.
104
- *
105
- * @param path - The path being resolved, with a JSON pointer in the hash
106
- * @param [options]
107
- * @returns - Returns the resolved value
108
- */
109
- get(path, options) {
110
- return this._resolve(path, "", options).value;
111
- }
112
- /**
113
- * Sets the value at the given path in the schema. If the property, or any of its parents, don't exist, they will be created.
114
- *
115
- * @param path The JSON Reference path, optionally with a JSON Pointer in the hash
116
- * @param value The value to assign. Can be anything (object, string, number, etc.)
117
- */
118
- set(path, value) {
119
- const absPath = url.resolve(this._root$Ref.path, path);
120
- const withoutHash = url.stripHash(absPath);
121
- const $ref = this._$refs[withoutHash];
122
- if (!$ref) {
123
- throw (0, ono_1.ono)(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
124
- }
125
- $ref.set(absPath, value);
126
- }
127
- /**
128
- * Returns the specified {@link $Ref} object, or undefined.
129
- *
130
- * @param path - The path being resolved, optionally with a JSON pointer in the hash
131
- * @returns
132
- * @protected
133
- */
134
- _get$Ref(path) {
135
- path = url.resolve(this._root$Ref.path, path);
136
- const withoutHash = url.stripHash(path);
137
- return this._$refs[withoutHash];
138
- }
139
- /**
140
- * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.
141
- *
142
- * @param path - The file path or URL of the referenced file
143
- */
144
- _add(path) {
145
- const withoutHash = url.stripHash(path);
146
- const $ref = new ref_js_1.default(this);
147
- $ref.path = withoutHash;
148
- this._$refs[withoutHash] = $ref;
149
- this._root$Ref = this._root$Ref || $ref;
150
- return $ref;
151
- }
152
- /**
153
- * Resolves the given JSON reference.
154
- *
155
- * @param path - The path being resolved, optionally with a JSON pointer in the hash
156
- * @param pathFromRoot - The path of `obj` from the schema root
157
- * @param [options]
158
- * @returns
159
- * @protected
160
- */
161
- _resolve(path, pathFromRoot, options) {
162
- const absPath = url.resolve(this._root$Ref.path, path);
163
- const withoutHash = url.stripHash(absPath);
164
- const $ref = this._$refs[withoutHash];
165
- if (!$ref) {
166
- throw (0, ono_1.ono)(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
167
- }
168
- return $ref.resolve(absPath, options, path, pathFromRoot);
169
- }
170
- constructor() {
171
- /**
172
- * A map of paths/urls to {@link $Ref} objects
173
- *
174
- * @type {object}
175
- * @protected
176
- */
177
- this._$refs = {};
178
- /**
179
- * Returns the paths of all the files/URLs that are referenced by the JSON schema,
180
- * including the schema itself.
181
- *
182
- * @param [types] - Only return paths of the given types ("file", "http", etc.)
183
- * @returns
184
- */
185
- /**
186
- * Returns the map of JSON references and their resolved values.
187
- *
188
- * @param [types] - Only return references of the given types ("file", "http", etc.)
189
- * @returns
190
- */
191
- /**
192
- * Returns a POJO (plain old JavaScript object) for serialization as JSON.
193
- *
194
- * @returns {object}
195
- */
196
- this.toJSON = this.values;
197
- /**
198
- * Indicates whether the schema contains any circular references.
199
- *
200
- * @type {boolean}
201
- */
202
- this.circular = false;
203
- this._$refs = {};
204
- // @ts-ignore
205
- this._root$Ref = null;
206
- }
207
- }
208
- exports.default = $Refs;
209
- /**
210
- * Returns the encoded and decoded paths keys of the given object.
211
- *
212
- * @param $refs - The object whose keys are URL-encoded paths
213
- * @param [types] - Only return paths of the given types ("file", "http", etc.)
214
- * @returns
215
- */
216
- function getPaths($refs, types) {
217
- let paths = Object.keys($refs);
218
- // Filter the paths by type
219
- types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
220
- if (types.length > 0 && types[0]) {
221
- paths = paths.filter((key) => {
222
- return types.includes($refs[key].pathType);
223
- });
224
- }
225
- // Decode local filesystem paths
226
- return paths.map((path) => {
227
- return {
228
- encoded: path,
229
- decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path,
230
- };
231
- });
232
- }
@@ -1,13 +0,0 @@
1
- import type { $RefParserOptions } from "./options.js";
2
- import type { $RefParser } from "./index.js";
3
- /**
4
- * Crawls the JSON schema, finds all external JSON references, and resolves their values.
5
- * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.
6
- *
7
- * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.
8
- *
9
- * @returns
10
- * The promise resolves once all JSON references in the schema have been resolved,
11
- * including nested references that are contained in externally-referenced files.
12
- */
13
- export declare function resolveExternal(parser: $RefParser, options: $RefParserOptions): Promise<any[]>;
@@ -1,151 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.resolveExternal = resolveExternal;
40
- const ref_js_1 = __importDefault(require("./ref.js"));
41
- const pointer_js_1 = __importDefault(require("./pointer.js"));
42
- const parse_js_1 = require("./parse.js");
43
- const url = __importStar(require("./util/url.js"));
44
- const index_js_1 = require("./index.js");
45
- const errors_js_1 = require("./util/errors.js");
46
- const file_js_1 = require("./resolvers/file.js");
47
- const url_js_1 = require("./resolvers/url.js");
48
- /**
49
- * Crawls the JSON schema, finds all external JSON references, and resolves their values.
50
- * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.
51
- *
52
- * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.
53
- *
54
- * @returns
55
- * The promise resolves once all JSON references in the schema have been resolved,
56
- * including nested references that are contained in externally-referenced files.
57
- */
58
- function resolveExternal(parser, options) {
59
- try {
60
- // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
61
- const promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options);
62
- return Promise.all(promises);
63
- }
64
- catch (e) {
65
- return Promise.reject(e);
66
- }
67
- }
68
- /**
69
- * Recursively crawls the given value, and resolves any external JSON references.
70
- *
71
- * @param obj - The value to crawl. If it's not an object or array, it will be ignored.
72
- * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash
73
- * @param {boolean} external - Whether `obj` was found in an external document.
74
- * @param $refs
75
- * @param options
76
- * @param seen - Internal.
77
- *
78
- * @returns
79
- * Returns an array of promises. There will be one promise for each JSON reference in `obj`.
80
- * If `obj` does not contain any JSON references, then the array will be empty.
81
- * If any of the JSON references point to files that contain additional JSON references,
82
- * then the corresponding promise will internally reference an array of promises.
83
- */
84
- function crawl(obj, path, $refs, options, seen, external) {
85
- seen || (seen = new Set());
86
- let promises = [];
87
- if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {
88
- seen.add(obj); // Track previously seen objects to avoid infinite recursion
89
- if (ref_js_1.default.isExternal$Ref(obj)) {
90
- promises.push(resolve$Ref(obj, path, $refs, options));
91
- }
92
- const keys = Object.keys(obj);
93
- for (const key of keys) {
94
- const keyPath = pointer_js_1.default.join(path, key);
95
- const value = obj[key];
96
- promises = promises.concat(crawl(value, keyPath, $refs, options, seen, external));
97
- }
98
- }
99
- return promises;
100
- }
101
- /**
102
- * Resolves the given JSON Reference, and then crawls the resulting value.
103
- *
104
- * @param $ref - The JSON Reference to resolve
105
- * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash
106
- * @param $refs
107
- * @param options
108
- *
109
- * @returns
110
- * The promise resolves once all JSON references in the object have been resolved,
111
- * including nested references that are contained in externally-referenced files.
112
- */
113
- async function resolve$Ref($ref, path, $refs, options) {
114
- const resolvedPath = url.resolve(path, $ref.$ref);
115
- const withoutHash = url.stripHash(resolvedPath);
116
- // $ref.$ref = url.relative($refs._root$Ref.path, resolvedPath);
117
- // If this ref points back to an input source we've already merged, avoid re-importing
118
- // by checking if the path (without hash) matches a known source in parser and we can serve it internally later.
119
- // We keep normal flow but ensure cache hit if already added.
120
- // Do we already have this $ref?
121
- const ref = $refs._$refs[withoutHash];
122
- if (ref) {
123
- // We've already parsed this $ref, so crawl it to resolve its own externals
124
- const promises = crawl(ref.value, `${withoutHash}#`, $refs, options, new Set(), true);
125
- return Promise.all(promises);
126
- }
127
- // Parse the $referenced file/url
128
- const file = (0, parse_js_1.newFile)(resolvedPath);
129
- // Add a new $Ref for this file, even though we don't have the value yet.
130
- // This ensures that we don't simultaneously read & parse the same file multiple times
131
- const $refAdded = $refs._add(file.url);
132
- try {
133
- const resolvedInput = (0, index_js_1.getResolvedInput)({ pathOrUrlOrSchema: resolvedPath });
134
- $refAdded.pathType = resolvedInput.type;
135
- let promises = [];
136
- if (resolvedInput.type !== "json") {
137
- const resolver = resolvedInput.type === "file" ? file_js_1.fileResolver : url_js_1.urlResolver;
138
- await resolver.handler({ file });
139
- const parseResult = await (0, parse_js_1.parseFile)(file, options);
140
- $refAdded.value = parseResult.result;
141
- promises = crawl(parseResult.result, `${withoutHash}#`, $refs, options, new Set(), true);
142
- }
143
- return Promise.all(promises);
144
- }
145
- catch (err) {
146
- if ((0, errors_js_1.isHandledError)(err)) {
147
- $refAdded.value = err;
148
- }
149
- throw err;
150
- }
151
- }
@@ -1,6 +0,0 @@
1
- import type { FileInfo } from "../types/index.js";
2
- export declare const fileResolver: {
3
- handler: ({ file, }: {
4
- file: FileInfo;
5
- }) => Promise<void>;
6
- };
@@ -1,61 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.fileResolver = void 0;
40
- const fs_1 = __importDefault(require("fs"));
41
- const ono_1 = require("@jsdevtools/ono");
42
- const url = __importStar(require("../util/url.js"));
43
- const errors_js_1 = require("../util/errors.js");
44
- exports.fileResolver = {
45
- handler: async ({ file, }) => {
46
- let path;
47
- try {
48
- path = url.toFileSystemPath(file.url);
49
- }
50
- catch (error) {
51
- throw new errors_js_1.ResolverError(ono_1.ono.uri(error, `Malformed URI: ${file.url}`), file.url);
52
- }
53
- try {
54
- const data = await fs_1.default.promises.readFile(path);
55
- file.data = data;
56
- }
57
- catch (error) {
58
- throw new errors_js_1.ResolverError((0, ono_1.ono)(error, `Error opening file "${path}"`), path);
59
- }
60
- },
61
- };
@@ -1,17 +0,0 @@
1
- import type { FileInfo } from "../types/index.js";
2
- export declare const sendRequest: ({ fetchOptions, redirects, timeout, url, }: {
3
- fetchOptions?: RequestInit;
4
- redirects?: string[];
5
- timeout?: number;
6
- url: URL | string;
7
- }) => Promise<{
8
- fetchOptions?: RequestInit;
9
- response: Response;
10
- }>;
11
- export declare const urlResolver: {
12
- handler: ({ arrayBuffer, fetch: _fetch, file, }: {
13
- arrayBuffer?: ArrayBuffer;
14
- fetch?: RequestInit;
15
- file: FileInfo;
16
- }) => Promise<void>;
17
- };
@@ -1,62 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.urlResolver = exports.sendRequest = void 0;
4
- const ono_1 = require("@jsdevtools/ono");
5
- const url_js_1 = require("../util/url.js");
6
- const errors_js_1 = require("../util/errors.js");
7
- const sendRequest = async ({ fetchOptions, redirects = [], timeout = 60000, url, }) => {
8
- url = new URL(url);
9
- redirects.push(url.href);
10
- const controller = new AbortController();
11
- const timeoutId = setTimeout(() => {
12
- controller.abort();
13
- }, timeout);
14
- const response = await fetch(url, {
15
- signal: controller.signal,
16
- ...fetchOptions,
17
- });
18
- clearTimeout(timeoutId);
19
- if (response.status >= 300 && response.status <= 399) {
20
- if (redirects.length > 5) {
21
- throw new errors_js_1.ResolverError((0, ono_1.ono)({ status: response.status }, `Error requesting ${redirects[0]}. \nToo many redirects: \n ${redirects.join(" \n ")}`));
22
- }
23
- if (!("location" in response.headers) || !response.headers.location) {
24
- throw (0, ono_1.ono)({ status: response.status }, `HTTP ${response.status} redirect with no location header`);
25
- }
26
- return (0, exports.sendRequest)({
27
- fetchOptions,
28
- redirects,
29
- timeout,
30
- url: (0, url_js_1.resolve)(url.href, response.headers.location),
31
- });
32
- }
33
- return { fetchOptions, response };
34
- };
35
- exports.sendRequest = sendRequest;
36
- exports.urlResolver = {
37
- handler: async ({ arrayBuffer, fetch: _fetch, file, }) => {
38
- let data = arrayBuffer;
39
- if (!data) {
40
- try {
41
- const { fetchOptions, response } = await (0, exports.sendRequest)({
42
- fetchOptions: {
43
- method: 'GET',
44
- ..._fetch,
45
- },
46
- url: file.url,
47
- });
48
- if (response.status >= 400) {
49
- // gracefully handle HEAD method not allowed
50
- if (response.status !== 405 || fetchOptions?.method !== 'HEAD') {
51
- throw (0, ono_1.ono)({ status: response.status }, `HTTP ERROR ${response.status}`);
52
- }
53
- }
54
- data = response.body ? await response.arrayBuffer() : new ArrayBuffer(0);
55
- }
56
- catch (error) {
57
- throw new errors_js_1.ResolverError((0, ono_1.ono)(error, `Error requesting ${file.url}`), file.url);
58
- }
59
- }
60
- file.data = Buffer.from(data);
61
- },
62
- };
@@ -1,43 +0,0 @@
1
- import type { JSONSchema4, JSONSchema4Object, JSONSchema6, JSONSchema6Object, JSONSchema7, JSONSchema7Object } from "json-schema";
2
- export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7;
3
- export type JSONSchemaObject = JSONSchema4Object | JSONSchema6Object | JSONSchema7Object;
4
- export interface Plugin {
5
- /**
6
- * Can this parser be used to process this file?
7
- */
8
- canHandle: (file: FileInfo) => boolean;
9
- /**
10
- * This is where the real work of a parser happens. The `parse` method accepts the same file info object as the `canHandle` function, but rather than returning a boolean value, the `parse` method should return a JavaScript representation of the file contents. For our CSV parser, that is a two-dimensional array of lines and values. For your parser, it might be an object, a string, a custom class, or anything else.
11
- *
12
- * Unlike the `canHandle` function, the `parse` method can also be asynchronous. This might be important if your parser needs to retrieve data from a database or if it relies on an external HTTP service to return the parsed value. You can return your asynchronous value via a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a Node.js-style error-first callback. Here are examples of both approaches:
13
- */
14
- handler: (file: FileInfo) => string | Buffer | JSONSchema | Promise<{
15
- data: Buffer;
16
- }> | Promise<string | Buffer | JSONSchema>;
17
- name: 'binary' | 'file' | 'http' | 'json' | 'text' | 'yaml';
18
- }
19
- /**
20
- * JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canHandle()`, `read()`, `canHandle()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed.
21
- *
22
- * The file info object currently only consists of a few properties, but it may grow in the future if plug-ins end up needing more information.
23
- *
24
- * See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
25
- */
26
- export interface FileInfo {
27
- /**
28
- * The raw file contents, in whatever form they were returned by the resolver that read the file.
29
- */
30
- data: string | Buffer;
31
- /**
32
- * The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
33
- */
34
- extension: string;
35
- /**
36
- * The hash (URL fragment) of the file URL, including the # symbol. If the URL doesn't have a hash, then this will be an empty string.
37
- */
38
- hash: string;
39
- /**
40
- * The full URL of the file. This could be any type of URL, including "http://", "https://", "file://", "ftp://", "mongodb://", or even a local filesystem path (when running in Node.js).
41
- */
42
- url: string;
43
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1 +0,0 @@
1
- export default function convertPathToPosix(filePath: string): string;
@@ -1,14 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.default = convertPathToPosix;
7
- const path_1 = __importDefault(require("path"));
8
- function convertPathToPosix(filePath) {
9
- const isExtendedLengthPath = filePath.startsWith("\\\\?\\");
10
- if (isExtendedLengthPath) {
11
- return filePath;
12
- }
13
- return filePath.split(path_1.default?.win32?.sep).join(path_1.default?.posix?.sep ?? "/");
14
- }
@@ -1,56 +0,0 @@
1
- import type { $RefParser } from "../index.js";
2
- import type { JSONSchema } from "../types/index.js";
3
- export type JSONParserErrorType = "EUNKNOWN" | "EPARSER" | "EUNMATCHEDPARSER" | "ETIMEOUT" | "ERESOLVER" | "EUNMATCHEDRESOLVER" | "EMISSINGPOINTER" | "EINVALIDPOINTER";
4
- export declare class JSONParserError extends Error {
5
- readonly name: string;
6
- readonly message: string;
7
- source: string | undefined;
8
- path: Array<string | number> | null;
9
- readonly code: JSONParserErrorType;
10
- constructor(message: string, source?: string);
11
- get footprint(): string;
12
- }
13
- export declare class JSONParserErrorGroup<S extends object = JSONSchema> extends Error {
14
- files: $RefParser;
15
- constructor(parser: $RefParser);
16
- static getParserErrors<S extends object = JSONSchema>(parser: $RefParser): JSONParserError[];
17
- get errors(): Array<JSONParserError | InvalidPointerError | ResolverError | ParserError | MissingPointerError | UnmatchedParserError | UnmatchedResolverError>;
18
- }
19
- export declare class ParserError extends JSONParserError {
20
- code: JSONParserErrorType;
21
- name: string;
22
- constructor(message: any, source: any);
23
- }
24
- export declare class UnmatchedParserError extends JSONParserError {
25
- code: JSONParserErrorType;
26
- name: string;
27
- constructor(source: string);
28
- }
29
- export declare class ResolverError extends JSONParserError {
30
- code: JSONParserErrorType;
31
- name: string;
32
- ioErrorCode?: string;
33
- constructor(ex: Error | any, source?: string);
34
- }
35
- export declare class UnmatchedResolverError extends JSONParserError {
36
- code: JSONParserErrorType;
37
- name: string;
38
- constructor(source: any);
39
- }
40
- export declare class MissingPointerError extends JSONParserError {
41
- code: JSONParserErrorType;
42
- name: string;
43
- constructor(token: string, path: string);
44
- }
45
- export declare class TimeoutError extends JSONParserError {
46
- code: JSONParserErrorType;
47
- name: string;
48
- constructor(timeout: number);
49
- }
50
- export declare class InvalidPointerError extends JSONParserError {
51
- code: JSONParserErrorType;
52
- name: string;
53
- constructor(pointer: string, path: string);
54
- }
55
- export declare function isHandledError(err: any): err is JSONParserError;
56
- export declare function normalizeError(err: any): any;