/**
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.
*/
/**
 * CONTRAST-20233
 */
'use strict';

const logger = require('../core/logger')('contrast:hooks:stealthyRequire');
const requireHook = require('./require');
const isAgentPath = require('../util/is-agent-path');

module.exports = function() {
  module.exports.init();
};

/**
 * returns a wrapped function that adds a deleteProperty trap
 * on the first argument passed to stealthy-require
 * If the object key in require cache is an agent path fake it out and return true vs
 * removing from require cache
 */
module.exports.hook = function hook(stealthyRequire) {
  return function(
    ...args /*requireCache, callback, callbackForModulesToKeep, mod*/
  ) {
    if (typeof args[0] !== 'object') {
      return stealthyRequire.apply(this, args);
    }

    args[0] = new Proxy(args[0], {
      deleteProperty(target, prop) {
        if (isAgentPath(prop)) {
          logger.trace(`stealthy-require proxy stopped deletion of ${prop}`);
          return true;
        }

        return delete target[prop];
      }
    });
    return stealthyRequire.apply(this, args);
  };
};

module.exports.init = function init() {
  requireHook.resolve({ name: 'stealthy-require' }, function(stealthyRequire) {
    logger.trace(
      'patching stealthy-require to prevent getting kicked out of module cache'
    );

    return module.exports.hook(stealthyRequire);
  });
};
