/**
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 logger = require('../core/logger')('contrast:hooks:object-to-primitive');
const tracker = require('../tracker');

/**
 * Abstracted method that is used to patch String.prototype
 * and Object.prototype functions for dataflow reasons
 *
 * If the string value from toString or valueOf is tracked,
 * return the tracked version with proper tags/events applied
 *
 * @param {Function} origFn The original function to reflect
 * @param {String} str the this scope that method is being called on
 * @return {String} tracked/untracked string
 *
 */
function wrapNativeMethod(origFn, str) {
  let s = Reflect.apply(origFn, str, []);
  const origProps = tracker.getData(str);
  if (origProps) {
    const tracked = tracker.track(s);
    if (tracked) {
      s = tracked.str;
      tracked.props.tagRanges = origProps.tagRanges;
      tracked.props.event = origProps.event;
    }
  }
  return s;
}

module.exports = function init() {
  logger.debug('patching toString and valueOf methods');
  const stringPrototypeToString = String.prototype.toString;
  String.prototype.toString = function() {
    const str = this;
    return wrapNativeMethod(stringPrototypeToString, str);
  };

  const stringPrototypeValueOf = String.prototype.valueOf;
  String.prototype.valueOf = function() {
    const str = this;
    return wrapNativeMethod(stringPrototypeValueOf, str);
  };

  const objectPrototypeValueOf = Object.prototype.valueOf;
  Object.prototype.valueOf = function() {
    const obj = this;
    return wrapNativeMethod(objectPrototypeValueOf, obj);
  };
};
