/**
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.
*/
/**
 * String 'propagation'
 * Note: No propagation event is created because:
 * 	- when the argument to String is a string, it is effectively an identity function
 * 	  and there is no benefit to logging an event
 * 	- when the argument to String is anything else, no information is retained
 * 	  (eg: String(SomeTrackedObject) == '[object Object]'
 *
 * @module lib/assess/propagators/String
 */
'use strict';

const tracker = require('../../tracker.js');
const patcher = require('../../hooks/patcher.js');
const { PATCH_TYPES } = require('../../constants');
const ContrastString = require('../../core/rewrite/injections').get('String');

function handle() {
  ContrastString.enable();

  patcher.patch(ContrastString.value, {
    name: 'String',
    patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
    post(data) {
      const arg = data.args[0];
      let argData = tracker.getData(arg);

      // Checks if the string literal form of the new String object is tracked.
      // If so, we will want to copy the existing tag ranges below.
      if (data.obj && !argData) {
        argData = tracker.getData(data.result.toString());
      }

      if (!arg || !argData) {
        return;
      }

      const tracked = tracker.track(data.result);
      if (tracked) {
        // In a constructor context, data.obj is set to the new String object.
        // When a new String object is instantiated we must copy the existing tag
        // ranges from the string literal to the new String object.
        if (data.obj) {
          tracked.props.event = argData.event;
          tracked.props.tagRanges = tracked.props.tagRanges.concat(argData.tagRanges);
        }

        data.result = tracked.str;
      }
    }
  });
}

module.exports = { handle };
