/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const { KEYS, AsyncStorage } = require('../../core/async-storage');
const agentEmitter = require('../../agent-emitter');
const isContrastError = require('../../util/is-contrast-error');
const process = require('process');

const handledErrors = new WeakSet();

module.exports.install = function() {
  const originalOn = process.on;
  process.on = function (name, ...args) {
    if (name === 'unhandledRejection') {
      return originalOn.call(
        this,
        name,
        ...args.map(
          (origHandler) =>
            function (reason, promise) {
              if (handledErrors.has(reason)) {
                return; // skip
              }
              return origHandler(reason, promise);
            },
        ),
      );
    } else {
      return originalOn.call(this, name, ...args);
    }
  };

  process.on('unhandledRejection', function asyncErrorHandling(error) {
    handlerAsyncErrors(error);
  });

  function handlerAsyncErrors(error) {
    let handled = null;
    if (isContrastError(error)) {
      const res = AsyncStorage.fromException(error, KEYS.RES);
      handled = agentEmitter.handleError(error, res);
    }
    if (handled) {
      handledErrors.add(error);
    } else {
      console.warn(
        'An Unhandled Rejection has been found in the instrumented code:\n%s', error
      );
    }
  }
};


