Core istanbul API for JS code coverage instrumentation and analysis
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
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
});Main instrumenter class providing synchronous and asynchronous instrumentation methods.
class Instrumenter {
constructor(opts?: InstrumenterOptions);
}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
);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);
});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);
}import/export)return statements outside functions (useful for module-level returns)The instrumenter can throw errors in several scenarios:
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
});