ronantakizawa/codereview-bench huggingface dataset:
Repository: axios/axios
File: lib/adapters/http.js (JavaScript)

Code before:
    }

    onDone((value, isRejected) => {
      isDone = true;
      if (isRejected) {
        rejected = true;
        onFinished();
      }
    });

    function abort(reason) {
      emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
    }

    emitter.once('abort', reject);

    if (config.cancelToken || config.signal) {
      config.cancelToken && config.cancelToken.subscribe(abort);
      if (config.signal) {
        config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
      }
    }

    // Parse url
    const fullPath = buildFullPath(config.baseURL, config.url);
    const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined, config.allowAbsoluteUrls);
    const protocol = parsed.protocol || supportedProtocols[0];

    if (protocol === 'data:') {
      let convertedData;

      if (method !== 'GET') {
        return settle(resolve, reject, {
          status: 405,
          statusText: 'method not allowed',
          headers: {},
          config
        });
      }

      try {
        convertedData = fromDataURI(config.url, responseType === 'blob', {
          Blob: config.env && config.env.Blob
        });
      } catch (err) {
        throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
      }

      if (responseType === 'text') {
        convertedData = convertedData.toString(responseEncoding);


Review comment (suggestion):
i dont understand what you may be trying to achieve with this param? i am unaware of the URL class taking in a parameter like this.

Code after:
    }

    onDone((value, isRejected) => {
      isDone = true;
      if (isRejected) {
        rejected = true;
        onFinished();
      }
    });

    function abort(reason) {
      emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
    }

    emitter.once('abort', reject);

    if (config.cancelToken || config.signal) {
      config.cancelToken && config.cancelToken.subscribe(abort);
      if (config.signal) {
        config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
      }
    }

    // Parse url
    const fullPath = buildFullPath(config.baseURL, config.url);
    const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : undefined);
    const protocol = parsed.protocol || supportedProtocols[0];

    if (protocol === 'data:') {
      let convertedData;

      if (method !== 'GET') {
        return settle(resolve, reject, {
          status: 405,
          statusText: 'method not allowed',
          headers: {},
          config
        });
      }

      try {
        convertedData = fromDataURI(config.url, responseType === 'blob', {
          Blob: config.env && config.env.Blob
        });
      } catch (err) {
        throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
      }

      if (responseType === 'text') {
        convertedData = convertedData.toString(responseEncoding);
Repository: axios/axios
File: lib/helpers/validator.js (JavaScript)

Code before:
      throw new AxiosError(
        formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
        AxiosError.ERR_DEPRECATED
      );
    }

    if (version && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      // eslint-disable-next-line no-console
      console.warn(
        formatMessage(
          opt,
          ' has been deprecated since v' + version + ' and will be removed in the near future'
        )
      );
    }

    return validator ? validator(value, opt, opts) : true;
  };
};

validators.spelling = function spelling(correctSpelling) {
  return (value, opt) => {
    // eslint-disable-next-line no-console
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`)
    return true
  }
};

/**
 * Assert object's properties type
 *
 * @param {object} options
 * @param {object} schema
 * @param {boolean?} allowUnknown
 *
 * @returns {object}
 */

function assertOptions(options, schema, allowUnknown) {
  if (typeof options !== 'object') {
    throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  }
  const keys = Object.keys(options);
  let i = keys.length;
  while (i-- > 0) {
    const opt = keys[i];
    const validator = schema[opt];
    if (validator) {
      const value = options[opt];
      const result = value === undefined || validator(value, opt, options);

Review comment (suggestion):
```suggestion
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    return true;
```

Code after:
      throw new AxiosError(
        formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
        AxiosError.ERR_DEPRECATED
      );
    }

    if (version && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      // eslint-disable-next-line no-console
      console.warn(
        formatMessage(
          opt,
          ' has been deprecated since v' + version + ' and will be removed in the near future'
        )
      );
    }

    return validator ? validator(value, opt, opts) : true;
  };
};

validators.spelling = function spelling(correctSpelling) {
  return (value, opt) => {
    // eslint-disable-next-line no-console
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    return true;
  }
};

/**
 * Assert object's properties type
 *
 * @param {object} options
 * @param {object} schema
 * @param {boolean?} allowUnknown
 *
 * @returns {object}
 */

function assertOptions(options, schema, allowUnknown) {
  if (typeof options !== 'object') {
    throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  }
  const keys = Object.keys(options);
  let i = keys.length;
  while (i-- > 0) {
    const opt = keys[i];
    const validator = schema[opt];
    if (validator) {
      const value = options[opt];
      const result = value === undefined || validator(value, opt, options);
Repository: axios/axios
File: test/unit/regression/SNYK-JS-AXIOS-7361793.js (JavaScript)

Code before:
        }).listen(GOOD_PORT);
        badServer = http.createServer(function (req, res) {
            res.write('bad');
            res.end();
        }).listen(BAD_PORT);
    })

    afterEach(() => {
        goodServer.close();
        badServer.close();
    });

    it('should not fetch bad server', async () => {
        const ssrfAxios = axios.create({
            baseURL: 'http://localhost:' + String(GOOD_PORT),
        });

        // Good payload would be `userId = '12345'`
        // Malicious payload is as below.
        const userId = '/localhost:' + String(BAD_PORT);

        const response = await ssrfAxios.get(`/${userId}`);
        assert.strictEqual(response.data, 'good');
        assert.strictEqual(response.config.baseURL, 'http://localhost:' + String(GOOD_PORT));
        assert.strictEqual(response.config.url, '//localhost:' + String(BAD_PORT));
        assert.strictEqual(response.request.res.responseUrl, 'http://localhost:4666/localhost:4667');
    });
});


Review comment (suggestion):
```suggestion
        assert.strictEqual(response.request.res.responseUrl, 'http://localhost:' + String(GOOD_PORT) + '/localhost:' + String(BAD_PORT));
```

Code after:
        }).listen(GOOD_PORT);
        badServer = http.createServer(function (req, res) {
            res.write('bad');
            res.end();
        }).listen(BAD_PORT);
    })

    afterEach(() => {
        goodServer.close();
        badServer.close();
    });

    it('should not fetch bad server', async () => {
        const ssrfAxios = axios.create({
            baseURL: 'http://localhost:' + String(GOOD_PORT),
        });

        // Good payload would be `userId = '12345'`
        // Malicious payload is as below.
        const userId = '/localhost:' + String(BAD_PORT);

        const response = await ssrfAxios.get(`/${userId}`);
        assert.strictEqual(response.data, 'good');
        assert.strictEqual(response.config.baseURL, 'http://localhost:' + String(GOOD_PORT));
        assert.strictEqual(response.config.url, '//localhost:' + String(BAD_PORT));
        assert.strictEqual(response.request.res.responseUrl, 'http://localhost:' + String(GOOD_PORT) + '/localhost:' + String(BAD_PORT));
    });
});
Repository: axios/axios
File: lib/core/buildFullPath.js (JavaScript)

Code before:
'use strict';

var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');

/**
 * Creates a new URL by combining the baseURL with the requestedURL,
 * only when the requestedURL is not already an absolute URL.
 * If the requestURL is absolute, this function returns the requestedURL untouched.
 *
 * @param {string} baseURL The base URL
 * @param {string} requestedURL Absolute or relative URL to combine
 * @param {boolean} [allowAbsoluteUrls=false] Set to true to allow absolute URLs
 *
 * @returns {string} The combined full path
 */
module.exports = function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  var isRelativeURL = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeURL || allowAbsoluteUrls == false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
};


Review comment (suggestion):
this implies that the default is `false`, but it's actually `true` (since we're checking for explicit `false` in the function)

Code after:
'use strict';

var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');

/**
 * Creates a new URL by combining the baseURL with the requestedURL,
 * only when the requestedURL is not already an absolute URL.
 * If the requestURL is absolute, this function returns the requestedURL untouched.
 *
 * @param {string} baseURL The base URL
 * @param {string} requestedURL Absolute or relative URL to combine
 * @param {boolean} allowAbsoluteUrls Set to true to allow absolute URLs
 *
 * @returns {string} The combined full path
 */
module.exports = function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  var isRelativeURL = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeURL || allowAbsoluteUrls === false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
};
Repository: axios/axios
File: lib/core/buildFullPath.js (JavaScript)

Code before:
'use strict';

var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');

/**
 * Creates a new URL by combining the baseURL with the requestedURL,
 * only when the requestedURL is not already an absolute URL.
 * If the requestURL is absolute, this function returns the requestedURL untouched.
 *
 * @param {string} baseURL The base URL
 * @param {string} requestedURL Absolute or relative URL to combine
 * @param {boolean} allowAbsoluteUrls Set to true to allow absolute URLs
 *
 * @returns {string} The combined full path
 */
module.exports = function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  var isRelativeURL = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeURL || allowAbsoluteUrls == false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
};


Review comment (suggestion):
```suggestion
  if (baseURL && (isRelativeURL || allowAbsoluteUrls === false)) {
```

Code after:
'use strict';

var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');

/**
 * Creates a new URL by combining the baseURL with the requestedURL,
 * only when the requestedURL is not already an absolute URL.
 * If the requestURL is absolute, this function returns the requestedURL untouched.
 *
 * @param {string} baseURL The base URL
 * @param {string} requestedURL Absolute or relative URL to combine
 * @param {boolean} allowAbsoluteUrls Set to true to allow absolute URLs
 *
 * @returns {string} The combined full path
 */
module.exports = function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  var isRelativeURL = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeURL || allowAbsoluteUrls === false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
};
Repository: axios/axios
File: lib/utils.js (JavaScript)

Code before:
}


/**
 * Estimate decoded byte length of a data:// URL *without* allocating large buffers.
 * - For base64: compute exact decoded size using length and padding;
 *               handle %XX at the character-count level (no string allocation).
 * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound.
 *
 * @param {string} url
 * @returns {number}
 */
function estimateDataURLDecodedBytes(url) {
  if (!url || typeof url !== 'string') return 0;
  if (!url.startsWith('data:')) return 0;

  const comma = url.indexOf(',');
  if (comma < 0) return 0;

  const meta = url.slice(5, comma);
  const body = url.slice(comma + 1);
  const isBase64 = /;base64/i.test(meta);

  if (isBase64) {
    let effectiveLen = body.length;
    for (let i = 0; i < body.length; i++) {
      if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < body.length) {
        const a = body.charCodeAt(i + 1);
        const b = body.charCodeAt(i + 2);
        const isHex = (
          (a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)
        ) && (
          (b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102)
        );
        if (isHex) {
          effectiveLen -= 2;
          i += 2;
        }
      }
    }

    let pad = 0;
    let idx = body.length - 1;

    const tailIsPct3D = (j) =>
      j >= 2 &&
      body.charCodeAt(j - 2) === 37 && // '%'
      body.charCodeAt(j - 1) === 51 && // '3'
      (body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'



Review comment (suggestion):
I would prefer not to rely on V8 optimizations and move body.length to a local variable, since there can be a lot of iterations. There is no guarantee that it will work, nor that the code will not run on other engines in the future.

Code after:
}



/**
 * If the thing is a FormData object, return true, otherwise return false.
 *
 * @param {unknown} thing - The thing to check.
 *
 * @returns {boolean}
 */
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
}

const toJSONObject = (obj) => {
  const stack = new Array(10);

  const visit = (source, i) => {

    if (isObject(source)) {
      if (stack.indexOf(source) >= 0) {
        return;
      }

      //Buffer check
      if (isBuffer(source)) {
        return source;
      }

      if(!('toJSON' in source)) {
        stack[i] = source;
        const target = isArray(source) ? [] : {};

        forEach(source, (value, key) => {
          const reducedValue = visit(value, i + 1);
          !isUndefined(reducedValue) && (target[key] = reducedValue);
        });

        stack[i] = undefined;

        return target;
      }
    }

    return source;
  }

  return visit(obj, 0);
}
Repository: axios/axios
File: lib/utils.js (JavaScript)

Code before:

const noop = () => {}

const toFiniteNumber = (value, defaultValue) => {
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
}


/**
 * Estimate decoded byte length of a data:// URL *without* allocating large buffers.
 * - For base64: compute exact decoded size using length and padding;
 *               handle %XX at the character-count level (no string allocation).
 * - For non-base64: use UTF-8 byteLength of the encoded body as a safe upper bound.
 *
 * @param {string} url
 * @returns {number}
 */
function estimateDataURLDecodedBytes(url) {
  if (!url || typeof url !== 'string') return 0;
  if (!url.startsWith('data:')) return 0;

  const comma = url.indexOf(',');
  if (comma < 0) return 0;

  const meta = url.slice(5, comma);
  const body = url.slice(comma + 1);
  const isBase64 = /;base64/i.test(meta);

  if (isBase64) {
    let effectiveLen = body.length;
    for (let i = 0; i < body.length; i++) {
      if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < body.length) {
        const a = body.charCodeAt(i + 1);
        const b = body.charCodeAt(i + 2);
        const isHex = (
          (a >= 48 && a <= 57) || (a >= 65 && a <= 70) || (a >= 97 && a <= 102)
        ) && (
          (b >= 48 && b <= 57) || (b >= 65 && b <= 70) || (b >= 97 && b <= 102)
        );
        if (isHex) {
          effectiveLen -= 2;
          i += 2;
        }
      }
    }

    let pad = 0;
    let idx = body.length - 1;

    const tailIsPct3D = (j) =>
      j >= 2 &&

Review comment (performance):
I see you've put in a lot of effort on performance. Theoretically, we can avoid allocating a new line in memory, which is almost the same size as the original one, but work with the old one with the initial offset. But this is not necessary, just a remark.

Code after:

const noop = () => {}

const toFiniteNumber = (value, defaultValue) => {
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
}



/**
 * If the thing is a FormData object, return true, otherwise return false.
 *
 * @param {unknown} thing - The thing to check.
 *
 * @returns {boolean}
 */
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
}

const toJSONObject = (obj) => {
  const stack = new Array(10);

  const visit = (source, i) => {

    if (isObject(source)) {
      if (stack.indexOf(source) >= 0) {
        return;
      }

      //Buffer check
      if (isBuffer(source)) {
        return source;
      }

      if(!('toJSON' in source)) {
        stack[i] = source;
        const target = isArray(source) ? [] : {};

        forEach(source, (value, key) => {
          const reducedValue = visit(value, i + 1);
          !isUndefined(reducedValue) && (target[key] = reducedValue);
        });

        stack[i] = undefined;

        return target;
      }
    }

    return source;
Repository: babel/babel
File: packages/babel-helper-create-class-features-plugin/src/typescript.js (JavaScript)

Code before:
// @flow

import type { NodePath } from "@babel/traverse";

export function assertFieldTransformed(path: NodePath) {
  // TODO (Babel 8): Also check path.node.definite

  if (path.node.declare) {
    throw path.buildCodeFrameError(
      `TypeScript 'declare' fields must first be transformed by ` +
        `@babel/plugin-transform-typescript.\n` +
        `If you have already enabled  that plugin (or '@babel/preset-typescript'), make sure ` +
        `that it runs  before any plugin related to additional class features:\n` +
        ` - @babel/plugin-proposal-class-properties\n` +
        ` - @babel/plugin-proposal-private-methods\n` +
        ` - @babel/plugin-proposal-decorators`,
    );
  }
}


Review comment (suggestion):
nit: `s/  / /g`
(Even though I could comment on multiple lines, I couldn't submit a multiple line suggestion, else I would have created one.)

Code after:
// @flow

import type { NodePath } from "@babel/traverse";

export function assertFieldTransformed(path: NodePath) {
  // TODO (Babel 8): Also check path.node.definite

  if (path.node.declare) {
    throw path.buildCodeFrameError(
      `TypeScript 'declare' fields must first be transformed by ` +
        `@babel/plugin-transform-typescript.\n` +
        `If you have already enabled that plugin (or '@babel/preset-typescript'), make sure ` +
        `that it runs before any plugin related to additional class features:\n` +
        ` - @babel/plugin-proposal-class-properties\n` +
        ` - @babel/plugin-proposal-private-methods\n` +
        ` - @babel/plugin-proposal-decorators`,
    );
  }
}
Repository: babel/babel
File: packages/babel-cli/src/babel/dir.js (JavaScript)

Code before:
        console.error(err);
        return false;
      }

      throw err;
    }
  }

  function getDest(filename: string, base: string): string {
    if (cliOptions.relative) {
      return path.join(base, cliOptions.outDir, filename);
    }
    return path.join(cliOptions.outDir, filename);
  }

  async function handleFile(src: string, base: string): Promise<boolean> {
    const written = await write(src, base);
    const relative = path.relative(base, src);
    const isCompilableExtension = util.isCompilableExtension(
      relative,
      cliOptions.extensions,
    );
    if (
      !written &&
      ((!isCompilableExtension && cliOptions.copyFiles) ||
        cliOptions.includeIgnored)
    ) {
      const filename = path.relative(base, src);
      const dest = getDest(filename, base);
      outputFileSync(dest, fs.readFileSync(src));
      util.chmod(src, dest);
    }
    return written;
  }

  async function handle(filenameOrDir: string): Promise<number> {
    if (!fs.existsSync(filenameOrDir)) return 0;

    const stat = fs.statSync(filenameOrDir);

    if (stat.isDirectory()) {
      const dirname = filenameOrDir;

      let count = 0;

      const files = util.readdir(dirname, cliOptions.includeDotfiles);
      for (const filename of files) {
        const src = path.join(dirname, filename);

        const written = await handleFile(src, dirname);
        if (written) count += 1;

Review comment (suggestion):
I think we should throw in `parseArgv` when `copyFiles: false, includeIgnored: true`, otherwise we will have another flag that _could_ copy non compilable files.




Code after:
      outputFileSync(dest, res.code);
      util.chmod(src, dest);

      if (cliOptions.verbose) {
        console.log(src + " -> " + dest);
      }

      return FILE_TYPE.COMPILED;
    } catch (err) {
      if (cliOptions.watch) {
        console.error(err);
        return FILE_TYPE.ERR_COMPILATION;
      }

      throw err;
    }
  }

  function getDest(filename: string, base: string): string {
    if (cliOptions.relative) {
      return path.join(base, cliOptions.outDir, filename);
    }
    return path.join(cliOptions.outDir, filename);
  }

  async function handleFile(src: string, base: string): Promise<boolean> {
    const written = await write(src, base);

    if (
      (cliOptions.copyFiles && written === FILE_TYPE.NON_COMPILABLE) ||
      (cliOptions.copyIgnored && written === FILE_TYPE.IGNORED)
    ) {
      const filename = path.relative(base, src);
      const dest = getDest(filename, base);
      outputFileSync(dest, fs.readFileSync(src));
      util.chmod(src, dest);
    }
    return written === FILE_TYPE.COMPILED;
  }

  async function handle(filenameOrDir: string): Promise<number> {
    if (!fs.existsSync(filenameOrDir)) return 0;

    const stat = fs.statSync(filenameOrDir);

    if (stat.isDirectory()) {
      const dirname = filenameOrDir;

      let count = 0;

      const files = util.readdir(dirname, cliOptions.includeDotfiles);