CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-istanbul-lib-instrument

Core istanbul API for JS code coverage instrumentation and analysis

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

instrumentation.mddocs/

Code Instrumentation

Core instrumentation functionality for transforming JavaScript code with coverage tracking capabilities. The instrumenter adds counters for statements, branches, and functions while preserving original code semantics.

Capabilities

Create Instrumenter

Creates a new instrumenter instance with configurable options for different instrumentation scenarios.

/**
 * Creates a new instrumenter with the supplied options
 * @param opts - Instrumenter configuration options
 * @returns New Instrumenter instance
 */
function createInstrumenter(opts?: InstrumenterOptions): Instrumenter;

interface InstrumenterOptions {
  /** Name of global coverage variable (default: "__coverage__") */
  coverageVariable?: string;
  /** Report boolean value of logical expressions (default: false) */
  reportLogic?: boolean;
  /** Preserve comments in output (default: false) */
  preserveComments?: boolean;
  /** Generate compact code (default: true) */
  compact?: boolean;
  /** Set to true to instrument ES6 modules (default: false) */
  esModules?: boolean;
  /** Set to true to allow return statements outside of functions (default: false) */
  autoWrap?: boolean;
  /** Set to true to produce a source map for the instrumented code (default: false) */
  produceSourceMap?: boolean;
  /** Set to array of class method names to ignore for coverage (default: []) */
  ignoreClassMethods?: string[];
  /** Callback function called when a source map URL is found (default: null) */
  sourceMapUrlCallback?: (filename: string, url: string) => void;
  /** Turn debugging on (default: false) */
  debug?: boolean;
  /** Set babel parser plugins (default: from @istanbuljs/schema) */
  parserPlugins?: string[];
  /** The global coverage variable scope (default: "this") */
  coverageGlobalScope?: string;
  /** Use an evaluated function to find coverageGlobalScope (default: true) */
  coverageGlobalScopeFunc?: boolean;
  /** Set babel generator options */
  generatorOpts?: object;
}

Usage Examples:

const { createInstrumenter } = require("istanbul-lib-instrument");

// Basic instrumenter
const instrumenter = createInstrumenter();

// Instrumenter with custom options
const customInstrumenter = createInstrumenter({
  coverageVariable: "__cov__",
  esModules: true,
  preserveComments: true,
  produceSourceMap: true
});

// Instrumenter for browser environments
const browserInstrumenter = createInstrumenter({
  coverageGlobalScope: "window",
  compact: true,
  reportLogic: true
});

Instrumenter Class

Main instrumenter class providing synchronous and asynchronous instrumentation methods.

class Instrumenter {
  constructor(opts?: InstrumenterOptions);
}

Synchronous Instrumentation

Transform code synchronously and track coverage against the supplied filename. Throws if invalid code is passed.

/**
 * Instrument the supplied code and track coverage against the supplied filename
 * @param code - The code to instrument
 * @param filename - The filename against which to track coverage
 * @param inputSourceMap - Source map that maps uninstrumented code back to original form
 * @returns The instrumented code
 * @throws Error if invalid code is passed
 */
instrumentSync(code: string, filename: string, inputSourceMap?: object): string;

Usage Examples:

const { createInstrumenter } = require("istanbul-lib-instrument");

const instrumenter = createInstrumenter();

// Basic instrumentation
const code = `
function calculateTax(price, rate) {
  if (price > 0 && rate > 0) {
    return price * rate;
  }
  return 0;
}
`;

const instrumentedCode = instrumenter.instrumentSync(code, 'tax-calculator.js');

// Instrumentation with source map
const sourceMap = { /* source map object */ };
const instrumentedWithMap = instrumenter.instrumentSync(
  code, 
  'tax-calculator.js', 
  sourceMap
);

Asynchronous Instrumentation

Callback-style instrument method that calls back with an error instead of throwing. Note that the callback is called synchronously.

/**
 * Callback-style instrument method that calls back with an error
 * @param code - The code to instrument
 * @param filename - The filename against which to track coverage
 * @param callback - The callback function
 * @param inputSourceMap - Source map that maps uninstrumented code back to original form
 */
instrument(
  code: string, 
  filename: string, 
  callback: (err: Error | null, result?: string) => void,
  inputSourceMap?: object
): void;

// Alternative signature with filename optional
instrument(
  code: string,
  callback: (err: Error | null, result?: string) => void,
  inputSourceMap?: object
): void;

Usage Examples:

const { createInstrumenter } = require("istanbul-lib-instrument");

const instrumenter = createInstrumenter();

// Callback-style instrumentation
instrumenter.instrument(code, 'calculator.js', (err, instrumentedCode) => {
  if (err) {
    console.error('Instrumentation failed:', err);
    return;
  }
  console.log('Instrumented code:', instrumentedCode);
});

// With filename as optional parameter
instrumenter.instrument(code, (err, instrumentedCode) => {
  if (err) {
    console.error('Instrumentation failed:', err);
    return;
  }
  // filename will be auto-generated
  console.log('Instrumented code:', instrumentedCode);
});

Coverage Data Access

Retrieve coverage information for the last instrumented file.

/**
 * Returns the file coverage object for the last file instrumented
 * @returns The file coverage object with statement, branch, and function tracking
 */
lastFileCoverage(): object;

/**
 * Returns the source map produced for the last file instrumented
 * @returns The source map object or null if no source map was produced
 */
lastSourceMap(): object | null;

Usage Examples:

const { createInstrumenter } = require("istanbul-lib-instrument");

const instrumenter = createInstrumenter({ produceSourceMap: true });

// Instrument code
const instrumentedCode = instrumenter.instrumentSync(code, 'example.js');

// Get coverage data structure
const coverage = instrumenter.lastFileCoverage();
console.log('Statement map:', coverage.statementMap);
console.log('Function map:', coverage.fnMap);
console.log('Branch map:', coverage.branchMap);

// Get source map if produced
const sourceMap = instrumenter.lastSourceMap();
if (sourceMap) {
  console.log('Source map version:', sourceMap.version);
  console.log('Source map mappings:', sourceMap.mappings);
}

Configuration Options Details

Coverage Variable Options

  • coverageVariable: Name of the global variable where coverage data is stored
  • coverageGlobalScope: The scope where the coverage variable is attached ("this", "window", "global")
  • coverageGlobalScopeFunc: Whether to use an evaluated function to determine the scope

Code Generation Options

  • compact: Generate compact code without unnecessary whitespace
  • preserveComments: Keep comments in the instrumented output
  • generatorOpts: Pass-through options to Babel's code generator

Module System Options

  • esModules: Enable ES6 module instrumentation (required for import/export)
  • autoWrap: Allow return statements outside functions (useful for module-level returns)

Advanced Options

  • reportLogic: Track boolean evaluation in logical expressions (&&, ||)
  • ignoreClassMethods: Array of method names to skip instrumentation on classes
  • parserPlugins: Babel parser plugins for advanced syntax support
  • produceSourceMap: Generate source maps for debugging instrumented code
  • sourceMapUrlCallback: Custom handling of source map URLs found in code

Error Handling

The instrumenter can throw errors in several scenarios:

  • Invalid Code: Syntax errors in the input JavaScript code
  • Parser Configuration: Invalid parser plugin configurations
  • File System: Issues accessing files when source maps are involved
const { createInstrumenter } = require("istanbul-lib-instrument");

const instrumenter = createInstrumenter();

try {
  const result = instrumenter.instrumentSync('invalid javascript code {', 'test.js');
} catch (error) {
  console.error('Instrumentation failed:', error.message);
  // Handle parsing or transformation errors
}

// For callback style, errors are passed to callback
instrumenter.instrument('invalid code', 'test.js', (err, result) => {
  if (err) {
    console.error('Instrumentation failed:', err.message);
    return;
  }
  // Process result
});

docs

babel-integration.md

coverage-reading.md

index.md

instrumentation.md

tile.json