/**
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 patcher = require('../../../hooks/patcher');
const tracker = require('../../../tracker');
const { PATCH_TYPES } = require('../../../constants');
const moduleHook = require('../../../hooks/require');
const { createSubsetTagRanges } = require('../../propagators/manager');
const { Signature, CallContext, PropagationEvent } = require('../../models');

/**
 * Entry point to propagator provider
 * This instruments path.dirname on
 * both win32 and posix keys
 */
module.exports.handle = function handle() {
  const signature = new Signature('path.dirname');
  const params = [
    { index: 0, type: 'start' },
    { index: 1, inclusive: true, type: 'stop' }
  ];

  moduleHook.resolve({ name: 'path' }, (path) => {
    for (const os of ['posix', 'win32']) {
      patcher.patch(path[os], 'dirname', {
        name: `path.${os}.dirname`,
        patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
        post(data) {
          if (!data.args[0]) return;

          const trackingData = tracker.getData(data.args[0]);
          if (!trackingData) return;

          // path.dirname() does a slice at 0 to the calculated end separator
          const tagRanges = createSubsetTagRanges({
            sourceTagRanges: trackingData.tagRanges,
            data: {
              args: [0, data.result.length]
            },
            params,
            sources: [data.args[0]],
            target: data.result
          });

          if (!tagRanges.length) return;

          const tracked = tracker.track(data.result);
          const parentEvent = trackingData.event;
          if (tracked) {
            tracked.props.tagRanges = tagRanges;
            tracked.props.event = new PropagationEvent({
              context: CallContext.create(data),
              parents: [parentEvent],
              signature,
              source: 'P',
              tagRanges,
              target: 'R'
            });
            data.result = tracked.str;
          }
        }
      });
    }
  });
};
