Skip to content

Commit

Permalink
feat: parseFromUrl does not resolve relative references (asyncapi#504)
Browse files Browse the repository at this point in the history
  • Loading branch information
aeworxet committed Jul 19, 2022
1 parent c962a7e commit 6963e8d
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,13 @@ module.exports = {
* @param {ParserOptions=} options Configuration options object {@link #asyncapiparserparseroptions--object|ParserOptions}
* @returns {Promise<AsyncAPIDocument>} The parsed AsyncAPI document.
*/
async function parse(asyncapiYAMLorJSON, options = {}) {
async function parse(asyncapiYAMLorJSON, options = {}, urlRegExped) {
let parsedJSON;
let initialFormat;

options.path = options.path || `${process.cwd()}${path.sep}`;

options.path = options.path || urlRegExped || `${process.cwd()}${path.sep}`;
options.resolve = { external: true, file: true, http: true };

try {
({ initialFormat, parsedJSON } = toJS(asyncapiYAMLorJSON));

Expand Down Expand Up @@ -133,10 +134,22 @@ function parseFromUrl(url, fetchOptions, options) {
//To not break the API by changing argument position and to silet the linter it is just better to move adding
if (!fetchOptions) fetchOptions = {};

// RegExp, which chooses name of the file with spec in the URL string, is created.
const urlRegExp = /[^/]+$/g;
// When executed in multiple async calls, 'checkErrorWrapper' passes URL
// string as an object by reference. In this case 'String.replace()' method
// mutates original URL string causing test with multiple async calls to fail.
// Thus completely independent object containing URL string is created for
// future manipulation.
const urlCopy = new String(url);
// In the copy of the URL string, name of the file with spec is removed,
// leaving only absolute URL, which is later passed through thenable chain.
const urlRegExped = urlCopy.replace(urlRegExp.exec(urlCopy), '');

return new Promise((resolve, reject) => {
fetch(url, fetchOptions)
.then(res => res.text())
.then(doc => parse(doc, options))
.then(doc => parse(doc, options, urlRegExped))
.then(result => resolve(result))
.catch(e => {
if (e instanceof ParserError) return reject(e);
Expand Down

0 comments on commit 6963e8d

Please sign in to comment.