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 89034a1
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ 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}`;

try {
({ initialFormat, parsedJSON } = toJS(asyncapiYAMLorJSON));
Expand Down Expand Up @@ -133,10 +133,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 89034a1

Please sign in to comment.