Registry / testing / istanbul-lib-instrument

istanbul-lib-instrument

JSON →
library6.0.3jsnpmunverified

istanbul-lib-instrument serves as the core engine within the Istanbul.js ecosystem for transforming JavaScript source code into an instrumented form suitable for code coverage analysis. It injects tracking statements (for lines, functions, branches, and statements) into code. The library, currently at version 6.0.3 (released June 2024), is an active component of the `istanbuljs` monorepo, which receives regular updates across its packages to support modern JavaScript features and tooling. Its key differentiator is its reliance on Babel for its instrumentation process, providing two primary modes of operation: a direct programmatic API for straightforward source code transformation, and a `programVisitor` function designed for seamless integration within custom Babel plugins, which is the recommended approach for developers already utilizing Babel in their build pipelines.

npm install istanbul-lib-instrument
INSTALL
IMPORT
SIG · ISTANBUL-LIB-INSTR
I
istanbul-lib-instrument
testingjavascriptv6.0.3
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createInstrumenter
import { createInstrumenter } from 'istanbul-lib-instrument';
const createInstrumenter = require('istanbul-lib-instrument').createInstrumenter;
This is the primary factory function for programmatic instrumentation. CommonJS `require` works but ESM `import` is preferred.
Instrumenter
import { Instrumenter } from 'istanbul-lib-instrument';
import Instrumenter from 'istanbul-lib-instrument';
While `createInstrumenter` returns an `Instrumenter` instance, the class itself can be imported for extending or advanced use cases. It's a named export, not a default.
programVisitor
import { programVisitor } from 'istanbul-lib-instrument';
const { programVisitor } = require('istanbul-lib-instrument');
Used for integration into Babel plugins. It expects a `babel-types` instance as an argument for its visitor functions.

Demonstrates how to use `createInstrumenter` and `instrumentSync` to programmatically instrument a JavaScript string, generate source maps, and log the resulting instrumented code. It also highlights options for customizing the instrumentation process.

import { createInstrumenter } from 'istanbul-lib-instrument'; const codeToInstrument = ` function calculate(a, b) { if (a > 0) { return a + b; } else { return b; } } const result = calculate(10, 5); console.log(result); `; const filename = '/app/src/example.js'; // Crucial for unique coverage reporting try { const instrumenter = createInstrumenter({ coverageVariable: '__CUSTOM_COVERAGE_OBJ__', // Define a custom global variable preserveComments: true, compact: false, // Output human-readable instrumented code esModules: true, // Enable ES module syntax support produceSourceMap: true // Generate a source map for remapping coverage }); const instrumentedCode = instrumenter.instrumentSync(codeToInstrument, filename); const sourceMap = instrumenter.lastSourceMap(); console.log('--- Original Code ---'); console.log(codeToInstrument); console.log('\n--- Instrumented Code ---'); console.log(instrumentedCode); console.log('\n--- Generated Source Map (snippet) ---'); // Source map objects can be large, showing a snippet for brevity console.log(JSON.stringify(sourceMap?.toJSON() || {}, null, 2).substring(0, 500) + '...'); // To obtain coverage, execute the instrumented code in a global context // where the coverage variable is defined, then retrieve it. // Example (Node.js): // global.__CUSTOM_COVERAGE_OBJ__ = {}; // eval(instrumentedCode); // console.log('\n--- Coverage Object (after execution) ---'); // console.log(JSON.stringify(global.__CUSTOM_COVERAGE_OBJ__, null, 2)); } catch (error) { console.error('Instrumentation failed:', error); }
Debug
Known issues
breakingVersion 1.1.x introduced a fundamental architectural change by transitioning to Babel for JavaScript parsing and transformation. This replaced the previously used parser/generator, potentially breaking existing integrations that relied on internal AST structures or specific behaviors of the pre-Babel implementation. Consult `v0-changes.md` for detailed incompatibilities.
fix
Review `v0-changes.md` for specific migration steps. Update your codebase to align with Babel-based instrumentation practices, particularly if you were accessing internal APIs or custom parser options.
affects: >=1.1.0
gotcha`istanbul-lib-instrument` relies on Babel for parsing, meaning support for new JavaScript syntax features (e.g., decorators, pipeline operator, `importAttributes`) depends on the internal Babel version and its configured parser plugins. An older version might not correctly process modern syntax, leading to `SyntaxError`.
fix
Ensure you are using the latest stable version of `istanbul-lib-instrument` (>=6.0.3 for `importAttributes` support). If using `programVisitor` with your own Babel setup, ensure your Babel configuration includes all necessary plugins to parse your source code.
affects: <6.0.3
gotchaWhile `istanbul-lib-instrument` can generate source maps for instrumented code, achieving accurate coverage reporting with transpiled or bundled code (e.g., TypeScript, Webpack) heavily depends on correct input source maps and proper integration with `istanbul-lib-source-maps`. Misconfigured build tools or source map generation can lead to misaligned or incorrect coverage data.
fix
Always pass a valid `inputSourceMap` to `instrumentSync` if your code is already transpiled. Ensure your build process is correctly configured to generate and pass through source maps at each transformation step. Validate source map chains with tools like `source-map-explorer`.
affects: >=1.0.0
Errors
Common errors & fixes
SyntaxError: Unexpected token '...', 'const' (or similar Babel parsing errors)
The JavaScript code being instrumented contains syntax features (e.g., new ECMAScript proposals, TypeScript syntax) that are not supported by the internal Babel parser within `istanbul-lib-instrument` or by its default configuration.
fix
Update `istanbul-lib-instrument` to its latest version to ensure support for newer JavaScript syntax. If using the `programVisitor` with your own Babel setup, verify that your Babel configuration (especially `parserPlugins`) includes the necessary plugins for the syntax in your source code.
ReferenceError: __coverage__ is not defined (or custom variable name)
The global coverage variable (default: `__coverage__`, or a custom name set via `coverageVariable` option) was not initialized or accessible in the JavaScript runtime environment before the instrumented code was executed.
fix
Before executing instrumented code, ensure the global coverage object is defined. In Node.js, `global.__coverage__ = {};`. In browsers, `window.__coverage__ = {};`. Confirm the `coverageVariable` option used during instrumentation matches the variable you are checking.
Upgrade
Version history
6.0.3latest on npm
Audit
Dependencies
@babel/typesoptionalRequired as a parameter ('types' object) for the `programVisitor` function when integrating with custom Babel plugins.
Agent activity
5 hits · last 30 days
node
4
Amazon
1
Resources
istanbul-lib-instrument — npm install istanbul-lib-instrument · libregistry