/**
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 rewriterFactory = require('../../core/rewrite');
const logger = require('../../core/logger')('contrast:rules:propagation:ejs');

module.exports.setup = function(agent) {
  rewriter = rewriterFactory(agent);
};

function handle(data) {
  try {
    let { source } = data.obj;

    // prepend our own version of __append to the source that way it will get rewritten
    // __append gets prepended after generateSource so the result will be
    // function __append() { // unrewritten }
    // function __append() { // rewritten }
    // and the rewritten one will be what's called
    source = `
      var __output = "";
      function __append(s) { if (s !== undefined && s !== null) __output += s }
      ${source}
      return __output;
      `;

    const tempWrapperString = `
      function tempWrapper() {
        ${source}
      }
    `;
    const rewritten = rewriter.rewriteCode(tempWrapperString, '', {
      inject: false,
      wrap: false
    });

    const { code } = rewritten;

    if (code) {
      data.obj.source = code
        .split('\n')
        .slice(1, -1)
        .join('\n');
    }
  } catch (e) {
    logger.warn(`Failed to rewrite ejs template. ${e}`);
  }
}

module.exports.handle = handle;
