All files logging-espree.js

94.54% Statements 52/55
91.66% Branches 11/12
100% Functions 4/4
94.54% Lines 52/55

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 561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x       6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 349x 349x 349x 11x 11x 349x 6x 6x 6x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 11x  
import * as escodegen from "escodegen";
import * as espree from "espree";
import * as estraverse from "estraverse";
import * as fs from "fs/promises";
 
 
/**
 * Transpile the input file and write the output to the output file.
 * @param {string} inputFile 
 * @param {string} outputFile 
 */
export async function transpile(inputFile, outputFile) {
  let input = await fs.readFile(inputFile, 'utf-8')
  const code = addLogging(input);
  if (outputFile === undefined) {
    console.log(code);
    return;
  }
  await fs.writeFile(outputFile, code)
  console.log('Output written to', outputFile);
}
 
/**
 * Add logging to the input code.
 * @param {string} code
 * @returns {string} The code with logging added.
 */
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);
}
 
/**
 * Add code to the beginning of a function.
 * @param {object} node The function node.
 * @returns {object} The node with code added.
 */
function addBeforeCode(node) {
  const name = node.id ? node.id.name : '<anonymous function>';
  const args = node.params.map( p => "${ "+ p.name +" }" );
  const line = node.loc.start.line;
  const beforeCode = "console.log(`Entering " + 
    name + "(" + args.join(', ') + ") at line " + line +"`);";
  const beforeNodes = espree.parse(beforeCode, {ecmaVersion:6}).body;
  node.body.body = beforeNodes.concat(node.body.body);
}