All files logging-espree.js

76.78% Statements 43/56
90.9% Branches 10/11
100% Functions 4/4
76.78% Lines 43/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x 1x 1x 1x 1x 1x 1x 5x 5x 5x         5x 1x 1x 1x 1x 1x 1x 5x 5x 5x 13x 13x 5x 5x 13x 5x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 5x                   5x 5x 5x 5x 5x 5x  
import * as escodegen from "escodegen";
import * as espree from "espree";
import * as estraverse from "estraverse";
import * as fs from "fs/promises";
 
 
export async function transpile(inputFile, outputFile) {
  let input = await fs.readFile(inputFile, 'utf-8')
  let output = addLogging(input);
  if (outputFile === undefined) {
      console.log(output);
      return;
  }
  await fs.writeFile(outputFile, output);
}
 
/**
 * @desc Adds logging to the input code.
 * @param {string} code The code to add logging to.
 */
export function addLogging(code) {  
  const ast = espree.parse(code, { ecmaVersion: 6 }, { loc: true });
  estraverse.traverse(ast, {
    enter: function (node, parent) {
      if (node.type === 'FunctionDeclaration' ||
        node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
          addBeforeCode(node);
      }
    }
  });
  return escodegen.generate(ast);
}
 
/**
 * @desc Adds a console.log statement before the function
 * @param {Object} node the function node
 */
function addBeforeCode(node) {
  let name = node.id ? node.id.name : '<anonymous function>';
  let lineNum = node.loc.start.line;
  let params = node.params.map(function (argumentos) {
    if (argumentos.type === 'Identifier') {
      return argumentos.name;
    }
    else if (argumentos.type === 'AssignmentPattern') {
      return argumentos.left.name + "=" + argumentos.right.name;
    }
    else if (argumentos.type === 'RestElement') {
      return "..." + argumentos.argument.name;
    }
  });
  params = params.join(', ');
  let beforeCode = `console.log(\`Entering ${name}(${params}) at line ${lineNum}\`);`;
  let beforeNodes = espree.parse(beforeCode, { ecmaVersion: 6 }).body;
  node.body.body = beforeNodes.concat(node.body.body);
}