@apidevtools/json-schema-ref-parser 10.0.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/lib/bundle.d.ts +10 -0
  2. package/dist/lib/bundle.js +265 -0
  3. package/dist/lib/dereference.d.ts +9 -0
  4. package/dist/lib/dereference.js +206 -0
  5. package/dist/lib/index.d.ts +206 -0
  6. package/dist/lib/index.js +223 -0
  7. package/dist/lib/normalize-args.d.ts +10 -0
  8. package/dist/lib/normalize-args.js +42 -0
  9. package/dist/lib/options.d.ts +77 -0
  10. package/dist/lib/options.js +119 -0
  11. package/dist/lib/parse.d.ts +8 -0
  12. package/dist/lib/parse.js +177 -0
  13. package/dist/lib/parsers/binary.d.ts +3 -0
  14. package/dist/lib/parsers/binary.js +35 -0
  15. package/dist/lib/parsers/json.d.ts +3 -0
  16. package/dist/lib/parsers/json.js +57 -0
  17. package/dist/lib/parsers/text.d.ts +3 -0
  18. package/dist/lib/parsers/text.js +42 -0
  19. package/dist/lib/parsers/yaml.d.ts +3 -0
  20. package/dist/lib/parsers/yaml.js +65 -0
  21. package/dist/lib/pointer.d.ts +87 -0
  22. package/dist/lib/pointer.js +256 -0
  23. package/dist/lib/ref.d.ts +181 -0
  24. package/dist/lib/ref.js +239 -0
  25. package/dist/lib/refs.d.ts +127 -0
  26. package/dist/lib/refs.js +223 -0
  27. package/dist/lib/resolve-external.d.ts +14 -0
  28. package/dist/lib/resolve-external.js +148 -0
  29. package/dist/lib/resolvers/file.d.ts +3 -0
  30. package/dist/lib/resolvers/file.js +76 -0
  31. package/dist/lib/resolvers/http.d.ts +3 -0
  32. package/dist/lib/resolvers/http.js +159 -0
  33. package/dist/lib/types/index.d.ts +104 -0
  34. package/dist/lib/types/index.js +2 -0
  35. package/dist/lib/util/errors.d.ts +50 -0
  36. package/dist/lib/util/errors.js +106 -0
  37. package/dist/lib/util/maybe.d.ts +3 -0
  38. package/dist/lib/util/maybe.js +24 -0
  39. package/dist/lib/util/next.d.ts +2 -0
  40. package/dist/lib/util/next.js +16 -0
  41. package/dist/lib/util/plugins.d.ts +36 -0
  42. package/dist/lib/util/plugins.js +144 -0
  43. package/dist/lib/util/url.d.ts +93 -0
  44. package/{cjs → dist/lib}/util/url.js +134 -102
  45. package/dist/vite.config.d.ts +2 -0
  46. package/dist/vite.config.js +23 -0
  47. package/lib/{bundle.js → bundle.ts} +105 -101
  48. package/lib/{dereference.js → dereference.ts} +113 -52
  49. package/lib/index.ts +413 -0
  50. package/lib/{normalize-args.js → normalize-args.ts} +7 -14
  51. package/lib/options.ts +202 -0
  52. package/lib/parse.ts +153 -0
  53. package/lib/parsers/binary.ts +39 -0
  54. package/lib/parsers/{json.js → json.ts} +9 -22
  55. package/lib/parsers/text.ts +46 -0
  56. package/lib/parsers/{yaml.js → yaml.ts} +15 -19
  57. package/lib/pointer.ts +296 -0
  58. package/lib/ref.ts +288 -0
  59. package/lib/refs.ts +238 -0
  60. package/lib/{resolve-external.js → resolve-external.ts} +39 -36
  61. package/lib/resolvers/file.ts +40 -0
  62. package/lib/resolvers/http.ts +136 -0
  63. package/lib/tsconfig.json +103 -0
  64. package/lib/types/index.ts +135 -0
  65. package/lib/util/errors.ts +141 -0
  66. package/lib/util/maybe.ts +22 -0
  67. package/lib/util/next.ts +13 -0
  68. package/lib/util/{plugins.js → plugins.ts} +58 -57
  69. package/lib/util/{url.js → url.ts} +64 -83
  70. package/package.json +44 -45
  71. package/cjs/bundle.js +0 -304
  72. package/cjs/dereference.js +0 -258
  73. package/cjs/index.js +0 -603
  74. package/cjs/normalize-args.js +0 -64
  75. package/cjs/options.js +0 -125
  76. package/cjs/package.json +0 -3
  77. package/cjs/parse.js +0 -338
  78. package/cjs/parsers/binary.js +0 -54
  79. package/cjs/parsers/json.js +0 -199
  80. package/cjs/parsers/text.js +0 -61
  81. package/cjs/parsers/yaml.js +0 -239
  82. package/cjs/pointer.js +0 -290
  83. package/cjs/ref.js +0 -333
  84. package/cjs/refs.js +0 -214
  85. package/cjs/resolve-external.js +0 -333
  86. package/cjs/resolvers/file.js +0 -106
  87. package/cjs/resolvers/http.js +0 -184
  88. package/cjs/util/errors.js +0 -401
  89. package/cjs/util/plugins.js +0 -159
  90. package/cjs/util/projectDir.cjs +0 -6
  91. package/lib/index.d.ts +0 -496
  92. package/lib/index.js +0 -290
  93. package/lib/options.js +0 -128
  94. package/lib/parse.js +0 -162
  95. package/lib/parsers/binary.js +0 -53
  96. package/lib/parsers/text.js +0 -64
  97. package/lib/pointer.js +0 -293
  98. package/lib/ref.js +0 -292
  99. package/lib/refs.js +0 -196
  100. package/lib/resolvers/file.js +0 -63
  101. package/lib/resolvers/http.js +0 -155
  102. package/lib/util/errors.js +0 -134
  103. package/lib/util/projectDir.cjs +0 -6
@@ -0,0 +1,159 @@
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 (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ const ono_1 = require("@jsdevtools/ono");
36
+ const url = __importStar(require("../util/url.js"));
37
+ const errors_js_1 = require("../util/errors.js");
38
+ exports.default = {
39
+ /**
40
+ * The order that this resolver will run, in relation to other resolvers.
41
+ */
42
+ order: 200,
43
+ /**
44
+ * HTTP headers to send when downloading files.
45
+ *
46
+ * @example:
47
+ * {
48
+ * "User-Agent": "JSON Schema $Ref Parser",
49
+ * Accept: "application/json"
50
+ * }
51
+ */
52
+ headers: null,
53
+ /**
54
+ * HTTP request timeout (in milliseconds).
55
+ */
56
+ timeout: 5000,
57
+ /**
58
+ * The maximum number of HTTP redirects to follow.
59
+ * To disable automatic following of redirects, set this to zero.
60
+ */
61
+ redirects: 5,
62
+ /**
63
+ * The `withCredentials` option of XMLHttpRequest.
64
+ * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
65
+ */
66
+ withCredentials: false,
67
+ /**
68
+ * Determines whether this resolver can read a given file reference.
69
+ * Resolvers that return true will be tried in order, until one successfully resolves the file.
70
+ * Resolvers that return false will not be given a chance to resolve the file.
71
+ */
72
+ canRead(file) {
73
+ return url.isHttp(file.url);
74
+ },
75
+ /**
76
+ * Reads the given URL and returns its raw contents as a Buffer.
77
+ */
78
+ read(file) {
79
+ const u = url.parse(file.url);
80
+ if (typeof window !== "undefined" && !u.protocol) {
81
+ // Use the protocol of the current page
82
+ u.protocol = url.parse(location.href).protocol;
83
+ }
84
+ return download(u, this);
85
+ },
86
+ };
87
+ /**
88
+ * Downloads the given file.
89
+ * @returns
90
+ * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error.
91
+ */
92
+ function download(u, httpOptions, _redirects) {
93
+ return __awaiter(this, void 0, void 0, function* () {
94
+ u = url.parse(u);
95
+ const redirects = _redirects || [];
96
+ redirects.push(u.href);
97
+ try {
98
+ const res = yield get(u, httpOptions);
99
+ if (res.status >= 400) {
100
+ throw (0, ono_1.ono)({ status: res.status }, `HTTP ERROR ${res.status}`);
101
+ }
102
+ else if (res.status >= 300) {
103
+ if (!Number.isNaN(httpOptions.redirects) && redirects.length > httpOptions.redirects) {
104
+ throw new errors_js_1.ResolverError((0, ono_1.ono)({ status: res.status }, `Error downloading ${redirects[0]}. \nToo many redirects: \n ${redirects.join(" \n ")}`));
105
+ }
106
+ else if (!("location" in res.headers) || !res.headers.location) {
107
+ throw (0, ono_1.ono)({ status: res.status }, `HTTP ${res.status} redirect with no location header`);
108
+ }
109
+ else {
110
+ const redirectTo = url.resolve(u, res.headers.location);
111
+ return download(redirectTo, httpOptions, redirects);
112
+ }
113
+ }
114
+ else {
115
+ if (res.body) {
116
+ const buf = yield res.arrayBuffer();
117
+ return Buffer.from(buf);
118
+ }
119
+ return Buffer.alloc(0);
120
+ }
121
+ }
122
+ catch (err) {
123
+ throw new errors_js_1.ResolverError((0, ono_1.ono)(err, `Error downloading ${u.href}`), u.href);
124
+ }
125
+ });
126
+ }
127
+ /**
128
+ * Sends an HTTP GET request.
129
+ * The promise resolves with the HTTP Response object.
130
+ */
131
+ function get(u, httpOptions) {
132
+ return __awaiter(this, void 0, void 0, function* () {
133
+ let controller;
134
+ let timeoutId;
135
+ if (httpOptions.timeout) {
136
+ controller = new AbortController();
137
+ timeoutId = setTimeout(() => controller.abort(), httpOptions.timeout);
138
+ }
139
+ if (!global.fetch) {
140
+ const { default: fetch, Request, Headers } = yield Promise.resolve().then(() => __importStar(require("node-fetch")));
141
+ // @ts-ignore
142
+ global.fetch = fetch;
143
+ // @ts-ignore
144
+ global.Request = Request;
145
+ // @ts-ignore
146
+ global.Headers = Headers;
147
+ }
148
+ const response = yield fetch(u, {
149
+ method: "GET",
150
+ headers: httpOptions.headers || {},
151
+ credentials: httpOptions.withCredentials ? "include" : "same-origin",
152
+ signal: controller ? controller.signal : null,
153
+ });
154
+ if (timeoutId) {
155
+ clearTimeout(timeoutId);
156
+ }
157
+ return response;
158
+ });
159
+ }
@@ -0,0 +1,104 @@
1
+ /// <reference types="node" />
2
+ import type { JSONSchema4, JSONSchema4Object, JSONSchema6, JSONSchema6Object, JSONSchema7, JSONSchema7Object } from "json-schema";
3
+ import type $Refs from "../refs.js";
4
+ export type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7;
5
+ export type JSONSchemaObject = JSONSchema4Object | JSONSchema6Object | JSONSchema7Object;
6
+ export type SchemaCallback = (err: Error | null, schema?: JSONSchema | object) => any;
7
+ export type $RefsCallback = (err: Error | null, $refs?: $Refs) => any;
8
+ /**
9
+ * See https://apitools.dev/json-schema-ref-parser/docs/options.html
10
+ */
11
+ export interface HTTPResolverOptions extends Partial<ResolverOptions> {
12
+ /**
13
+ * You can specify any HTTP headers that should be sent when downloading files. For example, some servers may require you to set the `Accept` or `Referrer` header.
14
+ */
15
+ headers?: HeadersInit | null;
16
+ /**
17
+ * The amount of time (in milliseconds) to wait for a response from the server when downloading files. The default is 5 seconds.
18
+ */
19
+ timeout?: number;
20
+ /**
21
+ * The maximum number of HTTP redirects to follow per file. The default is 5. To disable automatic following of redirects, set this to zero.
22
+ */
23
+ redirects?: number;
24
+ /**
25
+ * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
26
+ */
27
+ withCredentials?: boolean;
28
+ }
29
+ /**
30
+ * JSON Schema `$Ref` Parser comes with built-in resolvers for HTTP and HTTPS URLs, as well as local filesystem paths (when running in Node.js). You can add your own custom resolvers to support additional protocols, or even replace any of the built-in resolvers with your own custom implementation.
31
+ *
32
+ * See https://apitools.dev/json-schema-ref-parser/docs/plugins/resolvers.html
33
+ */
34
+ export interface ResolverOptions {
35
+ name?: string;
36
+ /**
37
+ * All resolvers have an order property, even the built-in resolvers. If you don't specify an order property, then your resolver will run last. Specifying `order: 1`, like we did in this example, will make your resolver run first. Or you can squeeze your resolver in-between some of the built-in resolvers. For example, `order: 101` would make it run after the file resolver, but before the HTTP resolver. You can see the order of all the built-in resolvers by looking at their source code.
38
+ *
39
+ * The order property and canRead property are related to each other. For each file that JSON Schema $Ref Parser needs to resolve, it first determines which resolvers can read that file by checking their canRead property. If only one resolver matches a file, then only that one resolver is called, regardless of its order. If multiple resolvers match a file, then those resolvers are tried in order until one of them successfully reads the file. Once a resolver successfully reads the file, the rest of the resolvers are skipped.
40
+ */
41
+ order?: number;
42
+ /**
43
+ * The `canRead` property tells JSON Schema `$Ref` Parser what kind of files your resolver can read. In this example, we've simply specified a regular expression that matches "mogodb://" URLs, but we could have used a simple boolean, or even a function with custom logic to determine which files to resolve. Here are examples of each approach:
44
+ */
45
+ canRead: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
46
+ /**
47
+ * This is where the real work of a resolver happens. The `read` method accepts the same file info object as the `canRead` function, but rather than returning a boolean value, the `read` method should return the contents of the file. The file contents should be returned in as raw a form as possible, such as a string or a byte array. Any further parsing or processing should be done by parsers.
48
+ *
49
+ * Unlike the `canRead` function, the `read` method can also be asynchronous. This might be important if your resolver needs to read data from a database or some other external source. You can return your asynchronous value using either an ES6 Promise or a Node.js-style error-first callback. Of course, if your resolver has the ability to return its data synchronously, then that's fine too. Here are examples of all three approaches:
50
+ */
51
+ read: string | object | ((file: FileInfo, callback?: (error: Error | null, data: string | null) => any) => string | Buffer | JSONSchema | Promise<string | Buffer | JSONSchema>);
52
+ }
53
+ export interface Plugin {
54
+ name?: string;
55
+ /**
56
+ * Parsers run in a specific order, relative to other parsers. For example, a parser with `order: 5` will run before a parser with `order: 10`. If a parser is unable to successfully parse a file, then the next parser is tried, until one succeeds or they all fail.
57
+ *
58
+ * You can change the order in which parsers run, which is useful if you know that most of your referenced files will be a certain type, or if you add your own custom parser that you want to run first.
59
+ */
60
+ order?: number;
61
+ /**
62
+ * All of the built-in parsers allow empty files by default. The JSON and YAML parsers will parse empty files as `undefined`. The text parser will parse empty files as an empty string. The binary parser will parse empty files as an empty byte array.
63
+ *
64
+ * You can set `allowEmpty: false` on any parser, which will cause an error to be thrown if a file empty.
65
+ */
66
+ allowEmpty?: boolean;
67
+ /**
68
+ * The encoding that the text is expected to be in.
69
+ */
70
+ encoding?: BufferEncoding;
71
+ /**
72
+ * Determines which parsers will be used for which files.
73
+ *
74
+ * A regular expression can be used to match files by their full path. A string (or array of strings) can be used to match files by their file extension. Or a function can be used to perform more complex matching logic. See the custom parser docs for details.
75
+ */
76
+ canParse?: boolean | RegExp | string | string[] | ((file: FileInfo) => boolean);
77
+ /**
78
+ * This is where the real work of a parser happens. The `parse` method accepts the same file info object as the `canParse` 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.
79
+ *
80
+ * Unlike the `canParse` 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:
81
+ */
82
+ parse: ((file: FileInfo, callback?: (error: Error | null, data: string | null) => any) => unknown | Promise<unknown>) | number | string;
83
+ }
84
+ /**
85
+ * JSON Schema `$Ref` Parser supports plug-ins, such as resolvers and parsers. These plug-ins can have methods such as `canRead()`, `read()`, `canParse()`, and `parse()`. All of these methods accept the same object as their parameter: an object containing information about the file being read or parsed.
86
+ *
87
+ * 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.
88
+ *
89
+ * See https://apitools.dev/json-schema-ref-parser/docs/plugins/file-info-object.html
90
+ */
91
+ export interface FileInfo {
92
+ /**
93
+ * 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).
94
+ */
95
+ url: string;
96
+ /**
97
+ * The lowercase file extension, such as ".json", ".yaml", ".txt", etc.
98
+ */
99
+ extension: string;
100
+ /**
101
+ * The raw file contents, in whatever form they were returned by the resolver that read the file.
102
+ */
103
+ data: string | Buffer;
104
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,50 @@
1
+ import type $RefParser from "../index.js";
2
+ export type JSONParserErrorType = "EUNKNOWN" | "EPARSER" | "EUNMATCHEDPARSER" | "ERESOLVER" | "EUNMATCHEDRESOLVER" | "EMISSINGPOINTER" | "EINVALIDPOINTER";
3
+ export declare class JSONParserError extends Error {
4
+ readonly name: string;
5
+ readonly message: string;
6
+ source: string | undefined;
7
+ path: Array<string | number> | null;
8
+ readonly code: JSONParserErrorType;
9
+ constructor(message: string, source?: string);
10
+ get footprint(): string;
11
+ }
12
+ export declare class JSONParserErrorGroup extends Error {
13
+ files: $RefParser;
14
+ constructor(parser: $RefParser);
15
+ static getParserErrors(parser: any): any[];
16
+ get errors(): Array<JSONParserError | InvalidPointerError | ResolverError | ParserError | MissingPointerError | UnmatchedParserError | UnmatchedResolverError>;
17
+ }
18
+ export declare class ParserError extends JSONParserError {
19
+ code: JSONParserErrorType;
20
+ name: string;
21
+ constructor(message: any, source: any);
22
+ }
23
+ export declare class UnmatchedParserError extends JSONParserError {
24
+ code: JSONParserErrorType;
25
+ name: string;
26
+ constructor(source: string);
27
+ }
28
+ export declare class ResolverError extends JSONParserError {
29
+ code: JSONParserErrorType;
30
+ name: string;
31
+ ioErrorCode?: string;
32
+ constructor(ex: Error | any, source?: string);
33
+ }
34
+ export declare class UnmatchedResolverError extends JSONParserError {
35
+ code: JSONParserErrorType;
36
+ name: string;
37
+ constructor(source: any);
38
+ }
39
+ export declare class MissingPointerError extends JSONParserError {
40
+ code: JSONParserErrorType;
41
+ name: string;
42
+ constructor(token: any, path: any);
43
+ }
44
+ export declare class InvalidPointerError extends JSONParserError {
45
+ code: JSONParserErrorType;
46
+ name: string;
47
+ constructor(pointer: any, path: any);
48
+ }
49
+ export declare function isHandledError(err: any): err is JSONParserError;
50
+ export declare function normalizeError(err: any): any;
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeError = exports.isHandledError = exports.InvalidPointerError = exports.MissingPointerError = exports.UnmatchedResolverError = exports.ResolverError = exports.UnmatchedParserError = exports.ParserError = exports.JSONParserErrorGroup = exports.JSONParserError = void 0;
4
+ const ono_1 = require("@jsdevtools/ono");
5
+ const url_js_1 = require("./url.js");
6
+ class JSONParserError extends Error {
7
+ constructor(message, source) {
8
+ super();
9
+ this.code = "EUNKNOWN";
10
+ this.name = "JSONParserError";
11
+ this.message = message;
12
+ this.source = source;
13
+ this.path = null;
14
+ ono_1.Ono.extend(this);
15
+ }
16
+ get footprint() {
17
+ return `${this.path}+${this.source}+${this.code}+${this.message}`;
18
+ }
19
+ }
20
+ exports.JSONParserError = JSONParserError;
21
+ class JSONParserErrorGroup extends Error {
22
+ constructor(parser) {
23
+ super();
24
+ this.files = parser;
25
+ this.name = "JSONParserErrorGroup";
26
+ this.message = `${this.errors.length} error${this.errors.length > 1 ? "s" : ""} occurred while reading '${(0, url_js_1.toFileSystemPath)(parser.$refs._root$Ref.path)}'`;
27
+ ono_1.Ono.extend(this);
28
+ }
29
+ static getParserErrors(parser) {
30
+ const errors = [];
31
+ for (const $ref of Object.values(parser.$refs._$refs)) {
32
+ // @ts-expect-error TS(2571): Object is of type 'unknown'.
33
+ if ($ref.errors) {
34
+ // @ts-expect-error TS(2571): Object is of type 'unknown'.
35
+ errors.push(...$ref.errors);
36
+ }
37
+ }
38
+ return errors;
39
+ }
40
+ get errors() {
41
+ return JSONParserErrorGroup.getParserErrors(this.files);
42
+ }
43
+ }
44
+ exports.JSONParserErrorGroup = JSONParserErrorGroup;
45
+ class ParserError extends JSONParserError {
46
+ constructor(message, source) {
47
+ super(`Error parsing ${source}: ${message}`, source);
48
+ this.code = "EPARSER";
49
+ this.name = "ParserError";
50
+ }
51
+ }
52
+ exports.ParserError = ParserError;
53
+ class UnmatchedParserError extends JSONParserError {
54
+ constructor(source) {
55
+ super(`Could not find parser for "${source}"`, source);
56
+ this.code = "EUNMATCHEDPARSER";
57
+ this.name = "UnmatchedParserError";
58
+ }
59
+ }
60
+ exports.UnmatchedParserError = UnmatchedParserError;
61
+ class ResolverError extends JSONParserError {
62
+ constructor(ex, source) {
63
+ super(ex.message || `Error reading file "${source}"`, source);
64
+ this.code = "ERESOLVER";
65
+ this.name = "ResolverError";
66
+ if ("code" in ex) {
67
+ this.ioErrorCode = String(ex.code);
68
+ }
69
+ }
70
+ }
71
+ exports.ResolverError = ResolverError;
72
+ class UnmatchedResolverError extends JSONParserError {
73
+ constructor(source) {
74
+ super(`Could not find resolver for "${source}"`, source);
75
+ this.code = "EUNMATCHEDRESOLVER";
76
+ this.name = "UnmatchedResolverError";
77
+ }
78
+ }
79
+ exports.UnmatchedResolverError = UnmatchedResolverError;
80
+ class MissingPointerError extends JSONParserError {
81
+ constructor(token, path) {
82
+ super(`Token "${token}" does not exist.`, (0, url_js_1.stripHash)(path));
83
+ this.code = "EUNMATCHEDRESOLVER";
84
+ this.name = "MissingPointerError";
85
+ }
86
+ }
87
+ exports.MissingPointerError = MissingPointerError;
88
+ class InvalidPointerError extends JSONParserError {
89
+ constructor(pointer, path) {
90
+ super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, (0, url_js_1.stripHash)(path));
91
+ this.code = "EUNMATCHEDRESOLVER";
92
+ this.name = "InvalidPointerError";
93
+ }
94
+ }
95
+ exports.InvalidPointerError = InvalidPointerError;
96
+ function isHandledError(err) {
97
+ return err instanceof JSONParserError || err instanceof JSONParserErrorGroup;
98
+ }
99
+ exports.isHandledError = isHandledError;
100
+ function normalizeError(err) {
101
+ if (err.path === null) {
102
+ err.path = [];
103
+ }
104
+ return err;
105
+ }
106
+ exports.normalizeError = normalizeError;
@@ -0,0 +1,3 @@
1
+ type MaybeParams<T> = (err: Error | any | null, result?: T) => void;
2
+ export default function maybe<T>(cb: MaybeParams<T> | undefined, promise: Promise<T>): Promise<T> | void;
3
+ export {};
@@ -0,0 +1,24 @@
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
+ const next_js_1 = __importDefault(require("./next.js"));
7
+ function maybe(cb, promise) {
8
+ if (cb) {
9
+ promise.then(function (result) {
10
+ (0, next_js_1.default)(function () {
11
+ cb(null, result);
12
+ });
13
+ }, function (err) {
14
+ (0, next_js_1.default)(function () {
15
+ cb(err);
16
+ });
17
+ });
18
+ return undefined;
19
+ }
20
+ else {
21
+ return promise;
22
+ }
23
+ }
24
+ exports.default = maybe;
@@ -0,0 +1,2 @@
1
+ declare const _default: (callback: Function, ...args: any[]) => void;
2
+ export default _default;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function makeNext() {
4
+ if (typeof process === "object" && typeof process.nextTick === "function") {
5
+ return process.nextTick;
6
+ }
7
+ else if (typeof setImmediate === "function") {
8
+ return setImmediate;
9
+ }
10
+ else {
11
+ return function next(f) {
12
+ setTimeout(f, 0);
13
+ };
14
+ }
15
+ }
16
+ exports.default = makeNext();
@@ -0,0 +1,36 @@
1
+ /// <reference types="node" />
2
+ import type { FileInfo } from "../types/index.js";
3
+ import type $RefParserOptions from "../options.js";
4
+ import type { ResolverOptions } from "../types/index.js";
5
+ import type $Refs from "../refs.js";
6
+ import type { Plugin } from "../types/index.js";
7
+ import type { JSONSchema } from "../types/index.js";
8
+ /**
9
+ * Returns the given plugins as an array, rather than an object map.
10
+ * All other methods in this module expect an array of plugins rather than an object map.
11
+ *
12
+ * @returns
13
+ */
14
+ export declare function all(plugins: $RefParserOptions["resolve"]): Plugin[];
15
+ /**
16
+ * Filters the given plugins, returning only the ones return `true` for the given method.
17
+ */
18
+ export declare function filter(plugins: Plugin[], method: any, file: any): Plugin[];
19
+ /**
20
+ * Sorts the given plugins, in place, by their `order` property.
21
+ */
22
+ export declare function sort(plugins: Plugin[]): Plugin[];
23
+ export interface PluginResult {
24
+ plugin: Plugin;
25
+ result?: string | Buffer | JSONSchema;
26
+ error?: any;
27
+ }
28
+ /**
29
+ * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
30
+ * Each method can return a synchronous value, a Promise, or call an error-first callback.
31
+ * If the promise resolves successfully, or the callback is called without an error, then the result
32
+ * is immediately returned and no further plugins are called.
33
+ * If the promise rejects, or the callback is called with an error, then the next plugin is called.
34
+ * If ALL plugins fail, then the last error is thrown.
35
+ */
36
+ export declare function run(plugins: Plugin[], method: keyof Plugin | keyof ResolverOptions, file: FileInfo, $refs: $Refs): Promise<PluginResult>;
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.run = exports.sort = exports.filter = exports.all = void 0;
13
+ /**
14
+ * Returns the given plugins as an array, rather than an object map.
15
+ * All other methods in this module expect an array of plugins rather than an object map.
16
+ *
17
+ * @returns
18
+ */
19
+ function all(plugins) {
20
+ return Object.keys(plugins)
21
+ .filter((key) => {
22
+ return typeof plugins[key] === "object";
23
+ })
24
+ .map((key) => {
25
+ plugins[key].name = key;
26
+ return plugins[key];
27
+ });
28
+ }
29
+ exports.all = all;
30
+ /**
31
+ * Filters the given plugins, returning only the ones return `true` for the given method.
32
+ */
33
+ function filter(plugins, method, file) {
34
+ return plugins.filter((plugin) => {
35
+ return !!getResult(plugin, method, file);
36
+ });
37
+ }
38
+ exports.filter = filter;
39
+ /**
40
+ * Sorts the given plugins, in place, by their `order` property.
41
+ */
42
+ function sort(plugins) {
43
+ for (const plugin of plugins) {
44
+ plugin.order = plugin.order || Number.MAX_SAFE_INTEGER;
45
+ }
46
+ return plugins.sort((a, b) => {
47
+ return a.order - b.order;
48
+ });
49
+ }
50
+ exports.sort = sort;
51
+ /**
52
+ * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
53
+ * Each method can return a synchronous value, a Promise, or call an error-first callback.
54
+ * If the promise resolves successfully, or the callback is called without an error, then the result
55
+ * is immediately returned and no further plugins are called.
56
+ * If the promise rejects, or the callback is called with an error, then the next plugin is called.
57
+ * If ALL plugins fail, then the last error is thrown.
58
+ */
59
+ function run(plugins, method, file, $refs) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ let plugin;
62
+ let lastError;
63
+ let index = 0;
64
+ return new Promise((resolve, reject) => {
65
+ runNextPlugin();
66
+ function runNextPlugin() {
67
+ plugin = plugins[index++];
68
+ if (!plugin) {
69
+ // There are no more functions, so re-throw the last error
70
+ return reject(lastError);
71
+ }
72
+ try {
73
+ // console.log(' %s', plugin.name);
74
+ const result = getResult(plugin, method, file, callback, $refs);
75
+ if (result && typeof result.then === "function") {
76
+ // A promise was returned
77
+ result.then(onSuccess, onError);
78
+ }
79
+ else if (result !== undefined) {
80
+ // A synchronous result was returned
81
+ onSuccess(result);
82
+ }
83
+ else if (index === plugins.length) {
84
+ throw new Error("No promise has been returned or callback has been called.");
85
+ }
86
+ }
87
+ catch (e) {
88
+ onError(e);
89
+ }
90
+ }
91
+ function callback(err, result) {
92
+ if (err) {
93
+ onError(err);
94
+ }
95
+ else {
96
+ onSuccess(result);
97
+ }
98
+ }
99
+ function onSuccess(result) {
100
+ // console.log(' success');
101
+ resolve({
102
+ plugin,
103
+ result,
104
+ });
105
+ }
106
+ function onError(error) {
107
+ // console.log(' %s', err.message || err);
108
+ lastError = {
109
+ plugin,
110
+ error,
111
+ };
112
+ runNextPlugin();
113
+ }
114
+ });
115
+ });
116
+ }
117
+ exports.run = run;
118
+ /**
119
+ * Returns the value of the given property.
120
+ * If the property is a function, then the result of the function is returned.
121
+ * If the value is a RegExp, then it will be tested against the file URL.
122
+ * If the value is an array, then it will be compared against the file extension.
123
+ */
124
+ function getResult(obj, prop, file, callback, $refs) {
125
+ const value = obj[prop];
126
+ if (typeof value === "function") {
127
+ return value.apply(obj, [file, callback, $refs]);
128
+ }
129
+ if (!callback) {
130
+ // The synchronous plugin functions (canParse and canRead)
131
+ // allow a "shorthand" syntax, where the user can match
132
+ // files by RegExp or by file extension.
133
+ if (value instanceof RegExp) {
134
+ return value.test(file.url);
135
+ }
136
+ else if (typeof value === "string") {
137
+ return value === file.extension;
138
+ }
139
+ else if (Array.isArray(value)) {
140
+ return value.indexOf(file.extension) !== -1;
141
+ }
142
+ }
143
+ return value;
144
+ }