@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.
Files changed (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +138 -0
  3. package/dist/lib/bundle.d.ts +26 -0
  4. package/dist/lib/bundle.js +293 -0
  5. package/dist/lib/dereference.d.ts +11 -0
  6. package/dist/lib/dereference.js +224 -0
  7. package/dist/lib/index.d.ts +74 -0
  8. package/dist/lib/index.js +208 -0
  9. package/dist/lib/options.d.ts +61 -0
  10. package/dist/lib/options.js +45 -0
  11. package/dist/lib/parse.d.ts +13 -0
  12. package/dist/lib/parse.js +87 -0
  13. package/dist/lib/parsers/binary.d.ts +2 -0
  14. package/dist/lib/parsers/binary.js +12 -0
  15. package/dist/lib/parsers/json.d.ts +2 -0
  16. package/dist/lib/parsers/json.js +38 -0
  17. package/dist/lib/parsers/text.d.ts +2 -0
  18. package/dist/lib/parsers/text.js +18 -0
  19. package/dist/lib/parsers/yaml.d.ts +2 -0
  20. package/dist/lib/parsers/yaml.js +28 -0
  21. package/dist/lib/pointer.d.ts +88 -0
  22. package/dist/lib/pointer.js +293 -0
  23. package/dist/lib/ref.d.ts +180 -0
  24. package/dist/lib/ref.js +226 -0
  25. package/dist/lib/refs.d.ts +127 -0
  26. package/dist/lib/refs.js +232 -0
  27. package/dist/lib/resolve-external.d.ts +13 -0
  28. package/dist/lib/resolve-external.js +147 -0
  29. package/dist/lib/resolvers/file.d.ts +4 -0
  30. package/dist/lib/resolvers/file.js +61 -0
  31. package/dist/lib/resolvers/url.d.ts +11 -0
  32. package/dist/lib/resolvers/url.js +57 -0
  33. package/dist/lib/types/index.d.ts +43 -0
  34. package/dist/lib/types/index.js +2 -0
  35. package/dist/lib/util/convert-path-to-posix.d.ts +1 -0
  36. package/dist/lib/util/convert-path-to-posix.js +14 -0
  37. package/dist/lib/util/errors.d.ts +56 -0
  38. package/dist/lib/util/errors.js +112 -0
  39. package/dist/lib/util/is-windows.d.ts +1 -0
  40. package/dist/lib/util/is-windows.js +6 -0
  41. package/dist/lib/util/plugins.d.ts +16 -0
  42. package/dist/lib/util/plugins.js +45 -0
  43. package/dist/lib/util/url.d.ts +79 -0
  44. package/dist/lib/util/url.js +285 -0
  45. package/dist/vite.config.d.ts +2 -0
  46. package/dist/vite.config.js +18 -0
  47. package/lib/bundle.ts +299 -0
  48. package/lib/dereference.ts +286 -0
  49. package/lib/index.ts +209 -0
  50. package/lib/options.ts +108 -0
  51. package/lib/parse.ts +56 -0
  52. package/lib/parsers/binary.ts +13 -0
  53. package/lib/parsers/json.ts +39 -0
  54. package/lib/parsers/text.ts +21 -0
  55. package/lib/parsers/yaml.ts +26 -0
  56. package/lib/pointer.ts +327 -0
  57. package/lib/ref.ts +279 -0
  58. package/lib/refs.ts +239 -0
  59. package/lib/resolve-external.ts +141 -0
  60. package/lib/resolvers/file.ts +24 -0
  61. package/lib/resolvers/url.ts +78 -0
  62. package/lib/types/index.ts +51 -0
  63. package/lib/util/convert-path-to-posix.ts +11 -0
  64. package/lib/util/errors.ts +153 -0
  65. package/lib/util/is-windows.ts +2 -0
  66. package/lib/util/plugins.ts +56 -0
  67. package/lib/util/url.ts +266 -0
  68. package/package.json +96 -0
@@ -0,0 +1,224 @@
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 ref_js_1 = __importDefault(require("./ref.js"));
40
+ const pointer_js_1 = __importDefault(require("./pointer.js"));
41
+ const ono_1 = require("@jsdevtools/ono");
42
+ const url = __importStar(require("./util/url.js"));
43
+ const errors_1 = require("./util/errors");
44
+ exports.default = dereference;
45
+ /**
46
+ * Crawls the JSON schema, finds all JSON references, and dereferences them.
47
+ * This method mutates the JSON schema object, replacing JSON references with their resolved value.
48
+ *
49
+ * @param parser
50
+ * @param options
51
+ */
52
+ function dereference(parser, options) {
53
+ const start = Date.now();
54
+ // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);
55
+ const dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", new Set(), new Set(), new Map(), parser.$refs, options, start);
56
+ parser.$refs.circular = dereferenced.circular;
57
+ parser.schema = dereferenced.value;
58
+ }
59
+ /**
60
+ * Recursively crawls the given value, and dereferences any JSON references.
61
+ *
62
+ * @param obj - The value to crawl. If it's not an object or array, it will be ignored.
63
+ * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash
64
+ * @param pathFromRoot - The path of `obj` from the schema root
65
+ * @param parents - An array of the parent objects that have already been dereferenced
66
+ * @param processedObjects - An array of all the objects that have already been processed
67
+ * @param dereferencedCache - An map of all the dereferenced objects
68
+ * @param $refs
69
+ * @param options
70
+ * @param startTime - The time when the dereferencing started
71
+ * @returns
72
+ */
73
+ function crawl(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime) {
74
+ let dereferenced;
75
+ const result = {
76
+ value: obj,
77
+ circular: false,
78
+ };
79
+ if (options && options.timeoutMs) {
80
+ if (Date.now() - startTime > options.timeoutMs) {
81
+ throw new errors_1.TimeoutError(options.timeoutMs);
82
+ }
83
+ }
84
+ const derefOptions = (options.dereference || {});
85
+ const isExcludedPath = derefOptions.excludedPathMatcher || (() => false);
86
+ if (derefOptions?.circular === "ignore" || !processedObjects.has(obj)) {
87
+ if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot)) {
88
+ parents.add(obj);
89
+ processedObjects.add(obj);
90
+ if (ref_js_1.default.isAllowed$Ref(obj)) {
91
+ dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
92
+ result.circular = dereferenced.circular;
93
+ result.value = dereferenced.value;
94
+ }
95
+ else {
96
+ for (const key of Object.keys(obj)) {
97
+ const keyPath = pointer_js_1.default.join(path, key);
98
+ const keyPathFromRoot = pointer_js_1.default.join(pathFromRoot, key);
99
+ if (isExcludedPath(keyPathFromRoot)) {
100
+ continue;
101
+ }
102
+ const value = obj[key];
103
+ let circular = false;
104
+ if (ref_js_1.default.isAllowed$Ref(value)) {
105
+ dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
106
+ circular = dereferenced.circular;
107
+ // Avoid pointless mutations; breaks frozen objects to no profit
108
+ if (obj[key] !== dereferenced.value) {
109
+ obj[key] = dereferenced.value;
110
+ derefOptions?.onDereference?.(value.$ref, obj[key], obj, key);
111
+ }
112
+ }
113
+ else {
114
+ if (!parents.has(value)) {
115
+ dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
116
+ circular = dereferenced.circular;
117
+ // Avoid pointless mutations; breaks frozen objects to no profit
118
+ if (obj[key] !== dereferenced.value) {
119
+ obj[key] = dereferenced.value;
120
+ }
121
+ }
122
+ else {
123
+ circular = foundCircularReference(keyPath, $refs, options);
124
+ }
125
+ }
126
+ // Set the "isCircular" flag if this or any other property is circular
127
+ result.circular = result.circular || circular;
128
+ }
129
+ }
130
+ parents.delete(obj);
131
+ }
132
+ }
133
+ return result;
134
+ }
135
+ /**
136
+ * Dereferences the given JSON Reference, and then crawls the resulting value.
137
+ *
138
+ * @param $ref - The JSON Reference to resolve
139
+ * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash
140
+ * @param pathFromRoot - The path of `$ref` from the schema root
141
+ * @param parents - An array of the parent objects that have already been dereferenced
142
+ * @param processedObjects - An array of all the objects that have already been dereferenced
143
+ * @param dereferencedCache - An map of all the dereferenced objects
144
+ * @param $refs
145
+ * @param options
146
+ * @returns
147
+ */
148
+ function dereference$Ref($ref, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime) {
149
+ const $refPath = url.resolve(path, $ref.$ref);
150
+ const cache = dereferencedCache.get($refPath);
151
+ if (cache && !cache.circular) {
152
+ const refKeys = Object.keys($ref);
153
+ if (refKeys.length > 1) {
154
+ const extraKeys = {};
155
+ for (const key of refKeys) {
156
+ if (key !== "$ref" && !(key in cache.value)) {
157
+ // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
158
+ extraKeys[key] = $ref[key];
159
+ }
160
+ }
161
+ return {
162
+ circular: cache.circular,
163
+ value: Object.assign({}, cache.value, extraKeys),
164
+ };
165
+ }
166
+ return cache;
167
+ }
168
+ const pointer = $refs._resolve($refPath, path, options);
169
+ if (pointer === null) {
170
+ return {
171
+ circular: false,
172
+ value: null,
173
+ };
174
+ }
175
+ // Check for circular references
176
+ const directCircular = pointer.circular;
177
+ let circular = directCircular || parents.has(pointer.value);
178
+ if (circular) {
179
+ foundCircularReference(path, $refs, options);
180
+ }
181
+ // Dereference the JSON reference
182
+ let dereferencedValue = ref_js_1.default.dereference($ref, pointer.value);
183
+ // Crawl the dereferenced value (unless it's circular)
184
+ if (!circular) {
185
+ // Determine if the dereferenced value is circular
186
+ const dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
187
+ circular = dereferenced.circular;
188
+ dereferencedValue = dereferenced.value;
189
+ }
190
+ if (circular && !directCircular && options.dereference?.circular === "ignore") {
191
+ // The user has chosen to "ignore" circular references, so don't change the value
192
+ dereferencedValue = $ref;
193
+ }
194
+ if (directCircular) {
195
+ // The pointer is a DIRECT circular reference (i.e. it references itself).
196
+ // So replace the $ref path with the absolute path from the JSON Schema root
197
+ dereferencedValue.$ref = pathFromRoot;
198
+ }
199
+ const dereferencedObject = {
200
+ circular,
201
+ value: dereferencedValue,
202
+ };
203
+ // only cache if no extra properties than $ref
204
+ if (Object.keys($ref).length === 1) {
205
+ dereferencedCache.set($refPath, dereferencedObject);
206
+ }
207
+ return dereferencedObject;
208
+ }
209
+ /**
210
+ * Called when a circular reference is found.
211
+ * It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false.
212
+ *
213
+ * @param keyPath - The JSON Reference path of the circular reference
214
+ * @param $refs
215
+ * @param options
216
+ * @returns - always returns true, to indicate that a circular reference was found
217
+ */
218
+ function foundCircularReference(keyPath, $refs, options) {
219
+ $refs.circular = true;
220
+ if (!options.dereference.circular) {
221
+ throw ono_1.ono.reference(`Circular $ref pointer found at ${keyPath}`);
222
+ }
223
+ return true;
224
+ }
@@ -0,0 +1,74 @@
1
+ import $Refs from "./refs.js";
2
+ import type { JSONSchema } from "./types/index.js";
3
+ interface ResolvedInput {
4
+ path: string;
5
+ schema: string | JSONSchema | Buffer<ArrayBufferLike> | Awaited<JSONSchema> | undefined;
6
+ type: 'file' | 'json' | 'url';
7
+ }
8
+ export declare const getResolvedInput: ({ pathOrUrlOrSchema, }: {
9
+ pathOrUrlOrSchema: JSONSchema | string | unknown;
10
+ }) => ResolvedInput;
11
+ /**
12
+ * This class parses a JSON schema, builds a map of its JSON references and their resolved values,
13
+ * and provides methods for traversing, manipulating, and dereferencing those references.
14
+ */
15
+ export declare class $RefParser {
16
+ /**
17
+ * The resolved JSON references
18
+ *
19
+ * @type {$Refs}
20
+ * @readonly
21
+ */
22
+ $refs: $Refs<JSONSchema>;
23
+ options: import("./options.js").$RefParserOptions;
24
+ /**
25
+ * The parsed (and possibly dereferenced) JSON schema object
26
+ *
27
+ * @type {object}
28
+ * @readonly
29
+ */
30
+ schema: JSONSchema | null;
31
+ /**
32
+ * Bundles all referenced files/URLs into a single schema that only has internal `$ref` pointers. This lets you split-up your schema however you want while you're building it, but easily combine all those files together when it's time to package or distribute the schema to other people. The resulting schema size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
33
+ *
34
+ * This also eliminates the risk of circular references, so the schema can be safely serialized using `JSON.stringify()`.
35
+ *
36
+ * See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#bundleschema-options-callback
37
+ *
38
+ * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file.
39
+ */
40
+ bundle({ arrayBuffer, pathOrUrlOrSchema, resolvedInput, }: {
41
+ arrayBuffer?: ArrayBuffer;
42
+ pathOrUrlOrSchema: JSONSchema | string | unknown;
43
+ resolvedInput?: ResolvedInput;
44
+ }): Promise<JSONSchema>;
45
+ /**
46
+ * Dereferences all `$ref` pointers in the JSON Schema, replacing each reference with its resolved value. This results in a schema object that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
47
+ *
48
+ * The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the schema using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
49
+ *
50
+ * See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#dereferenceschema-options-callback
51
+ *
52
+ * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file.
53
+ */
54
+ dereference({ pathOrUrlOrSchema, }: {
55
+ pathOrUrlOrSchema: JSONSchema | string | unknown;
56
+ }): Promise<JSONSchema>;
57
+ /**
58
+ * Parses the given JSON schema.
59
+ * This method does not resolve any JSON references.
60
+ * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
61
+ *
62
+ * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file.
63
+ * @returns - The returned promise resolves with the parsed JSON schema object.
64
+ */
65
+ parse({ arrayBuffer, pathOrUrlOrSchema, resolvedInput: _resolvedInput, }: {
66
+ arrayBuffer?: ArrayBuffer;
67
+ pathOrUrlOrSchema: JSONSchema | string | unknown;
68
+ resolvedInput?: ResolvedInput;
69
+ }): Promise<{
70
+ schema: JSONSchema;
71
+ }>;
72
+ }
73
+ export { sendRequest } from './resolvers/url.js';
74
+ export type { JSONSchema } from "./types/index.js";
@@ -0,0 +1,208 @@
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.sendRequest = exports.$RefParser = exports.getResolvedInput = void 0;
40
+ const refs_js_1 = __importDefault(require("./refs.js"));
41
+ const parse_js_1 = require("./parse.js");
42
+ const resolve_external_js_1 = require("./resolve-external.js");
43
+ const bundle_js_1 = __importDefault(require("./bundle.js"));
44
+ const dereference_js_1 = __importDefault(require("./dereference.js"));
45
+ const url = __importStar(require("./util/url.js"));
46
+ const errors_js_1 = require("./util/errors.js");
47
+ const ono_1 = require("@jsdevtools/ono");
48
+ const options_js_1 = require("./options.js");
49
+ const url_js_1 = require("./resolvers/url.js");
50
+ const file_js_1 = require("./resolvers/file.js");
51
+ const getResolvedInput = ({ pathOrUrlOrSchema, }) => {
52
+ if (!pathOrUrlOrSchema) {
53
+ throw (0, ono_1.ono)(`Expected a file path, URL, or object. Got ${pathOrUrlOrSchema}`);
54
+ }
55
+ const resolvedInput = {
56
+ path: typeof pathOrUrlOrSchema === 'string' ? pathOrUrlOrSchema : '',
57
+ schema: undefined,
58
+ type: 'url',
59
+ };
60
+ // If the path is a filesystem path, then convert it to a URL.
61
+ // NOTE: According to the JSON Reference spec, these should already be URLs,
62
+ // but, in practice, many people use local filesystem paths instead.
63
+ // So we're being generous here and doing the conversion automatically.
64
+ // This is not intended to be a 100% bulletproof solution.
65
+ // If it doesn't work for your use-case, then use a URL instead.
66
+ if (url.isFileSystemPath(resolvedInput.path)) {
67
+ resolvedInput.path = url.fromFileSystemPath(resolvedInput.path);
68
+ resolvedInput.type = 'file';
69
+ }
70
+ else if (!resolvedInput.path && pathOrUrlOrSchema && typeof pathOrUrlOrSchema === 'object') {
71
+ if ("$id" in pathOrUrlOrSchema && pathOrUrlOrSchema.$id) {
72
+ // when schema id has defined an URL should use that hostname to request the references,
73
+ // instead of using the current page URL
74
+ const { hostname, protocol } = new URL(pathOrUrlOrSchema.$id);
75
+ resolvedInput.path = `${protocol}//${hostname}:${protocol === "https:" ? 443 : 80}`;
76
+ resolvedInput.type = 'url';
77
+ }
78
+ else {
79
+ resolvedInput.schema = pathOrUrlOrSchema;
80
+ resolvedInput.type = 'json';
81
+ }
82
+ }
83
+ // resolve the absolute path of the schema
84
+ resolvedInput.path = url.resolve(url.cwd(), resolvedInput.path);
85
+ return resolvedInput;
86
+ };
87
+ exports.getResolvedInput = getResolvedInput;
88
+ /**
89
+ * This class parses a JSON schema, builds a map of its JSON references and their resolved values,
90
+ * and provides methods for traversing, manipulating, and dereferencing those references.
91
+ */
92
+ class $RefParser {
93
+ constructor() {
94
+ /**
95
+ * The resolved JSON references
96
+ *
97
+ * @type {$Refs}
98
+ * @readonly
99
+ */
100
+ this.$refs = new refs_js_1.default();
101
+ this.options = (0, options_js_1.getJsonSchemaRefParserDefaultOptions)();
102
+ /**
103
+ * The parsed (and possibly dereferenced) JSON schema object
104
+ *
105
+ * @type {object}
106
+ * @readonly
107
+ */
108
+ this.schema = null;
109
+ }
110
+ /**
111
+ * Bundles all referenced files/URLs into a single schema that only has internal `$ref` pointers. This lets you split-up your schema however you want while you're building it, but easily combine all those files together when it's time to package or distribute the schema to other people. The resulting schema size will be small, since it will still contain internal JSON references rather than being fully-dereferenced.
112
+ *
113
+ * This also eliminates the risk of circular references, so the schema can be safely serialized using `JSON.stringify()`.
114
+ *
115
+ * See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#bundleschema-options-callback
116
+ *
117
+ * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file.
118
+ */
119
+ async bundle({ arrayBuffer, pathOrUrlOrSchema, resolvedInput, }) {
120
+ await this.parse({ arrayBuffer, pathOrUrlOrSchema, resolvedInput });
121
+ await (0, resolve_external_js_1.resolveExternal)(this, this.options);
122
+ const errors = errors_js_1.JSONParserErrorGroup.getParserErrors(this);
123
+ if (errors.length > 0) {
124
+ throw new errors_js_1.JSONParserErrorGroup(this);
125
+ }
126
+ (0, bundle_js_1.default)(this, this.options);
127
+ const errors2 = errors_js_1.JSONParserErrorGroup.getParserErrors(this);
128
+ if (errors2.length > 0) {
129
+ throw new errors_js_1.JSONParserErrorGroup(this);
130
+ }
131
+ return this.schema;
132
+ }
133
+ /**
134
+ * Dereferences all `$ref` pointers in the JSON Schema, replacing each reference with its resolved value. This results in a schema object that does not contain any `$ref` pointers. Instead, it's a normal JavaScript object tree that can easily be crawled and used just like any other JavaScript object. This is great for programmatic usage, especially when using tools that don't understand JSON references.
135
+ *
136
+ * The dereference method maintains object reference equality, meaning that all `$ref` pointers that point to the same object will be replaced with references to the same object. Again, this is great for programmatic usage, but it does introduce the risk of circular references, so be careful if you intend to serialize the schema using `JSON.stringify()`. Consider using the bundle method instead, which does not create circular references.
137
+ *
138
+ * See https://apitools.dev/json-schema-ref-parser/docs/ref-parser.html#dereferenceschema-options-callback
139
+ *
140
+ * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file.
141
+ */
142
+ async dereference({ pathOrUrlOrSchema, }) {
143
+ await this.parse({ pathOrUrlOrSchema });
144
+ await (0, resolve_external_js_1.resolveExternal)(this, this.options);
145
+ const errors = errors_js_1.JSONParserErrorGroup.getParserErrors(this);
146
+ if (errors.length > 0) {
147
+ throw new errors_js_1.JSONParserErrorGroup(this);
148
+ }
149
+ (0, dereference_js_1.default)(this, this.options);
150
+ const errors2 = errors_js_1.JSONParserErrorGroup.getParserErrors(this);
151
+ if (errors2.length > 0) {
152
+ throw new errors_js_1.JSONParserErrorGroup(this);
153
+ }
154
+ return this.schema;
155
+ }
156
+ /**
157
+ * Parses the given JSON schema.
158
+ * This method does not resolve any JSON references.
159
+ * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
160
+ *
161
+ * @param pathOrUrlOrSchema A JSON Schema object, or the file path or URL of a JSON Schema file.
162
+ * @returns - The returned promise resolves with the parsed JSON schema object.
163
+ */
164
+ async parse({ arrayBuffer, pathOrUrlOrSchema, resolvedInput: _resolvedInput, }) {
165
+ const resolvedInput = _resolvedInput || (0, exports.getResolvedInput)({ pathOrUrlOrSchema });
166
+ const { path, type } = resolvedInput;
167
+ let { schema } = resolvedInput;
168
+ // reset everything
169
+ this.schema = null;
170
+ this.$refs = new refs_js_1.default();
171
+ if (schema) {
172
+ // immediately add a new $Ref with the schema object as value
173
+ const $ref = this.$refs._add(path);
174
+ $ref.pathType = url.isFileSystemPath(path) ? 'file' : 'http';
175
+ $ref.value = schema;
176
+ }
177
+ else if (type !== 'json') {
178
+ const file = (0, parse_js_1.newFile)(path);
179
+ // Add a new $Ref for this file, even though we don't have the value yet.
180
+ // This ensures that we don't simultaneously read & parse the same file multiple times
181
+ const $refAdded = this.$refs._add(file.url);
182
+ $refAdded.pathType = type;
183
+ try {
184
+ const resolver = type === 'file' ? file_js_1.fileResolver : url_js_1.urlResolver;
185
+ await resolver.handler(file, arrayBuffer);
186
+ const parseResult = await (0, parse_js_1.parseFile)(file, this.options);
187
+ $refAdded.value = parseResult.result;
188
+ schema = parseResult.result;
189
+ }
190
+ catch (err) {
191
+ if ((0, errors_js_1.isHandledError)(err)) {
192
+ $refAdded.value = err;
193
+ }
194
+ throw err;
195
+ }
196
+ }
197
+ if (schema === null || typeof schema !== 'object' || Buffer.isBuffer(schema)) {
198
+ throw ono_1.ono.syntax(`"${this.$refs._root$Ref.path || schema}" is not a valid JSON Schema`);
199
+ }
200
+ this.schema = schema;
201
+ return {
202
+ schema,
203
+ };
204
+ }
205
+ }
206
+ exports.$RefParser = $RefParser;
207
+ var url_js_2 = require("./resolvers/url.js");
208
+ Object.defineProperty(exports, "sendRequest", { enumerable: true, get: function () { return url_js_2.sendRequest; } });
@@ -0,0 +1,61 @@
1
+ import type { JSONSchemaObject, Plugin } from "./types/index.js";
2
+ export interface DereferenceOptions {
3
+ /**
4
+ * Determines whether circular `$ref` pointers are handled.
5
+ *
6
+ * If set to `false`, then a `ReferenceError` will be thrown if the schema contains any circular references.
7
+ *
8
+ * If set to `"ignore"`, then circular references will simply be ignored. No error will be thrown, but the `$Refs.circular` property will still be set to `true`.
9
+ */
10
+ circular?: boolean | "ignore";
11
+ /**
12
+ * A function, called for each path, which can return true to stop this path and all
13
+ * subpaths from being dereferenced further. This is useful in schemas where some
14
+ * subpaths contain literal $ref keys that should not be dereferenced.
15
+ */
16
+ excludedPathMatcher?(path: string): boolean;
17
+ /**
18
+ * Callback invoked during dereferencing.
19
+ *
20
+ * @argument {string} path - The path being dereferenced (ie. the `$ref` string)
21
+ * @argument {JSONSchemaObject} value - The JSON-Schema that the `$ref` resolved to
22
+ * @argument {JSONSchemaObject} parent - The parent of the dereferenced object
23
+ * @argument {string} parentPropName - The prop name of the parent object whose value was dereferenced
24
+ */
25
+ onDereference?(path: string, value: JSONSchemaObject, parent?: JSONSchemaObject, parentPropName?: string): void;
26
+ }
27
+ /**
28
+ * Options that determine how JSON schemas are parsed, resolved, and dereferenced.
29
+ *
30
+ * @param [options] - Overridden options
31
+ * @class
32
+ */
33
+ export interface $RefParserOptions {
34
+ /**
35
+ * The `dereference` options control how JSON Schema `$Ref` Parser will dereference `$ref` pointers within the JSON schema.
36
+ */
37
+ dereference: DereferenceOptions;
38
+ /**
39
+ * The `parse` options determine how different types of files will be parsed.
40
+ *
41
+ * JSON Schema `$Ref` Parser comes with built-in JSON, YAML, plain-text, and binary parsers, any of which you can configure or disable. You can also add your own custom parsers if you want.
42
+ */
43
+ parse: {
44
+ binary: Plugin;
45
+ json: Plugin;
46
+ text: Plugin;
47
+ yaml: Plugin;
48
+ };
49
+ /**
50
+ * The maximum amount of time (in milliseconds) that JSON Schema $Ref Parser will spend dereferencing a single schema.
51
+ * It will throw a timeout error if the operation takes longer than this.
52
+ */
53
+ timeoutMs?: number;
54
+ }
55
+ export declare const getJsonSchemaRefParserDefaultOptions: () => $RefParserOptions;
56
+ export type Options = $RefParserOptions;
57
+ type DeepPartial<T> = T extends object ? {
58
+ [P in keyof T]?: DeepPartial<T[P]>;
59
+ } : T;
60
+ export type ParserOptions = DeepPartial<$RefParserOptions>;
61
+ export {};
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getJsonSchemaRefParserDefaultOptions = void 0;
4
+ const json_js_1 = require("./parsers/json.js");
5
+ const yaml_js_1 = require("./parsers/yaml.js");
6
+ const text_js_1 = require("./parsers/text.js");
7
+ const binary_js_1 = require("./parsers/binary.js");
8
+ const getJsonSchemaRefParserDefaultOptions = () => ({
9
+ /**
10
+ * Determines the types of JSON references that are allowed.
11
+ */
12
+ dereference: {
13
+ /**
14
+ * Dereference circular (recursive) JSON references?
15
+ * If false, then a {@link ReferenceError} will be thrown if a circular reference is found.
16
+ * If "ignore", then circular references will not be dereferenced.
17
+ *
18
+ * @type {boolean|string}
19
+ */
20
+ circular: true,
21
+ /**
22
+ * A function, called for each path, which can return true to stop this path and all
23
+ * subpaths from being dereferenced further. This is useful in schemas where some
24
+ * subpaths contain literal $ref keys that should not be dereferenced.
25
+ *
26
+ * @type {function}
27
+ */
28
+ excludedPathMatcher: () => false,
29
+ // @ts-expect-error
30
+ referenceResolution: "relative",
31
+ },
32
+ /**
33
+ * Determines how different types of files will be parsed.
34
+ *
35
+ * You can add additional parsers of your own, replace an existing one with
36
+ * your own implementation, or disable any parser by setting it to false.
37
+ */
38
+ parse: {
39
+ binary: { ...binary_js_1.binaryParser },
40
+ json: { ...json_js_1.jsonParser },
41
+ text: { ...text_js_1.textParser },
42
+ yaml: { ...yaml_js_1.yamlParser },
43
+ },
44
+ });
45
+ exports.getJsonSchemaRefParserDefaultOptions = getJsonSchemaRefParserDefaultOptions;
@@ -0,0 +1,13 @@
1
+ import type { PluginResult } from "./util/plugins.js";
2
+ import type { $RefParserOptions } from "./options.js";
3
+ import type { FileInfo } from "./types/index.js";
4
+ /**
5
+ * Prepares the file object so we can populate it with data and other values
6
+ * when it's read and parsed. This "file object" will be passed to all
7
+ * resolvers and parsers.
8
+ */
9
+ export declare function newFile(path: string): FileInfo;
10
+ /**
11
+ * Parses the given file's contents, using the configured parser plugins.
12
+ */
13
+ export declare const parseFile: (file: FileInfo, options: $RefParserOptions) => Promise<PluginResult>;