/**
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 Module = require('module');

const ModuleHook = require('./require');
const patcher = require('./patcher');
const { PATCH_TYPES } = require('../constants');
const isAgentPath = require('../util/is-agent-path');

// See https://github.com/newrelic/node-newrelic/blob/master/lib/uninstrumented.js#L80
module.exports = function() {
  ModuleHook.resolve(
    { name: 'newrelic', file: 'lib/util/properties.js' },
    (properties) => {
      patcher.patch(properties, 'hasOwn', {
        name: 'newrelic.properties',
        patchType: PATCH_TYPES.MISC,
        alwaysRun: true,
        post: (wrapCtx) => {
          const [object, key] = wrapCtx.args;

          if (isRequireCache(object)) {
            // Lie about our code that has filenames matching module names
            // that they instrument.
            if (isAgentPath(key)) {
              wrapCtx.result = false;
            }
          }
        }
      });
    }
  );

  /**
   * Makes judgement as to whether the object is the module cache.
   * @param   {Object} object The object to check
   * @returns {Boolean}
   */
  function isRequireCache(object) {
    return (
      typeof object === 'object' &&
      !object.__proto__ &&
      Object.keys(object).some((key) => object[key] instanceof Module)
    );
  }
};
