/**
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 moduleHook = require('../../../hooks/require');
const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');
const { propagate, absolutePath, getResultMeta } = require('./common');

function hookPath(path) {
  for (const os of ['posix', 'win32']) {
    patcher.patch(path[os], 'join', {
      name: `path.${os}.join`,
      patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
      post: (data) => {
        if (!data.args[0]) return;
        const resultMeta = getResultMeta(data, 'join');
        if (!absolutePath(data.args[0])) {
          resultMeta.offset = 0;
          resultMeta.evaluator = (segmentOffset) => segmentOffset === 0;
        }
        propagate({
          data,
          resultMeta,
          win32: os === 'win32'
        });
      }
    });
  }
}

/**
 * Entry point to propagator provider
 * This instruments path.join on
 * both win32 and posix keys
 */
module.exports.handle = function() {
  moduleHook.resolve({ name: 'path' }, hookPath);
};

module.exports.hookPath = hookPath;
