@hey-api/json-schema-ref-parser 0.0.1
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/LICENSE +21 -0
- package/README.md +138 -0
- package/dist/lib/bundle.d.ts +26 -0
- package/dist/lib/bundle.js +293 -0
- package/dist/lib/dereference.d.ts +11 -0
- package/dist/lib/dereference.js +224 -0
- package/dist/lib/index.d.ts +74 -0
- package/dist/lib/index.js +208 -0
- package/dist/lib/options.d.ts +61 -0
- package/dist/lib/options.js +45 -0
- package/dist/lib/parse.d.ts +13 -0
- package/dist/lib/parse.js +87 -0
- package/dist/lib/parsers/binary.d.ts +2 -0
- package/dist/lib/parsers/binary.js +12 -0
- package/dist/lib/parsers/json.d.ts +2 -0
- package/dist/lib/parsers/json.js +38 -0
- package/dist/lib/parsers/text.d.ts +2 -0
- package/dist/lib/parsers/text.js +18 -0
- package/dist/lib/parsers/yaml.d.ts +2 -0
- package/dist/lib/parsers/yaml.js +28 -0
- package/dist/lib/pointer.d.ts +88 -0
- package/dist/lib/pointer.js +293 -0
- package/dist/lib/ref.d.ts +180 -0
- package/dist/lib/ref.js +226 -0
- package/dist/lib/refs.d.ts +127 -0
- package/dist/lib/refs.js +232 -0
- package/dist/lib/resolve-external.d.ts +13 -0
- package/dist/lib/resolve-external.js +147 -0
- package/dist/lib/resolvers/file.d.ts +4 -0
- package/dist/lib/resolvers/file.js +61 -0
- package/dist/lib/resolvers/url.d.ts +11 -0
- package/dist/lib/resolvers/url.js +57 -0
- package/dist/lib/types/index.d.ts +43 -0
- package/dist/lib/types/index.js +2 -0
- package/dist/lib/util/convert-path-to-posix.d.ts +1 -0
- package/dist/lib/util/convert-path-to-posix.js +14 -0
- package/dist/lib/util/errors.d.ts +56 -0
- package/dist/lib/util/errors.js +112 -0
- package/dist/lib/util/is-windows.d.ts +1 -0
- package/dist/lib/util/is-windows.js +6 -0
- package/dist/lib/util/plugins.d.ts +16 -0
- package/dist/lib/util/plugins.js +45 -0
- package/dist/lib/util/url.d.ts +79 -0
- package/dist/lib/util/url.js +285 -0
- package/dist/vite.config.d.ts +2 -0
- package/dist/vite.config.js +18 -0
- package/lib/bundle.ts +299 -0
- package/lib/dereference.ts +286 -0
- package/lib/index.ts +209 -0
- package/lib/options.ts +108 -0
- package/lib/parse.ts +56 -0
- package/lib/parsers/binary.ts +13 -0
- package/lib/parsers/json.ts +39 -0
- package/lib/parsers/text.ts +21 -0
- package/lib/parsers/yaml.ts +26 -0
- package/lib/pointer.ts +327 -0
- package/lib/ref.ts +279 -0
- package/lib/refs.ts +239 -0
- package/lib/resolve-external.ts +141 -0
- package/lib/resolvers/file.ts +24 -0
- package/lib/resolvers/url.ts +78 -0
- package/lib/types/index.ts +51 -0
- package/lib/util/convert-path-to-posix.ts +11 -0
- package/lib/util/errors.ts +153 -0
- package/lib/util/is-windows.ts +2 -0
- package/lib/util/plugins.ts +56 -0
- package/lib/util/url.ts +266 -0
- package/package.json +96 -0
package/lib/refs.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import { ono } from "@jsdevtools/ono";
|
|
2
|
+
import $Ref from "./ref.js";
|
|
3
|
+
import * as url from "./util/url.js";
|
|
4
|
+
import type { JSONSchema4Type, JSONSchema6Type, JSONSchema7Type } from "json-schema";
|
|
5
|
+
import type { ParserOptions } from "./options.js";
|
|
6
|
+
import convertPathToPosix from "./util/convert-path-to-posix";
|
|
7
|
+
import type { JSONSchema } from "./types";
|
|
8
|
+
|
|
9
|
+
interface $RefsMap<S extends object = JSONSchema> {
|
|
10
|
+
[url: string]: $Ref<S>;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* 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.
|
|
14
|
+
*
|
|
15
|
+
* 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.
|
|
16
|
+
*
|
|
17
|
+
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html
|
|
18
|
+
*/
|
|
19
|
+
export default class $Refs<S extends object = JSONSchema> {
|
|
20
|
+
/**
|
|
21
|
+
* This property is true if the schema contains any circular references. You may want to check this property before serializing the dereferenced schema as JSON, since JSON.stringify() does not support circular references by default.
|
|
22
|
+
*
|
|
23
|
+
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#circular
|
|
24
|
+
*/
|
|
25
|
+
public circular: boolean;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Returns the paths/URLs of all the files in your schema (including the main schema file).
|
|
29
|
+
*
|
|
30
|
+
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#pathstypes
|
|
31
|
+
*
|
|
32
|
+
* @param types (optional) Optionally only return certain types of paths ("file", "http", etc.)
|
|
33
|
+
*/
|
|
34
|
+
paths(...types: (string | string[])[]): string[] {
|
|
35
|
+
const paths = getPaths(this._$refs, types.flat());
|
|
36
|
+
return paths.map((path) => {
|
|
37
|
+
return convertPathToPosix(path.decoded);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Returns a map of paths/URLs and their correspond values.
|
|
43
|
+
*
|
|
44
|
+
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#valuestypes
|
|
45
|
+
*
|
|
46
|
+
* @param types (optional) Optionally only return values from certain locations ("file", "http", etc.)
|
|
47
|
+
*/
|
|
48
|
+
values(...types: (string | string[])[]): S {
|
|
49
|
+
const $refs = this._$refs;
|
|
50
|
+
const paths = getPaths($refs, types.flat());
|
|
51
|
+
return paths.reduce<Record<string, any>>((obj, path) => {
|
|
52
|
+
obj[convertPathToPosix(path.decoded)] = $refs[path.encoded].value;
|
|
53
|
+
return obj;
|
|
54
|
+
}, {}) as S;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Returns `true` if the given path exists in the schema; otherwise, returns `false`
|
|
59
|
+
*
|
|
60
|
+
* See https://apitools.dev/json-schema-ref-parser/docs/refs.html#existsref
|
|
61
|
+
*
|
|
62
|
+
* @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
|
|
63
|
+
*/
|
|
64
|
+
/**
|
|
65
|
+
* Determines whether the given JSON reference exists.
|
|
66
|
+
*
|
|
67
|
+
* @param path - The path being resolved, optionally with a JSON pointer in the hash
|
|
68
|
+
* @param [options]
|
|
69
|
+
* @returns
|
|
70
|
+
*/
|
|
71
|
+
exists(path: string, options: any) {
|
|
72
|
+
try {
|
|
73
|
+
this._resolve(path, "", options);
|
|
74
|
+
return true;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Resolves the given JSON reference and returns the resolved value.
|
|
82
|
+
*
|
|
83
|
+
* @param path - The path being resolved, with a JSON pointer in the hash
|
|
84
|
+
* @param [options]
|
|
85
|
+
* @returns - Returns the resolved value
|
|
86
|
+
*/
|
|
87
|
+
get(path: string, options?: ParserOptions): JSONSchema4Type | JSONSchema6Type | JSONSchema7Type {
|
|
88
|
+
return this._resolve(path, "", options)!.value;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 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.
|
|
93
|
+
*
|
|
94
|
+
* @param path The JSON Reference path, optionally with a JSON Pointer in the hash
|
|
95
|
+
* @param value The value to assign. Can be anything (object, string, number, etc.)
|
|
96
|
+
*/
|
|
97
|
+
set(path: string, value: JSONSchema4Type | JSONSchema6Type | JSONSchema7Type) {
|
|
98
|
+
const absPath = url.resolve(this._root$Ref.path!, path);
|
|
99
|
+
const withoutHash = url.stripHash(absPath);
|
|
100
|
+
const $ref = this._$refs[withoutHash];
|
|
101
|
+
|
|
102
|
+
if (!$ref) {
|
|
103
|
+
throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
$ref.set(absPath, value);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Returns the specified {@link $Ref} object, or undefined.
|
|
110
|
+
*
|
|
111
|
+
* @param path - The path being resolved, optionally with a JSON pointer in the hash
|
|
112
|
+
* @returns
|
|
113
|
+
* @protected
|
|
114
|
+
*/
|
|
115
|
+
_get$Ref(path: string) {
|
|
116
|
+
path = url.resolve(this._root$Ref.path!, path);
|
|
117
|
+
const withoutHash = url.stripHash(path);
|
|
118
|
+
return this._$refs[withoutHash];
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.
|
|
123
|
+
*
|
|
124
|
+
* @param path - The file path or URL of the referenced file
|
|
125
|
+
*/
|
|
126
|
+
_add(path: string) {
|
|
127
|
+
const withoutHash = url.stripHash(path);
|
|
128
|
+
|
|
129
|
+
const $ref = new $Ref<S>(this);
|
|
130
|
+
$ref.path = withoutHash;
|
|
131
|
+
|
|
132
|
+
this._$refs[withoutHash] = $ref;
|
|
133
|
+
this._root$Ref = this._root$Ref || $ref;
|
|
134
|
+
|
|
135
|
+
return $ref;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Resolves the given JSON reference.
|
|
140
|
+
*
|
|
141
|
+
* @param path - The path being resolved, optionally with a JSON pointer in the hash
|
|
142
|
+
* @param pathFromRoot - The path of `obj` from the schema root
|
|
143
|
+
* @param [options]
|
|
144
|
+
* @returns
|
|
145
|
+
* @protected
|
|
146
|
+
*/
|
|
147
|
+
_resolve(path: string, pathFromRoot: string, options?: ParserOptions) {
|
|
148
|
+
const absPath = url.resolve(this._root$Ref.path!, path);
|
|
149
|
+
const withoutHash = url.stripHash(absPath);
|
|
150
|
+
const $ref = this._$refs[withoutHash];
|
|
151
|
+
|
|
152
|
+
if (!$ref) {
|
|
153
|
+
throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return $ref.resolve(absPath, options, path, pathFromRoot);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* A map of paths/urls to {@link $Ref} objects
|
|
161
|
+
*
|
|
162
|
+
* @type {object}
|
|
163
|
+
* @protected
|
|
164
|
+
*/
|
|
165
|
+
_$refs: $RefsMap<S> = {};
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The {@link $Ref} object that is the root of the JSON schema.
|
|
169
|
+
*
|
|
170
|
+
* @type {$Ref}
|
|
171
|
+
* @protected
|
|
172
|
+
*/
|
|
173
|
+
_root$Ref: $Ref<S>;
|
|
174
|
+
|
|
175
|
+
constructor() {
|
|
176
|
+
/**
|
|
177
|
+
* Indicates whether the schema contains any circular references.
|
|
178
|
+
*
|
|
179
|
+
* @type {boolean}
|
|
180
|
+
*/
|
|
181
|
+
this.circular = false;
|
|
182
|
+
|
|
183
|
+
this._$refs = {};
|
|
184
|
+
|
|
185
|
+
// @ts-ignore
|
|
186
|
+
this._root$Ref = null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Returns the paths of all the files/URLs that are referenced by the JSON schema,
|
|
191
|
+
* including the schema itself.
|
|
192
|
+
*
|
|
193
|
+
* @param [types] - Only return paths of the given types ("file", "http", etc.)
|
|
194
|
+
* @returns
|
|
195
|
+
*/
|
|
196
|
+
/**
|
|
197
|
+
* Returns the map of JSON references and their resolved values.
|
|
198
|
+
*
|
|
199
|
+
* @param [types] - Only return references of the given types ("file", "http", etc.)
|
|
200
|
+
* @returns
|
|
201
|
+
*/
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Returns a POJO (plain old JavaScript object) for serialization as JSON.
|
|
205
|
+
*
|
|
206
|
+
* @returns {object}
|
|
207
|
+
*/
|
|
208
|
+
toJSON = this.values;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Returns the encoded and decoded paths keys of the given object.
|
|
213
|
+
*
|
|
214
|
+
* @param $refs - The object whose keys are URL-encoded paths
|
|
215
|
+
* @param [types] - Only return paths of the given types ("file", "http", etc.)
|
|
216
|
+
* @returns
|
|
217
|
+
*/
|
|
218
|
+
function getPaths<S extends object = JSONSchema>(
|
|
219
|
+
$refs: $RefsMap<S>,
|
|
220
|
+
types: string[],
|
|
221
|
+
) {
|
|
222
|
+
let paths = Object.keys($refs);
|
|
223
|
+
|
|
224
|
+
// Filter the paths by type
|
|
225
|
+
types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
|
|
226
|
+
if (types.length > 0 && types[0]) {
|
|
227
|
+
paths = paths.filter((key) => {
|
|
228
|
+
return types.includes($refs[key].pathType as string);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Decode local filesystem paths
|
|
233
|
+
return paths.map((path) => {
|
|
234
|
+
return {
|
|
235
|
+
encoded: path,
|
|
236
|
+
decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path,
|
|
237
|
+
};
|
|
238
|
+
});
|
|
239
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import $Ref from "./ref.js";
|
|
2
|
+
import Pointer from "./pointer.js";
|
|
3
|
+
import { newFile, parseFile } from "./parse.js";
|
|
4
|
+
import * as url from "./util/url.js";
|
|
5
|
+
import type $Refs from "./refs.js";
|
|
6
|
+
import type { $RefParserOptions } from "./options.js";
|
|
7
|
+
import type { JSONSchema } from "./types/index.js";
|
|
8
|
+
import { getResolvedInput } from "./index.js";
|
|
9
|
+
import type { $RefParser } from "./index.js";
|
|
10
|
+
import { isHandledError } from "./util/errors.js";
|
|
11
|
+
import { fileResolver } from "./resolvers/file.js";
|
|
12
|
+
import { urlResolver } from "./resolvers/url.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Crawls the JSON schema, finds all external JSON references, and resolves their values.
|
|
16
|
+
* This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.
|
|
17
|
+
*
|
|
18
|
+
* NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.
|
|
19
|
+
*
|
|
20
|
+
* @returns
|
|
21
|
+
* The promise resolves once all JSON references in the schema have been resolved,
|
|
22
|
+
* including nested references that are contained in externally-referenced files.
|
|
23
|
+
*/
|
|
24
|
+
export function resolveExternal(
|
|
25
|
+
parser: $RefParser,
|
|
26
|
+
options: $RefParserOptions,
|
|
27
|
+
) {
|
|
28
|
+
try {
|
|
29
|
+
// console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
|
|
30
|
+
const promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options);
|
|
31
|
+
return Promise.all(promises);
|
|
32
|
+
} catch (e) {
|
|
33
|
+
return Promise.reject(e);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Recursively crawls the given value, and resolves any external JSON references.
|
|
39
|
+
*
|
|
40
|
+
* @param obj - The value to crawl. If it's not an object or array, it will be ignored.
|
|
41
|
+
* @param path - The full path of `obj`, possibly with a JSON Pointer in the hash
|
|
42
|
+
* @param {boolean} external - Whether `obj` was found in an external document.
|
|
43
|
+
* @param $refs
|
|
44
|
+
* @param options
|
|
45
|
+
* @param seen - Internal.
|
|
46
|
+
*
|
|
47
|
+
* @returns
|
|
48
|
+
* Returns an array of promises. There will be one promise for each JSON reference in `obj`.
|
|
49
|
+
* If `obj` does not contain any JSON references, then the array will be empty.
|
|
50
|
+
* If any of the JSON references point to files that contain additional JSON references,
|
|
51
|
+
* then the corresponding promise will internally reference an array of promises.
|
|
52
|
+
*/
|
|
53
|
+
function crawl<S extends object = JSONSchema>(
|
|
54
|
+
obj: string | Buffer | S | undefined | null,
|
|
55
|
+
path: string,
|
|
56
|
+
$refs: $Refs<S>,
|
|
57
|
+
options: $RefParserOptions,
|
|
58
|
+
seen?: Set<any>,
|
|
59
|
+
external?: boolean,
|
|
60
|
+
) {
|
|
61
|
+
seen ||= new Set();
|
|
62
|
+
let promises: any = [];
|
|
63
|
+
|
|
64
|
+
if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {
|
|
65
|
+
seen.add(obj); // Track previously seen objects to avoid infinite recursion
|
|
66
|
+
if ($Ref.isExternal$Ref(obj)) {
|
|
67
|
+
promises.push(resolve$Ref<S>(obj, path, $refs, options));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const keys = Object.keys(obj) as string[];
|
|
71
|
+
for (const key of keys) {
|
|
72
|
+
const keyPath = Pointer.join(path, key);
|
|
73
|
+
const value = obj[key as keyof typeof obj] as string | JSONSchema | Buffer | undefined;
|
|
74
|
+
promises = promises.concat(crawl(value, keyPath, $refs, options, seen, external));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return promises;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Resolves the given JSON Reference, and then crawls the resulting value.
|
|
83
|
+
*
|
|
84
|
+
* @param $ref - The JSON Reference to resolve
|
|
85
|
+
* @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash
|
|
86
|
+
* @param $refs
|
|
87
|
+
* @param options
|
|
88
|
+
*
|
|
89
|
+
* @returns
|
|
90
|
+
* The promise resolves once all JSON references in the object have been resolved,
|
|
91
|
+
* including nested references that are contained in externally-referenced files.
|
|
92
|
+
*/
|
|
93
|
+
async function resolve$Ref<S extends object = JSONSchema>(
|
|
94
|
+
$ref: S,
|
|
95
|
+
path: string,
|
|
96
|
+
$refs: $Refs<S>,
|
|
97
|
+
options: $RefParserOptions,
|
|
98
|
+
) {
|
|
99
|
+
const resolvedPath = url.resolve(path, ($ref as JSONSchema).$ref!);
|
|
100
|
+
const withoutHash = url.stripHash(resolvedPath);
|
|
101
|
+
|
|
102
|
+
// $ref.$ref = url.relative($refs._root$Ref.path, resolvedPath);
|
|
103
|
+
|
|
104
|
+
// Do we already have this $ref?
|
|
105
|
+
const ref = $refs._$refs[withoutHash];
|
|
106
|
+
if (ref) {
|
|
107
|
+
// We've already parsed this $ref, so use the existing value
|
|
108
|
+
return Promise.resolve(ref.value);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Parse the $referenced file/url
|
|
112
|
+
const file = newFile(resolvedPath)
|
|
113
|
+
|
|
114
|
+
// Add a new $Ref for this file, even though we don't have the value yet.
|
|
115
|
+
// This ensures that we don't simultaneously read & parse the same file multiple times
|
|
116
|
+
const $refAdded = $refs._add(file.url);
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const resolvedInput = getResolvedInput({ pathOrUrlOrSchema: resolvedPath })
|
|
120
|
+
|
|
121
|
+
$refAdded.pathType = resolvedInput.type;
|
|
122
|
+
|
|
123
|
+
let promises: any = [];
|
|
124
|
+
|
|
125
|
+
if (resolvedInput.type !== 'json') {
|
|
126
|
+
const resolver = resolvedInput.type === 'file' ? fileResolver : urlResolver;
|
|
127
|
+
await resolver.handler(file);
|
|
128
|
+
const parseResult = await parseFile(file, options);
|
|
129
|
+
$refAdded.value = parseResult.result;
|
|
130
|
+
promises = crawl(parseResult.result, `${withoutHash}#`, $refs, options, new Set(), true);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return Promise.all(promises);
|
|
134
|
+
} catch (err) {
|
|
135
|
+
if (isHandledError(err)) {
|
|
136
|
+
$refAdded.value = err;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
throw err;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import { ono } from "@jsdevtools/ono";
|
|
3
|
+
import * as url from "../util/url.js";
|
|
4
|
+
import { ResolverError } from "../util/errors.js";
|
|
5
|
+
import type { FileInfo } from "../types/index.js";
|
|
6
|
+
|
|
7
|
+
export const fileResolver = {
|
|
8
|
+
handler: async (file: FileInfo): Promise<void> => {
|
|
9
|
+
let path: string | undefined;
|
|
10
|
+
|
|
11
|
+
try {
|
|
12
|
+
path = url.toFileSystemPath(file.url);
|
|
13
|
+
} catch (error: any) {
|
|
14
|
+
throw new ResolverError(ono.uri(error, `Malformed URI: ${file.url}`), file.url);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
const data = await fs.promises.readFile(path);
|
|
19
|
+
file.data = data;
|
|
20
|
+
} catch (error: any) {
|
|
21
|
+
throw new ResolverError(ono(error, `Error opening file "${path}"`), path);
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { ono } from "@jsdevtools/ono";
|
|
2
|
+
import { resolve } from "../util/url.js";
|
|
3
|
+
import { ResolverError } from "../util/errors.js";
|
|
4
|
+
import type { FileInfo } from "../types/index.js";
|
|
5
|
+
|
|
6
|
+
export const sendRequest = async ({
|
|
7
|
+
init,
|
|
8
|
+
redirects = [],
|
|
9
|
+
url,
|
|
10
|
+
}: {
|
|
11
|
+
init?: RequestInit;
|
|
12
|
+
redirects?: string[];
|
|
13
|
+
url: URL | string;
|
|
14
|
+
}): Promise<{
|
|
15
|
+
response: Response;
|
|
16
|
+
}> => {
|
|
17
|
+
url = new URL(url);
|
|
18
|
+
redirects.push(url.href);
|
|
19
|
+
|
|
20
|
+
try {
|
|
21
|
+
const controller = new AbortController();
|
|
22
|
+
const timeoutId = setTimeout(() => {
|
|
23
|
+
controller.abort();
|
|
24
|
+
}, 60_000);
|
|
25
|
+
const response = await fetch(url, {
|
|
26
|
+
signal: controller.signal,
|
|
27
|
+
...init,
|
|
28
|
+
});
|
|
29
|
+
clearTimeout(timeoutId);
|
|
30
|
+
|
|
31
|
+
if (response.status >= 400) {
|
|
32
|
+
throw ono({ status: response.status }, `HTTP ERROR ${response.status}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (response.status >= 300) {
|
|
36
|
+
if (redirects.length > 5) {
|
|
37
|
+
throw new ResolverError(
|
|
38
|
+
ono(
|
|
39
|
+
{ status: response.status },
|
|
40
|
+
`Error requesting ${redirects[0]}. \nToo many redirects: \n ${redirects.join(" \n ")}`,
|
|
41
|
+
),
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (!("location" in response.headers) || !response.headers.location) {
|
|
46
|
+
throw ono({ status: response.status }, `HTTP ${response.status} redirect with no location header`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return sendRequest({
|
|
50
|
+
init,
|
|
51
|
+
redirects,
|
|
52
|
+
url: resolve(url.href, response.headers.location as string),
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return { response };
|
|
57
|
+
} catch (error: any) {
|
|
58
|
+
throw new ResolverError(ono(error, `Error requesting ${url.href}`), url.href);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export const urlResolver = {
|
|
63
|
+
handler: async (file: FileInfo, arrayBuffer?: ArrayBuffer): Promise<void> => {
|
|
64
|
+
let data = arrayBuffer;
|
|
65
|
+
|
|
66
|
+
if (!data) {
|
|
67
|
+
const { response } = await sendRequest({
|
|
68
|
+
init: {
|
|
69
|
+
method: 'GET',
|
|
70
|
+
},
|
|
71
|
+
url: file.url,
|
|
72
|
+
});
|
|
73
|
+
data = response.body ? await response.arrayBuffer() : new ArrayBuffer(0)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
file.data = Buffer.from(data);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
JSONSchema4,
|
|
3
|
+
JSONSchema4Object,
|
|
4
|
+
JSONSchema6,
|
|
5
|
+
JSONSchema6Object,
|
|
6
|
+
JSONSchema7,
|
|
7
|
+
JSONSchema7Object,
|
|
8
|
+
} from "json-schema";
|
|
9
|
+
|
|
10
|
+
export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7;
|
|
11
|
+
export type JSONSchemaObject = JSONSchema4Object | JSONSchema6Object | JSONSchema7Object;
|
|
12
|
+
|
|
13
|
+
export interface Plugin {
|
|
14
|
+
/**
|
|
15
|
+
* Can this parser be used to process this file?
|
|
16
|
+
*/
|
|
17
|
+
canHandle: (file: FileInfo) => boolean;
|
|
18
|
+
/**
|
|
19
|
+
* 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.
|
|
20
|
+
*
|
|
21
|
+
* 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:
|
|
22
|
+
*/
|
|
23
|
+
handler: (file: FileInfo) => string | Buffer | JSONSchema | Promise<{ data: Buffer }> | Promise<string | Buffer | JSONSchema>;
|
|
24
|
+
name: 'binary' | 'file' | 'http' | 'json' | 'text' | 'yaml';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 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.
|
|
29
|
+
*
|
|
30
|
+
* 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.
|
|
31
|
+
*
|
|
32
|
+
* See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
|
|
33
|
+
*/
|
|
34
|
+
export interface FileInfo {
|
|
35
|
+
/**
|
|
36
|
+
* The raw file contents, in whatever form they were returned by the resolver that read the file.
|
|
37
|
+
*/
|
|
38
|
+
data: string | Buffer;
|
|
39
|
+
/**
|
|
40
|
+
* The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
|
|
41
|
+
*/
|
|
42
|
+
extension: string;
|
|
43
|
+
/**
|
|
44
|
+
* 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.
|
|
45
|
+
*/
|
|
46
|
+
hash: string;
|
|
47
|
+
/**
|
|
48
|
+
* 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).
|
|
49
|
+
*/
|
|
50
|
+
url: string;
|
|
51
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import path from "path";
|
|
2
|
+
|
|
3
|
+
export default function convertPathToPosix(filePath: string) {
|
|
4
|
+
const isExtendedLengthPath = filePath.startsWith("\\\\?\\");
|
|
5
|
+
|
|
6
|
+
if (isExtendedLengthPath) {
|
|
7
|
+
return filePath;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
return filePath.split(path?.win32?.sep).join(path?.posix?.sep ?? "/");
|
|
11
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { Ono } from "@jsdevtools/ono";
|
|
2
|
+
import { getHash, stripHash, toFileSystemPath } from "./url.js";
|
|
3
|
+
import type { $RefParser } from "../index.js";
|
|
4
|
+
import type { JSONSchema } from "../types/index.js";
|
|
5
|
+
import type $Ref from "../ref";
|
|
6
|
+
|
|
7
|
+
export type JSONParserErrorType =
|
|
8
|
+
| "EUNKNOWN"
|
|
9
|
+
| "EPARSER"
|
|
10
|
+
| "EUNMATCHEDPARSER"
|
|
11
|
+
| "ETIMEOUT"
|
|
12
|
+
| "ERESOLVER"
|
|
13
|
+
| "EUNMATCHEDRESOLVER"
|
|
14
|
+
| "EMISSINGPOINTER"
|
|
15
|
+
| "EINVALIDPOINTER";
|
|
16
|
+
|
|
17
|
+
export class JSONParserError extends Error {
|
|
18
|
+
public readonly name: string;
|
|
19
|
+
public readonly message: string;
|
|
20
|
+
public source: string | undefined;
|
|
21
|
+
public path: Array<string | number> | null;
|
|
22
|
+
public readonly code: JSONParserErrorType;
|
|
23
|
+
public constructor(message: string, source?: string) {
|
|
24
|
+
super();
|
|
25
|
+
|
|
26
|
+
this.code = "EUNKNOWN";
|
|
27
|
+
this.name = "JSONParserError";
|
|
28
|
+
this.message = message;
|
|
29
|
+
this.source = source;
|
|
30
|
+
this.path = null;
|
|
31
|
+
|
|
32
|
+
Ono.extend(this);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
get footprint() {
|
|
36
|
+
return `${this.path}+${this.source}+${this.code}+${this.message}`;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export class JSONParserErrorGroup<S extends object = JSONSchema> extends Error {
|
|
41
|
+
files: $RefParser;
|
|
42
|
+
|
|
43
|
+
constructor(parser: $RefParser) {
|
|
44
|
+
super();
|
|
45
|
+
|
|
46
|
+
this.files = parser;
|
|
47
|
+
this.name = "JSONParserErrorGroup";
|
|
48
|
+
this.message = `${this.errors.length} error${
|
|
49
|
+
this.errors.length > 1 ? "s" : ""
|
|
50
|
+
} occurred while reading '${toFileSystemPath(parser.$refs._root$Ref!.path)}'`;
|
|
51
|
+
|
|
52
|
+
Ono.extend(this);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
static getParserErrors<S extends object = JSONSchema>(
|
|
56
|
+
parser: $RefParser,
|
|
57
|
+
) {
|
|
58
|
+
const errors = [];
|
|
59
|
+
|
|
60
|
+
for (const $ref of Object.values(parser.$refs._$refs) as $Ref<S>[]) {
|
|
61
|
+
if ($ref.errors) {
|
|
62
|
+
errors.push(...$ref.errors);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return errors;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
get errors(): Array<
|
|
70
|
+
| JSONParserError
|
|
71
|
+
| InvalidPointerError
|
|
72
|
+
| ResolverError
|
|
73
|
+
| ParserError
|
|
74
|
+
| MissingPointerError
|
|
75
|
+
| UnmatchedParserError
|
|
76
|
+
| UnmatchedResolverError
|
|
77
|
+
> {
|
|
78
|
+
return JSONParserErrorGroup.getParserErrors<S>(this.files);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export class ParserError extends JSONParserError {
|
|
83
|
+
code = "EPARSER" as JSONParserErrorType;
|
|
84
|
+
name = "ParserError";
|
|
85
|
+
constructor(message: any, source: any) {
|
|
86
|
+
super(`Error parsing ${source}: ${message}`, source);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class UnmatchedParserError extends JSONParserError {
|
|
91
|
+
code = "EUNMATCHEDPARSER" as JSONParserErrorType;
|
|
92
|
+
name = "UnmatchedParserError";
|
|
93
|
+
|
|
94
|
+
constructor(source: string) {
|
|
95
|
+
super(`Could not find parser for "${source}"`, source);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class ResolverError extends JSONParserError {
|
|
100
|
+
code = "ERESOLVER" as JSONParserErrorType;
|
|
101
|
+
name = "ResolverError";
|
|
102
|
+
ioErrorCode?: string;
|
|
103
|
+
constructor(ex: Error | any, source?: string) {
|
|
104
|
+
super(ex.message || `Error reading file "${source}"`, source);
|
|
105
|
+
if ("code" in ex) {
|
|
106
|
+
this.ioErrorCode = String(ex.code);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export class UnmatchedResolverError extends JSONParserError {
|
|
112
|
+
code = "EUNMATCHEDRESOLVER" as JSONParserErrorType;
|
|
113
|
+
name = "UnmatchedResolverError";
|
|
114
|
+
constructor(source: any) {
|
|
115
|
+
super(`Could not find resolver for "${source}"`, source);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export class MissingPointerError extends JSONParserError {
|
|
120
|
+
code = "EMISSINGPOINTER" as JSONParserErrorType;
|
|
121
|
+
name = "MissingPointerError";
|
|
122
|
+
constructor(token: string, path: string) {
|
|
123
|
+
super(`Missing $ref pointer "${getHash(path)}". Token "${token}" does not exist.`, stripHash(path));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export class TimeoutError extends JSONParserError {
|
|
128
|
+
code = "ETIMEOUT" as JSONParserErrorType;
|
|
129
|
+
name = "TimeoutError";
|
|
130
|
+
constructor(timeout: number) {
|
|
131
|
+
super(`Dereferencing timeout reached: ${timeout}ms`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export class InvalidPointerError extends JSONParserError {
|
|
136
|
+
code = "EUNMATCHEDRESOLVER" as JSONParserErrorType;
|
|
137
|
+
name = "InvalidPointerError";
|
|
138
|
+
constructor(pointer: string, path: string) {
|
|
139
|
+
super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, stripHash(path));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function isHandledError(err: any): err is JSONParserError {
|
|
144
|
+
return err instanceof JSONParserError || err instanceof JSONParserErrorGroup;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function normalizeError(err: any) {
|
|
148
|
+
if (err.path === null) {
|
|
149
|
+
err.path = [];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return err;
|
|
153
|
+
}
|