/**
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';

let rewriter;
const logger = require('../../core/logger')(
  'contrast:rules:propagation:pug.compile'
);

/**
 * Setup rewriter state
 * @param   {Object}   agent agent instance
 */
module.exports.setup = function(agent) {
  rewriter = require('../../core/rewrite')(agent);
};

module.exports.handle = { pre };

/**
 * Pre hook for pug compiler to rewrite the pug compiler's
 * generated JavaScript code so that we get free propagation
 * through their html generation.
 * This could cause a slow response to the first request, but every
 * subsequent response should be fine.
 */
function pre(data) {
  const opts = data.args[1] || {};
  const plugins = opts.plugins || [];

  plugins.push({
    postCodeGen: (value, options) => {
      try {
        return rewriter.rewriteCode(value, '', false, false).code;
      } catch (e) {
        logger.warn(`Failed to rewrite pug code. ${e}`);
        return value;
      }
    }
  });

  opts.plugins = plugins;
  data.args[1] = opts;
}

module.exports.handle = { pre };
