@hey-api/json-schema-ref-parser 1.2.3 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +9 -84
  2. package/dist/index.d.mts +629 -0
  3. package/dist/index.d.mts.map +1 -0
  4. package/dist/index.mjs +1887 -0
  5. package/dist/index.mjs.map +1 -0
  6. package/package.json +42 -78
  7. package/src/__tests__/bundle.test.ts +59 -0
  8. package/src/__tests__/index.test.ts +43 -0
  9. package/src/__tests__/pointer.test.ts +34 -0
  10. package/src/__tests__/utils.ts +3 -0
  11. package/{lib → src}/bundle.ts +143 -229
  12. package/{lib → src}/dereference.ts +20 -43
  13. package/{lib → src}/index.ts +103 -125
  14. package/{lib → src}/options.ts +13 -9
  15. package/{lib → src}/parse.ts +19 -15
  16. package/src/parsers/binary.ts +13 -0
  17. package/{lib → src}/parsers/json.ts +5 -6
  18. package/src/parsers/text.ts +21 -0
  19. package/{lib → src}/parsers/yaml.ts +9 -9
  20. package/{lib → src}/pointer.ts +42 -23
  21. package/{lib → src}/ref.ts +25 -21
  22. package/{lib → src}/refs.ts +23 -26
  23. package/{lib → src}/resolve-external.ts +91 -60
  24. package/{lib → src}/resolvers/file.ts +7 -10
  25. package/{lib → src}/resolvers/url.ts +12 -8
  26. package/{lib → src}/types/index.ts +9 -2
  27. package/src/util/convert-path-to-posix.ts +8 -0
  28. package/{lib → src}/util/errors.ts +38 -36
  29. package/{lib → src}/util/is-windows.ts +1 -1
  30. package/{lib → src}/util/plugins.ts +7 -8
  31. package/{lib → src}/util/url.ts +41 -42
  32. package/dist/lib/__tests__/bundle.test.d.ts +0 -1
  33. package/dist/lib/__tests__/bundle.test.js +0 -50
  34. package/dist/lib/__tests__/index.test.d.ts +0 -1
  35. package/dist/lib/__tests__/index.test.js +0 -43
  36. package/dist/lib/__tests__/pointer.test.d.ts +0 -1
  37. package/dist/lib/__tests__/pointer.test.js +0 -27
  38. package/dist/lib/bundle.d.ts +0 -26
  39. package/dist/lib/bundle.js +0 -600
  40. package/dist/lib/dereference.d.ts +0 -11
  41. package/dist/lib/dereference.js +0 -226
  42. package/dist/lib/index.d.ts +0 -92
  43. package/dist/lib/index.js +0 -525
  44. package/dist/lib/options.d.ts +0 -61
  45. package/dist/lib/options.js +0 -45
  46. package/dist/lib/parse.d.ts +0 -13
  47. package/dist/lib/parse.js +0 -87
  48. package/dist/lib/parsers/binary.d.ts +0 -2
  49. package/dist/lib/parsers/binary.js +0 -12
  50. package/dist/lib/parsers/json.d.ts +0 -2
  51. package/dist/lib/parsers/json.js +0 -38
  52. package/dist/lib/parsers/text.d.ts +0 -2
  53. package/dist/lib/parsers/text.js +0 -18
  54. package/dist/lib/parsers/yaml.d.ts +0 -2
  55. package/dist/lib/parsers/yaml.js +0 -28
  56. package/dist/lib/pointer.d.ts +0 -88
  57. package/dist/lib/pointer.js +0 -297
  58. package/dist/lib/ref.d.ts +0 -180
  59. package/dist/lib/ref.js +0 -226
  60. package/dist/lib/refs.d.ts +0 -127
  61. package/dist/lib/refs.js +0 -232
  62. package/dist/lib/resolve-external.d.ts +0 -13
  63. package/dist/lib/resolve-external.js +0 -151
  64. package/dist/lib/resolvers/file.d.ts +0 -6
  65. package/dist/lib/resolvers/file.js +0 -61
  66. package/dist/lib/resolvers/url.d.ts +0 -17
  67. package/dist/lib/resolvers/url.js +0 -62
  68. package/dist/lib/types/index.d.ts +0 -43
  69. package/dist/lib/types/index.js +0 -2
  70. package/dist/lib/util/convert-path-to-posix.d.ts +0 -1
  71. package/dist/lib/util/convert-path-to-posix.js +0 -14
  72. package/dist/lib/util/errors.d.ts +0 -56
  73. package/dist/lib/util/errors.js +0 -112
  74. package/dist/lib/util/is-windows.d.ts +0 -1
  75. package/dist/lib/util/is-windows.js +0 -6
  76. package/dist/lib/util/plugins.d.ts +0 -16
  77. package/dist/lib/util/plugins.js +0 -45
  78. package/dist/lib/util/url.d.ts +0 -79
  79. package/dist/lib/util/url.js +0 -285
  80. package/dist/vite.config.d.ts +0 -2
  81. package/dist/vite.config.js +0 -19
  82. package/lib/__tests__/bundle.test.ts +0 -52
  83. package/lib/__tests__/index.test.ts +0 -45
  84. package/lib/__tests__/pointer.test.ts +0 -26
  85. package/lib/__tests__/spec/circular-ref-with-description.json +0 -11
  86. package/lib/__tests__/spec/multiple-refs.json +0 -34
  87. package/lib/__tests__/spec/openapi-paths-ref.json +0 -46
  88. package/lib/__tests__/spec/path-parameter.json +0 -16
  89. package/lib/parsers/binary.ts +0 -13
  90. package/lib/parsers/text.ts +0 -21
  91. package/lib/util/convert-path-to-posix.ts +0 -11
  92. /package/{LICENSE → LICENSE.md} +0 -0
@@ -1,112 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InvalidPointerError = exports.TimeoutError = exports.MissingPointerError = exports.UnmatchedResolverError = exports.ResolverError = exports.UnmatchedParserError = exports.ParserError = exports.JSONParserErrorGroup = exports.JSONParserError = void 0;
4
- exports.isHandledError = isHandledError;
5
- exports.normalizeError = normalizeError;
6
- const ono_1 = require("@jsdevtools/ono");
7
- const url_js_1 = require("./url.js");
8
- class JSONParserError extends Error {
9
- constructor(message, source) {
10
- super();
11
- this.code = "EUNKNOWN";
12
- this.name = "JSONParserError";
13
- this.message = message;
14
- this.source = source;
15
- this.path = null;
16
- ono_1.Ono.extend(this);
17
- }
18
- get footprint() {
19
- return `${this.path}+${this.source}+${this.code}+${this.message}`;
20
- }
21
- }
22
- exports.JSONParserError = JSONParserError;
23
- class JSONParserErrorGroup extends Error {
24
- constructor(parser) {
25
- super();
26
- this.files = parser;
27
- this.name = "JSONParserErrorGroup";
28
- this.message = `${this.errors.length} error${this.errors.length > 1 ? "s" : ""} occurred while reading '${(0, url_js_1.toFileSystemPath)(parser.$refs._root$Ref.path)}'`;
29
- ono_1.Ono.extend(this);
30
- }
31
- static getParserErrors(parser) {
32
- const errors = [];
33
- for (const $ref of Object.values(parser.$refs._$refs)) {
34
- if ($ref.errors) {
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(`Missing $ref pointer "${(0, url_js_1.getHash)(path)}". Token "${token}" does not exist.`, (0, url_js_1.stripHash)(path));
83
- this.code = "EMISSINGPOINTER";
84
- this.name = "MissingPointerError";
85
- }
86
- }
87
- exports.MissingPointerError = MissingPointerError;
88
- class TimeoutError extends JSONParserError {
89
- constructor(timeout) {
90
- super(`Dereferencing timeout reached: ${timeout}ms`);
91
- this.code = "ETIMEOUT";
92
- this.name = "TimeoutError";
93
- }
94
- }
95
- exports.TimeoutError = TimeoutError;
96
- class InvalidPointerError extends JSONParserError {
97
- constructor(pointer, path) {
98
- super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, (0, url_js_1.stripHash)(path));
99
- this.code = "EUNMATCHEDRESOLVER";
100
- this.name = "InvalidPointerError";
101
- }
102
- }
103
- exports.InvalidPointerError = InvalidPointerError;
104
- function isHandledError(err) {
105
- return err instanceof JSONParserError || err instanceof JSONParserErrorGroup;
106
- }
107
- function normalizeError(err) {
108
- if (err.path === null) {
109
- err.path = [];
110
- }
111
- return err;
112
- }
@@ -1 +0,0 @@
1
- export declare const isWindows: () => boolean;
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isWindows = void 0;
4
- const isWindowsConst = /^win/.test(globalThis.process ? globalThis.process.platform : "");
5
- const isWindows = () => isWindowsConst;
6
- exports.isWindows = isWindows;
@@ -1,16 +0,0 @@
1
- import type { FileInfo, JSONSchema } from "../types/index.js";
2
- import type { Plugin } from "../types/index.js";
3
- export interface PluginResult {
4
- error?: any;
5
- plugin: Pick<Plugin, 'handler'>;
6
- result?: string | Buffer | JSONSchema;
7
- }
8
- /**
9
- * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
10
- * Each method can return a synchronous value, a Promise, or call an error-first callback.
11
- * If the promise resolves successfully, or the callback is called without an error, then the result
12
- * is immediately returned and no further plugins are called.
13
- * If the promise rejects, or the callback is called with an error, then the next plugin is called.
14
- * If ALL plugins fail, then the last error is thrown.
15
- */
16
- export declare function run(plugins: Pick<Plugin, 'handler'>[], file: FileInfo): Promise<PluginResult>;
@@ -1,45 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.run = run;
4
- /**
5
- * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
6
- * Each method can return a synchronous value, a Promise, or call an error-first callback.
7
- * If the promise resolves successfully, or the callback is called without an error, then the result
8
- * is immediately returned and no further plugins are called.
9
- * If the promise rejects, or the callback is called with an error, then the next plugin is called.
10
- * If ALL plugins fail, then the last error is thrown.
11
- */
12
- async function run(plugins, file) {
13
- let index = 0;
14
- let lastError;
15
- let plugin;
16
- return new Promise((resolve, reject) => {
17
- const runNextPlugin = async () => {
18
- plugin = plugins[index++];
19
- if (!plugin) {
20
- // there are no more functions, re-throw the last error
21
- return reject(lastError);
22
- }
23
- try {
24
- const result = await plugin.handler(file);
25
- if (result !== undefined) {
26
- return resolve({
27
- plugin,
28
- result,
29
- });
30
- }
31
- if (index === plugins.length) {
32
- throw new Error("No promise has been returned.");
33
- }
34
- }
35
- catch (e) {
36
- lastError = {
37
- plugin,
38
- error: e,
39
- };
40
- runNextPlugin();
41
- }
42
- };
43
- runNextPlugin();
44
- });
45
- }
@@ -1,79 +0,0 @@
1
- /**
2
- * Returns resolved target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.
3
- *
4
- * @returns
5
- */
6
- export declare function resolve(from: string, to: string): string;
7
- /**
8
- * Returns the current working directory (in Node) or the current page URL (in browsers).
9
- *
10
- * @returns
11
- */
12
- export declare function cwd(): string;
13
- /**
14
- * Returns the protocol of the given URL, or `undefined` if it has no protocol.
15
- *
16
- * @param path
17
- * @returns
18
- */
19
- export declare function getProtocol(path: string | undefined): string | undefined;
20
- /**
21
- * Returns the lowercased file extension of the given URL,
22
- * or an empty string if it has no extension.
23
- *
24
- * @param path
25
- * @returns
26
- */
27
- export declare function getExtension(path: any): any;
28
- /**
29
- * Removes the query, if any, from the given path.
30
- *
31
- * @param path
32
- * @returns
33
- */
34
- export declare function stripQuery(path: any): any;
35
- /**
36
- * Returns the hash (URL fragment), of the given path.
37
- * If there is no hash, then the root hash ("#") is returned.
38
- *
39
- * @param path
40
- * @returns
41
- */
42
- export declare function getHash(path: undefined | string): string;
43
- /**
44
- * Removes the hash (URL fragment), if any, from the given path.
45
- *
46
- * @param path
47
- * @returns
48
- */
49
- export declare function stripHash(path?: string | undefined): string;
50
- /**
51
- * Determines whether the given path is a filesystem path.
52
- * This includes "file://" URLs.
53
- *
54
- * @param path
55
- * @returns
56
- */
57
- export declare function isFileSystemPath(path: string | undefined): boolean;
58
- /**
59
- * Converts a filesystem path to a properly-encoded URL.
60
- *
61
- * This is intended to handle situations where JSON Schema $Ref Parser is called
62
- * with a filesystem path that contains characters which are not allowed in URLs.
63
- *
64
- * @example
65
- * The following filesystem paths would be converted to the following URLs:
66
- *
67
- * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json
68
- * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json
69
- * file://Project #42/file.json ==> file://Project%20%2342/file.json
70
- *
71
- * @param path
72
- * @returns
73
- */
74
- export declare function fromFileSystemPath(path: string): string;
75
- /**
76
- * Converts a URL to a local filesystem path.
77
- */
78
- export declare function toFileSystemPath(path: string | undefined, keepFileProtocol?: boolean): string;
79
- export declare function relative(from: string, to: string): string;
@@ -1,285 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.resolve = resolve;
40
- exports.cwd = cwd;
41
- exports.getProtocol = getProtocol;
42
- exports.getExtension = getExtension;
43
- exports.stripQuery = stripQuery;
44
- exports.getHash = getHash;
45
- exports.stripHash = stripHash;
46
- exports.isFileSystemPath = isFileSystemPath;
47
- exports.fromFileSystemPath = fromFileSystemPath;
48
- exports.toFileSystemPath = toFileSystemPath;
49
- exports.relative = relative;
50
- const convert_path_to_posix_1 = __importDefault(require("./convert-path-to-posix"));
51
- const path_1 = __importStar(require("path"));
52
- const forwardSlashPattern = /\//g;
53
- const protocolPattern = /^(\w{2,}):\/\//i;
54
- const path_2 = require("path");
55
- const is_windows_1 = require("./is-windows");
56
- // RegExp patterns to URL-encode special characters in local filesystem paths
57
- const urlEncodePatterns = [
58
- [/\?/g, "%3F"],
59
- [/#/g, "%23"],
60
- ];
61
- // RegExp patterns to URL-decode special characters for local filesystem paths
62
- const urlDecodePatterns = [/%23/g, "#", /%24/g, "$", /%26/g, "&", /%2C/g, ",", /%40/g, "@"];
63
- /**
64
- * Returns resolved target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.
65
- *
66
- * @returns
67
- */
68
- function resolve(from, to) {
69
- const fromUrl = new URL((0, convert_path_to_posix_1.default)(from), "resolve://");
70
- const resolvedUrl = new URL((0, convert_path_to_posix_1.default)(to), fromUrl);
71
- const endSpaces = to.match(/(\s*)$/)?.[1] || "";
72
- if (resolvedUrl.protocol === "resolve:") {
73
- // `from` is a relative URL.
74
- const { pathname, search, hash } = resolvedUrl;
75
- return pathname + search + hash + endSpaces;
76
- }
77
- return resolvedUrl.toString() + endSpaces;
78
- }
79
- /**
80
- * Returns the current working directory (in Node) or the current page URL (in browsers).
81
- *
82
- * @returns
83
- */
84
- function cwd() {
85
- if (typeof window !== "undefined") {
86
- return location.href;
87
- }
88
- const path = process.cwd();
89
- const lastChar = path.slice(-1);
90
- if (lastChar === "/" || lastChar === "\\") {
91
- return path;
92
- }
93
- else {
94
- return path + "/";
95
- }
96
- }
97
- /**
98
- * Returns the protocol of the given URL, or `undefined` if it has no protocol.
99
- *
100
- * @param path
101
- * @returns
102
- */
103
- function getProtocol(path) {
104
- const match = protocolPattern.exec(path || "");
105
- if (match) {
106
- return match[1].toLowerCase();
107
- }
108
- return undefined;
109
- }
110
- /**
111
- * Returns the lowercased file extension of the given URL,
112
- * or an empty string if it has no extension.
113
- *
114
- * @param path
115
- * @returns
116
- */
117
- function getExtension(path) {
118
- const lastDot = path.lastIndexOf(".");
119
- if (lastDot > -1) {
120
- return stripQuery(path.substr(lastDot).toLowerCase());
121
- }
122
- return "";
123
- }
124
- /**
125
- * Removes the query, if any, from the given path.
126
- *
127
- * @param path
128
- * @returns
129
- */
130
- function stripQuery(path) {
131
- const queryIndex = path.indexOf("?");
132
- if (queryIndex > -1) {
133
- path = path.substr(0, queryIndex);
134
- }
135
- return path;
136
- }
137
- /**
138
- * Returns the hash (URL fragment), of the given path.
139
- * If there is no hash, then the root hash ("#") is returned.
140
- *
141
- * @param path
142
- * @returns
143
- */
144
- function getHash(path) {
145
- if (!path) {
146
- return "#";
147
- }
148
- const hashIndex = path.indexOf("#");
149
- if (hashIndex > -1) {
150
- return path.substring(hashIndex);
151
- }
152
- return "#";
153
- }
154
- /**
155
- * Removes the hash (URL fragment), if any, from the given path.
156
- *
157
- * @param path
158
- * @returns
159
- */
160
- function stripHash(path) {
161
- if (!path) {
162
- return "";
163
- }
164
- const hashIndex = path.indexOf("#");
165
- if (hashIndex > -1) {
166
- path = path.substring(0, hashIndex);
167
- }
168
- return path;
169
- }
170
- /**
171
- * Determines whether the given path is a filesystem path.
172
- * This includes "file://" URLs.
173
- *
174
- * @param path
175
- * @returns
176
- */
177
- function isFileSystemPath(path) {
178
- // @ts-ignore
179
- if (typeof window !== "undefined" || (typeof process !== "undefined" && process.browser)) {
180
- // We're running in a browser, so assume that all paths are URLs.
181
- // This way, even relative paths will be treated as URLs rather than as filesystem paths
182
- return false;
183
- }
184
- const protocol = getProtocol(path);
185
- return protocol === undefined || protocol === "file";
186
- }
187
- /**
188
- * Converts a filesystem path to a properly-encoded URL.
189
- *
190
- * This is intended to handle situations where JSON Schema $Ref Parser is called
191
- * with a filesystem path that contains characters which are not allowed in URLs.
192
- *
193
- * @example
194
- * The following filesystem paths would be converted to the following URLs:
195
- *
196
- * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json
197
- * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json
198
- * file://Project #42/file.json ==> file://Project%20%2342/file.json
199
- *
200
- * @param path
201
- * @returns
202
- */
203
- function fromFileSystemPath(path) {
204
- // Step 1: On Windows, replace backslashes with forward slashes,
205
- // rather than encoding them as "%5C"
206
- if ((0, is_windows_1.isWindows)()) {
207
- const projectDir = cwd();
208
- const upperPath = path.toUpperCase();
209
- const projectDirPosixPath = (0, convert_path_to_posix_1.default)(projectDir);
210
- const posixUpper = projectDirPosixPath.toUpperCase();
211
- const hasProjectDir = upperPath.includes(posixUpper);
212
- const hasProjectUri = upperPath.includes(posixUpper);
213
- const isAbsolutePath = path_1.win32?.isAbsolute(path) ||
214
- path.startsWith("http://") ||
215
- path.startsWith("https://") ||
216
- path.startsWith("file://");
217
- if (!(hasProjectDir || hasProjectUri || isAbsolutePath) && !projectDir.startsWith("http")) {
218
- path = (0, path_2.join)(projectDir, path);
219
- }
220
- path = (0, convert_path_to_posix_1.default)(path);
221
- }
222
- // Step 2: `encodeURI` will take care of MOST characters
223
- path = encodeURI(path);
224
- // Step 3: Manually encode characters that are not encoded by `encodeURI`.
225
- // This includes characters such as "#" and "?", which have special meaning in URLs,
226
- // but are just normal characters in a filesystem path.
227
- for (const pattern of urlEncodePatterns) {
228
- path = path.replace(pattern[0], pattern[1]);
229
- }
230
- return path;
231
- }
232
- /**
233
- * Converts a URL to a local filesystem path.
234
- */
235
- function toFileSystemPath(path, keepFileProtocol) {
236
- // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc.
237
- path = decodeURI(path);
238
- // Step 2: Manually decode characters that are not decoded by `decodeURI`.
239
- // This includes characters such as "#" and "?", which have special meaning in URLs,
240
- // but are just normal characters in a filesystem path.
241
- for (let i = 0; i < urlDecodePatterns.length; i += 2) {
242
- path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]);
243
- }
244
- // Step 3: If it's a "file://" URL, then format it consistently
245
- // or convert it to a local filesystem path
246
- let isFileUrl = path.substr(0, 7).toLowerCase() === "file://";
247
- if (isFileUrl) {
248
- // Strip-off the protocol, and the initial "/", if there is one
249
- path = path[7] === "/" ? path.substr(8) : path.substr(7);
250
- // insert a colon (":") after the drive letter on Windows
251
- if ((0, is_windows_1.isWindows)() && path[1] === "/") {
252
- path = path[0] + ":" + path.substr(1);
253
- }
254
- if (keepFileProtocol) {
255
- // Return the consistently-formatted "file://" URL
256
- path = "file:///" + path;
257
- }
258
- else {
259
- // Convert the "file://" URL to a local filesystem path.
260
- // On Windows, it will start with something like "C:/".
261
- // On Posix, it will start with "/"
262
- isFileUrl = false;
263
- path = (0, is_windows_1.isWindows)() ? path : "/" + path;
264
- }
265
- }
266
- // Step 4: Normalize Windows paths (unless it's a "file://" URL)
267
- if ((0, is_windows_1.isWindows)() && !isFileUrl) {
268
- // Replace forward slashes with backslashes
269
- path = path.replace(forwardSlashPattern, "\\");
270
- // Capitalize the drive letter
271
- if (path.substr(1, 2) === ":\\") {
272
- path = path[0].toUpperCase() + path.substr(1);
273
- }
274
- }
275
- return path;
276
- }
277
- function relative(from, to) {
278
- if (!isFileSystemPath(from) || !isFileSystemPath(to)) {
279
- return resolve(from, to);
280
- }
281
- const fromDir = path_1.default.dirname(stripHash(from));
282
- const toPath = stripHash(to);
283
- const result = path_1.default.relative(fromDir, toPath);
284
- return result + getHash(to);
285
- }
@@ -1,2 +0,0 @@
1
- declare const _default: import("vite").UserConfig;
2
- export default _default;
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const config_1 = require("vitest/config");
4
- const isBrowser = process.env.BROWSER === "true";
5
- exports.default = (0, config_1.defineConfig)({
6
- test: {
7
- coverage: { reporter: ["lcov", "html", "text"] },
8
- dir: "test",
9
- environment: isBrowser ? "jsdom" : "node",
10
- exclude: ["**/__IGNORED__/**"],
11
- globals: true,
12
- globalSetup: isBrowser ? ["./test/fixtures/server.ts"] : undefined,
13
- include: ['./lib/**/*.test.ts'],
14
- passWithNoTests: true,
15
- reporters: ["verbose"],
16
- testTimeout: 5000,
17
- watch: false,
18
- },
19
- });
@@ -1,52 +0,0 @@
1
- import path from "path";
2
-
3
- import { describe, expect, it } from "vitest";
4
-
5
- import { $RefParser } from "..";
6
-
7
- describe("bundle", () => {
8
- it("handles circular reference with description", async () => {
9
- const refParser = new $RefParser();
10
- const pathOrUrlOrSchema = path.resolve("lib", "__tests__", "spec", "circular-ref-with-description.json");
11
- const schema = await refParser.bundle({ pathOrUrlOrSchema });
12
- expect(schema).toEqual({
13
- schemas: {
14
- Bar: {
15
- $ref: '#/schemas/Foo',
16
- description: 'ok',
17
- },
18
- Foo: {
19
- $ref: '#/schemas/Bar',
20
- },
21
- },
22
- });
23
- });
24
-
25
- it("bundles multiple references to the same file correctly", async () => {
26
- const refParser = new $RefParser();
27
- const pathOrUrlOrSchema = path.resolve("lib", "__tests__", "spec", "multiple-refs.json");
28
- const schema = (await refParser.bundle({ pathOrUrlOrSchema })) as any;
29
-
30
- // Both parameters should now be $ref to the same internal definition
31
- const firstParam = schema.paths["/test1/{pathId}"].get.parameters[0];
32
- const secondParam = schema.paths["/test2/{pathId}"].get.parameters[0];
33
-
34
- // The $ref should match the output structure in file_context_0
35
- expect(firstParam.$ref).toBe("#/components/parameters/path-parameter_pathId");
36
- expect(secondParam.$ref).toBe("#/components/parameters/path-parameter_pathId");
37
-
38
- // The referenced parameter should exist and match the expected structure
39
- expect(schema.components).toBeDefined();
40
- expect(schema.components.parameters).toBeDefined();
41
- expect(schema.components.parameters["path-parameter_pathId"]).toEqual({
42
- name: "pathId",
43
- in: "path",
44
- required: true,
45
- schema: {
46
- type: "string",
47
- format: "uuid",
48
- description: "Unique identifier for the path",
49
- },
50
- });
51
- });
52
- });
@@ -1,45 +0,0 @@
1
- import path from "node:path";
2
-
3
- import { describe, expect, it } from "vitest";
4
-
5
- import { getResolvedInput } from "../index";
6
-
7
- describe("getResolvedInput", () => {
8
- it("handles url", async () => {
9
- const pathOrUrlOrSchema = "https://foo.com";
10
- const resolvedInput = await getResolvedInput({ pathOrUrlOrSchema });
11
- expect(resolvedInput.type).toBe("url");
12
- expect(resolvedInput.schema).toBeUndefined();
13
- expect(resolvedInput.path).toBe("https://foo.com/");
14
- });
15
-
16
- it("handles file", async () => {
17
- const pathOrUrlOrSchema = "./path/to/openapi.json";
18
- const resolvedInput = await getResolvedInput({ pathOrUrlOrSchema });
19
- expect(resolvedInput.type).toBe("file");
20
- expect(resolvedInput.schema).toBeUndefined();
21
- expect(path.normalize(resolvedInput.path).toLowerCase()).toBe(
22
- path.normalize(path.resolve("./path/to/openapi.json")).toLowerCase(),
23
- );
24
- });
25
-
26
- it("handles raw spec", async () => {
27
- const pathOrUrlOrSchema = {
28
- info: {
29
- version: "1.0.0",
30
- },
31
- openapi: "3.1.0",
32
- paths: {},
33
- };
34
- const resolvedInput = await getResolvedInput({ pathOrUrlOrSchema });
35
- expect(resolvedInput.type).toBe("json");
36
- expect(resolvedInput.schema).toEqual({
37
- info: {
38
- version: "1.0.0",
39
- },
40
- openapi: "3.1.0",
41
- paths: {},
42
- });
43
- expect(resolvedInput.path).toBe("");
44
- });
45
- });