### exports.builder(yargs) with example Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/check-coverage-command.md Adds a usage example for the check-coverage command. No additional options are declared here; the command inherits all options from buildYargs(). ```javascript exports.builder = function (yargs) { yargs .example('$0 check-coverage --lines 95', "check whether the JSON in c8's output folder meets the thresholds provided") } ``` -------------------------------- ### Install and run c8 Source: https://github.com/bcoe/c8/blob/main/README.md Install c8 globally and run it against a Node.js script to generate coverage metrics for the target file. The output includes coverage metrics for foo.js. ```sh npm i c8 -g c8 node foo.js ``` -------------------------------- ### Full CLI example Source: https://github.com/bcoe/c8/blob/main/_autodocs/configuration.md Run c8 with a full set of CLI options: reporters, reports directory, temp directory, include/exclude patterns, extension, all files, source directory, and coverage thresholds. The command executes node ./dist/main.js. ```sh c8 --reporter=text --reporter=html \ --reports-dir=./coverage \ --temp-directory=./coverage/tmp \ --include='src/**/*.js' \ --exclude='**/node_modules/**' \ --extension=.js \ --all --src=src \ --check-coverage --lines=95 --functions=90 --branches=85 --statements=95 \ node ./dist/main.js ``` -------------------------------- ### runMonocart() usage example Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Example of using runMonocart() via the Report constructor. This is equivalent to running c8 with --experimental-monocart and the specified reporters. The reporter option is unused in monocart mode; argv.reporter drives output. ```javascript const { Report } = require('c8') // Equivalent of `c8 --experimental-monocart --reporter=v8 --reporter=console-details node foo.js` Report({ reporter: [], // unused in monocart mode; argv.reporter drives output tempDirectory: './coverage/tmp', reportsDirectory: './coverage', monocartArgv: { reporter: ['v8', 'console-details'], reportsDir: './coverage', tempDirectory: './coverage/tmp', skipFull: false, clean: false, all: false, excludeAfterRemap: false } }).run() ``` -------------------------------- ### Install monocart-coverage-reports Source: https://github.com/bcoe/c8/blob/main/README.md Installs the required monocart-coverage-reports package as a dev dependency. ```sh npm i monocart-coverage-reports@2 --save-dev ``` -------------------------------- ### Using getCoverageMapFromAllCoverageFiles to log line coverage Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Example usage of getCoverageMapFromAllCoverageFiles. Creates a Report instance with specified options, then logs the line coverage percentage from the resulting coverage map. ```javascript const { Report } = require('c8') const report = Report({ reporter: ['text'], tempDirectory: './coverage/tmp', resolve: process.cwd(), wrapperLength: 0, excludeAfterRemap: true }) report.getCoverageMapFromAllCoverageFiles().then((map) => { const summary = map.getCoverageSummary() console.log(`lines: ${summary.lines.pct}%`) }) ``` -------------------------------- ### hideInstrumenterArgs usage example Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/parse-args.md Shows how to call hideInstrumenterArgs with the parsed argv from buildYargs().parse(). The example sets process.argv to ['node', 'c8', '--lines=90', 'my-app', '--help'] and expects childArgs to equal ['my-app', '--help']. ```javascript process.argv = ['node', 'c8', '--lines=90', 'my-app', '--help'] const { buildYargs, hideInstrumenterArgs } = require('c8/lib/parse-args') const childArgs = hideInstrumenterArgs(buildYargs().parse(['--lines=90', 'my-app'])) // childArgs === ['my-app', '--help'] ``` -------------------------------- ### Usage example of getSourceMapFromFile Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/source-map-from-file.md Example usage of getSourceMapFromFile. It loads the map for a compiled file and logs sources and mappings, or a fallback message if null. ```javascript const getSourceMapFromFile = require('c8/lib/source-map-from-file') const map = getSourceMapFromFile('./dist/index.js') if (map !== null) { console.log(map.sources, map.mappings) } else { console.log('no sourceMappingURL comment, or map unreadable') } ``` -------------------------------- ### Import and usage of Watermark and Report Source: https://github.com/bcoe/c8/blob/main/_autodocs/types.md Shows how to import the Watermark type and use it with the Report class. The example creates a Report instance with a text reporter, a temp directory, and watermarks for lines, functions, branches, and statements. ```TypeScript import { Report, type Watermark } from 'c8' const lines: Watermark = [80, 95] // red below 80%, green at/above 95% const report = new Report({ reporter: ['text'], tempDirectory: './coverage/tmp', watermarks: { lines, functions: [80, 95], branches: [75, 90], statements: [80, 95] } }) ``` -------------------------------- ### importMonocart() usage example Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Example usage of importMonocart(). Creates a Report instance with monocartArgv and reporter options, then calls importMonocart() to load the monocart-coverage-reports module. ```javascript const report = Report({ monocartArgv: {}, reporter: ['v8'] }) report.importMonocart() // → node_modules/monocart-coverage-reports entry ``` -------------------------------- ### Ignore all lines until told with /* c8 ignore start */ and /* c8 ignore stop */ Source: https://github.com/bcoe/c8/blob/main/README.md Use `/* c8 ignore start */` and `/* c8 ignore stop */` to ignore all lines between these comments. This is useful for ignoring entire blocks of code, such as a function that should not be covered. ```javascript /* c8 ignore start */ function dontMindMe() { // ... } /* c8 ignore stop */ ``` -------------------------------- ### hideInstrumenteeArgs usage example Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/parse-args.md Shows how to call hideInstrumenteeArgs() after setting process.argv to ['node', 'c8', '--foo=99', 'my-app', '--help']. The function returns ['--foo=99', 'my-app']. ```javascript process.argv = ['node', 'c8', '--foo=99', 'my-app', '--help'] const { hideInstrumenteeArgs } = require('c8/lib/parse-args') console.log(hideInstrumenteeArgs()) // ['--foo=99', 'my-app'] ``` -------------------------------- ### Ignore the next N lines with /* c8 ignore next 3 */ Source: https://github.com/bcoe/c8/blob/main/README.md Use `/* c8 ignore next N */` to ignore the next N lines. The example ignores the next 3 lines, which include the `if` statement and its block. ```javascript const myVariable = 99 /* c8 ignore next 3 */ if (process.platform === 'win32') { console.info('hello world') } ``` -------------------------------- ### Basic Report construction with `new` Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Creates a Report instance with the `new` keyword, configuring reporters, directories, exclusions, and watermarks. The `run()` method returns a promise that resolves when all reporters have executed. ```javascript const { Report } = require('c8') const report = new Report({ reporter: ['text', 'html'], reportsDirectory: './coverage', tempDirectory: './coverage/tmp', exclude: ['test/**', 'node_modules/**'], excludeNodeModules: true, all: false, watermarks: { lines: [80, 95], functions: [80, 95], branches: [80, 95], statements: [80, 95] } }) report.run().then(() => { console.log('done') }) ``` -------------------------------- ### getMonocart() usage example Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Example usage of getMonocart(). Creates a Report instance with monocartArgv and then logs the CoverageReport property from the resolved module namespace. ```javascript const report = Report({ monocartArgv: {} }) report.getMonocart().then((MCR) => console.log(MCR.CoverageReport)) ``` -------------------------------- ### bin/c8.js imports and initial argument parsing Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/cli.md Initializes the CLI by requiring foreground-child, outputReport, fs/promises, and parse-args helpers. Hides instrumentee args and builds yargs to parse them. ```javascript const { foregroundChild } = require('foreground-child') const { outputReport } = require('../lib/commands/report') const { rm, mkdir } = require('fs/promises') const { buildYargs, hideInstrumenteeArgs, hideInstrumenterArgs } = require('../lib/parse-args') const instrumenterArgs = hideInstrumenteeArgs() let argv = buildYargs().parse(instrumenterArgs) ``` -------------------------------- ### Run tests Source: https://github.com/bcoe/c8/blob/main/CONTRIBUTING.md Runs the test suite; everything should pass except the snapshot. ```sh npm test ``` -------------------------------- ### Clone and set up c8 repository Source: https://github.com/bcoe/c8/blob/main/CONTRIBUTING.md Clones the forked c8 repository, navigates into it, adds the upstream remote, and fetches upstream changes. ```sh git clone git@github.com:username/c8.git cd c8 git remote add upstream https://github.com/bcoe/c8.git git fetch upstream ``` -------------------------------- ### Run tests and check coverage with --check-coverage Source: https://github.com/bcoe/c8/blob/main/README.md Runs tests and checks coverage in one command; fails if coverage falls below 100%. ```sh c8 --check-coverage --lines 100 npm test ``` -------------------------------- ### Using buildYargs to parse check-coverage arguments Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/parse-args.md Demonstrates how to use buildYargs(true) to parse arguments for the check-coverage command, showing the resulting argv properties. ```javascript const { buildYargs } = require('c8/lib/parse-args') // Simulate `c8 check-coverage --lines 95 --temp-directory ./coverage/tmp` const argv = buildYargs(true).parse([ 'check-coverage', '--lines', '95', '--temp-directory', './coverage/tmp' ]) console.log(argv.lines) // 95 console.log(argv.reporter) // 'text' (string; normalized to array by command handlers) ``` -------------------------------- ### Ignore a block on the current line with /* c8 ignore next */ Source: https://github.com/bcoe/c8/blob/main/README.md Use `/* c8 ignore next */` on the same line to ignore a block on the current line. The example ignores the ternary expression's `'Windowsy'` branch. ```javascript const myVariable = 99 const os = process.platform === 'darwin' ? 'OSXy' /* c8 ignore next */ : 'Windowsy' ``` -------------------------------- ### buildYargs(withCommands = false) Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/parse-args.md Builds and returns a configured yargs instance for the c8 CLI. The instance is not parsed; call `.parse(args)` on it to process command-line arguments. ```APIDOC ## buildYargs(withCommands = false) ### Description Builds and returns a configured yargs instance for the c8 CLI. The instance is not parsed; call `.parse(args)` on it to process command-line arguments. ### Method Function call ### Endpoint `buildYargs(withCommands = false)` ### Parameters - **withCommands** (boolean) - Optional, default `false` - When `true`, registers the `check-coverage` and `report` command modules with full builders; when `false`, only attaches command metadata. ### Returns A configured `yargs` instance (from `Yargs([])`). ### Usage Example ```js const { buildYargs } = require('c8/lib/parse-args') // Simulate `c8 check-coverage --lines 95 --temp-directory ./coverage/tmp` const argv = buildYargs(true).parse([ 'check-coverage', '--lines', '95', '--temp-directory', './coverage/tmp' ]) console.log(argv.lines) // 95 console.log(argv.reporter) // 'text' (string; normalized to array by command handlers) ``` ### Registered Options - `config` (with `-c` alias, `config: true`, configParser for JSON and extends resolution, default `findUp.sync(['.c8rc', '.c8rc.json', '.nycrc', '.nycrc.json'])`) - `reporter` (`-r`, default `'text'`) - `reports-dir` (aliases `-o`, `report-dir`, default `'./coverage'`) - `all` - `src` (repeatable) - `exclude-node-modules` (default `true`) - `include` (`-n`, default `[]`) - `exclude` (`-x`, default Istanbul `default-exclude` list) - `extension` (`-e`, default Istanbul `default-extension` list) - `exclude-after-remap` (`-a`, default `false`) - `skip-full` (default `false`) - `check-coverage` (default `false`) - `branches` (default `0`) - `functions` (default `0`) - `lines` (default `90`) - `statements` (default `0`) - `per-file` (default `false`) - `100` (default `false`) - `temp-directory` (default `process.env.NODE_V8_COVERAGE`) - `clean` (default `true`) - `resolve` (default `''`) - `wrapper-length` (number) - `omit-relative` (default `true`) - `allowExternal` (default `false`) - `merge-async` (default `false`) - `experimental-monocart` (default `false`) ### Other yargs Configuration - `.usage('$0 [opts] [script] [opts]')` - `.pkgConf('c8')` — reads a `c8` key from the nearest `package.json` and merges its camelCase fields as defaults - `.demandCommand(1)` — at least one positional argument is required - `.check((argv) => { ... })` — post-parse validation: if `argv.tempDirectory` is falsy, it is populated with `resolve(argv.reportsDir, 'tmp')` (i.e. `./coverage/tmp`); always returns `true` (never produces a validation error itself) - `.epilog('visit https://git.io/vHysA for list of available reporters')` ### Commands - With `withCommands = true`: registers `check-coverage` and `report` command modules with full `yargs.command(module)`. - With `withCommands = false`: only attaches `.command`/`.describe` metadata via `yargs.command(name, describe)`. ``` -------------------------------- ### Two-step flow: run tests and check coverage Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/check-coverage-command.md First command runs tests with c8, collecting V8 coverage into ./coverage/tmp. Second command checks the collected coverage against thresholds (lines, functions, branches at 95). The --temp-directory and --clean=false flags are used to preserve coverage data. ```sh # 1. run tests and collect V8 coverage into ./coverage/tmp c8 --exclude="test/*.js" --temp-directory=./coverage/tmp --clean=false node ./test/runner.js # 2. check the previously collected coverage c8 check-coverage --lines 95 --functions 95 --branches 95 --temp-directory=./coverage/tmp ``` -------------------------------- ### hideInstrumenterArgs(yargv) Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/parse-args.md Strips c8's own flags from the child command line, returning the argument list to pass to the instrumented process. It takes the parsed argv object from buildYargs().parse() and returns the original process.argv entries from the first positional script onward, optionally prepending process.execPath if the first positional starts with a dash. ```APIDOC ## hideInstrumenterArgs(yargv) ### Description Strips c8's own flags from the child command line so that `c8 --foo=99 my-app --help` spawns `my-app --help`. Returns the argument list to pass to the instrumented process. ### Method Function ### Signature `hideInstrumenterArgs(yargv)` ### Parameters - **yargv** (object) - Required - The parsed argv object from `buildYargs().parse(...)`. Must expose `_`, the positional strings array. ### Returns - **string[]** - The argument list to pass to the instrumented process: all original `process.argv` entries from the first positional script onward (`argv.slice(argv.indexOf(yargv._[0]))`). If that first positional starts with `-`, `process.execPath` is unshifted instead. ### Example ```js process.argv = ['node', 'c8', '--lines=90', 'my-app', '--help'] const { buildYargs, hideInstrumenterArgs } = require('c8/lib/parse-args') const childArgs = hideInstrumenterArgs(buildYargs().parse(['--lines=90', 'my-app'])) // childArgs === ['my-app', '--help'] ``` ``` -------------------------------- ### new Report(options) Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Creates a new Report instance. The constructor normalizes the src option and initializes an Exclude instance for filtering coverage files. ```APIDOC ## new Report(options) ### Description Creates a new Report instance. The constructor normalizes the src option and initializes an Exclude instance for filtering coverage files. ### Parameters #### Options - **reporter** (Array) - Required - List of reporter names (e.g., 'text', 'html'). - **reportsDirectory** (string) - Required - Directory where reports will be written. - **tempDirectory** (string) - Required - Directory containing V8 coverage data. - **exclude** (Array) - Optional - Glob patterns to exclude from coverage. - **include** (Array) - Optional - Glob patterns to include in coverage. - **extension** (Array) - Optional - File extensions to consider. - **excludeNodeModules** (boolean) - Optional - Whether to exclude node_modules. - **allowExternal** (boolean) - Optional - Whether to allow external files. - **all** (boolean) - Optional - Whether to include all files in coverage. - **watermarks** (Object) - Optional - Watermarks for lines, functions, branches, statements. - **src** (string|Array) - Optional - Source directories or files. Normalized to an array. - **omitRelative** (boolean) - Optional - Whether to omit relative paths. ### Example ```js const { Report } = require('c8') const report = new Report({ reporter: ['text', 'html'], reportsDirectory: './coverage', tempDirectory: './coverage/tmp', exclude: ['test/**', 'node_modules/**'], excludeNodeModules: true, all: false, watermarks: { lines: [80, 95], functions: [80, 95], branches: [80, 95], statements: [80, 95] } }) ``` ### Factory Form Alternatively, the module can be called as a factory without `new`: ```js const Report = require('c8/lib/report') const report = Report({ reporter: ['lcovonly'], reportsDirectory: './coverage', tempDirectory: './coverage/tmp', include: ['**/*.js'], exclude: [], omitRelative: true, all: true, src: ['src/', 'lib/', 'test/fixtures/multidir1/'], allowExternal: true }) ``` ``` -------------------------------- ### new Report(opts) Source: https://github.com/bcoe/c8/blob/main/_autodocs/types.md Creates a new Report instance with the provided options. The options object configures coverage collection and reporting behavior. ```APIDOC ## new Report(opts) ### Description Creates a new Report instance with the provided options. The options object configures coverage collection and reporting behavior. ### Constructor `new Report(opts)` ### Parameters #### Options Object - **exclude** (string | string[]) - Optional - Glob patterns excluding files from coverage (defaults to the Istanbul default-exclude list when omitted at CLI level) - **extension** (string | string[]) - Optional - Extensions eligible for coverage - **excludeAfterRemap** (boolean) - Optional - Apply exclusions after source-map remapping - **include** (string | string[]) - Optional - Glob patterns restricting coverage to matching files - **reporter** (string[]) - Required - Istanbul reporter names - **reportsDirectory** (string) - Optional - Report output directory - **reporterOptions** (Record>) - Optional - Per-reporter options, keyed by reporter name - **tempDirectory** (string) - Optional - Directory with raw V8 coverage JSON - **watermarks** (Partial<{statements: Watermark; functions: Watermark; branches: Watermark; lines: Watermark}>) - Optional - Per-metric low/high percentages - **omitRelative** (boolean) - Optional - Drop relative (non-absolute) script URLs - **wrapperLength** (number) - Optional - Byte length of JS wrapper prefix (passed to v8-to-istanbul) - **resolve** (string) - Optional - Base directory for resolving script paths - **all** (boolean) - Optional - Include empty coverage for all `src` files - **src** (Array) - Optional - Directories where `--all` looks for source files - **allowExternal** (boolean) - Optional - Allow files outside cwd - **skipFull** (boolean) - Optional - Hide fully covered files - **excludeNodeModules** (boolean) - Optional - Exclude `**/node_modules/**` by default ### Request Example ```typescript const report = new Report({ reporter: ['text'], exclude: ['**/node_modules/**'], extension: ['.js'], excludeAfterRemap: true, include: ['src/**'], reportsDirectory: './coverage', reporterOptions: {}, tempDirectory: './temp', watermarks: { lines: { low: 50, high: 80 } }, omitRelative: false, wrapperLength: 0, resolve: './', all: false, src: ['src'], allowExternal: false, skipFull: false, excludeNodeModules: true }); ``` ### Response #### Success Response Returns a Report instance. #### Response Example ```typescript Report {} ``` ``` -------------------------------- ### run() function — main runtime flow Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/cli.md Defines the async run() function that dispatches to check-coverage/report commands or instruments a script. For instrumenting, it cleans the temp directory, creates it, sets NODE_V8_COVERAGE, and spawns the child with foregroundChild, then outputs the report. ```javascript async function run () { if ([ 'check-coverage', 'report' ].indexOf(argv._[0]) !== -1) { argv = buildYargs(true).parse(process.argv.slice(2)) } else { if (argv.clean) { await rm(argv.tempDirectory, { recursive: true, force: true }) } await mkdir(argv.tempDirectory, { recursive: true }) process.env.NODE_V8_COVERAGE = argv.tempDirectory foregroundChild(hideInstrumenterArgs(argv), async () => { try { await outputReport(argv) return process.exitCode } catch (err) { console.error(err.stack) return 1 } }) } } ``` -------------------------------- ### Require c8/lib/parse-args module Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/parse-args.md Shows how to import the internal parse-args module to access buildYargs, hideInstrumenterArgs, and hideInstrumenteeArgs. ```javascript const { buildYargs, hideInstrumenterArgs, hideInstrumenteeArgs } = require('c8/lib/parse-args') ``` -------------------------------- ### exports.checkCoverages(argv, report) - check coverage thresholds Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/check-coverage-command.md Builds thresholds from argv and checks coverage against the merged coverage map. With perFile, checks each file individually; otherwise checks the global summary. Failures set process.exitCode = 1. ```javascript exports.checkCoverages = async function (argv, report) { const thresholds = { lines: argv.lines, functions: argv.functions, branches: argv.branches, statements: argv.statements } const map = await report.getCoverageMapFromAllCoverageFiles() if (argv.perFile) { map.files().forEach(file => { checkCoverage(map.fileCoverageFor(file).toSummary(), thresholds, file) }) } else { checkCoverage(map.getCoverageSummary(), thresholds) } } ``` -------------------------------- ### .c8rc.json with extends Source: https://github.com/bcoe/c8/blob/main/_autodocs/configuration.md Use a base configuration file and extend it with .c8rc.json. The base.json sets lines threshold and exclude patterns; .c8rc.json overrides lines to 100 and adds reporters. ```json { "lines": 90, "exclude": ["test/**"] } ``` ```json { "extends": "./base.json", "lines": 100, "reporter": ["lcovonly", "text"] } ``` -------------------------------- ### Regenerate reports from existing temp data with c8 report Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report-command.md Shows the two-step workflow: first collect coverage with `c8` writing JSON to `./coverage/tmp`, then later regenerate any reporter set from the same temp data with a threshold gate using `c8 report`. The `--clean=false` flag preserves the temp data for reuse. ```sh # collect coverage (writes JSON to ./coverage/tmp) c8 --temp-directory=./coverage/tmp --clean=false node app.js # later, regenerate any reporter set from the same temp data, with threshold gate c8 report --temp-directory=./coverage/tmp \ --reporter=text --reporter=lcov \ --check-coverage --lines=90 --branches=85 ``` -------------------------------- ### run() Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Executes all configured reporters against the merged coverage map. Returns a Promise that resolves when all reporters have run. ```APIDOC ## run() ### Description Executes all configured reporters against the merged coverage map. Returns a Promise that resolves when all reporters have run. ### Method run ### Returns - **Promise** - Resolves once every configured reporter has been executed against the merged coverage map. ### Behavior - If `monocartArgv` is set, delegates to `runMonocart()`. - Otherwise, creates an istanbul-lib-report context with the configured reports directory, watermarks, and coverage map. - For each reporter name, creates a reporter via istanbul-reports and executes it. ### Errors - Throws `Cannot find module ''` if a reporter name cannot be resolved by istanbul-reports. ### Example ```js const { Report } = require('c8') Report({ reporter: ['text'], tempDirectory: process.env.NODE_V8_COVERAGE || './coverage/tmp', reportsDirectory: './coverage' }).run() ``` ``` -------------------------------- ### Import Report from c8 Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Shows how to import the Report class from the c8 package. The comment notes it is identical to requiring 'c8/lib/report'. ```javascript const { Report } = require('c8') // identical to require('c8/lib/report') ``` -------------------------------- ### runMonocart() method signature Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Constructs a MCR.CoverageReport from this.monocartArgv, then calls cleanCache(), addFromDir(argv.tempDirectory), and generate(). Returns early if getMonocart() returns falsy. Only used when --experimental-monocart/EXPERIMENTAL_MONOCART is enabled, bypassing the Istanbul pipeline. ```javascript async runMonocart () ``` -------------------------------- ### Factory form with full-source coverage Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Uses the factory form (no `new`) to create a report with full-source coverage, including `all: true` and explicit `src` directories. The `run()` promise is caught to log errors and set the exit code. ```javascript const Report = require('c8/lib/report') // module.exports is the factory const report = Report({ reporter: ['lcovonly'], reportsDirectory: './coverage', tempDirectory: './coverage/tmp', include: ['**/*.js'], exclude: [], omitRelative: true, all: true, src: ['src/', 'lib/', 'test/fixtures/multidir1/'], allowExternal: true }) report.run() .catch((err) => { console.error(`coverage report failed: ${err.stack}`) process.exitCode = 1 }) ``` -------------------------------- ### run(): Promise Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Runs the report generation process. This method is the primary entry point for generating coverage reports based on the configured options. ```APIDOC ## Method: run() ### Description Runs the report generation process. This method is the primary entry point for generating coverage reports based on the configured options. ### Method run ### Signature ```ts run(): Promise ``` ### Returns - `Promise` - Resolves when the report generation is complete. ### Notes - When `monocartArgv` is truthy, `run()` delegates to `runMonocart()`. ``` -------------------------------- ### Factory call with environment variable temp directory Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Calls the factory directly with a single text reporter, using the `NODE_V8_COVERAGE` environment variable for the temp directory. The `run()` promise is not handled, so errors are unhandled. ```javascript const { Report } = require('c8') Report({ reporter: ['text'], tempDirectory: process.env.NODE_V8_COVERAGE || './coverage/tmp', reportsDirectory: './coverage' }).run() ``` -------------------------------- ### Create a local branch from upstream/main Source: https://github.com/bcoe/c8/blob/main/CONTRIBUTING.md Creates a local branch tracking upstream/main for development. ```sh git checkout -b my-branch -t upstream/main ``` -------------------------------- ### Require getSourceMapFromFile from c8/lib/source-map-from-file Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/source-map-from-file.md Shows how to import the module's default export. The comment indicates the module exports the function directly. ```javascript const getSourceMapFromFile = require('c8/lib/source-map-from-file') // module.exports = getSourceMapFromFile (lib/source-map-from-file.js:100) ``` -------------------------------- ### getCoverageMapFromAllCoverageFiles() Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/report.md Asynchronously loads and merges coverage data from all V8 coverage files into a single Istanbul coverage map. The method is memoized and returns a Promise that resolves to a CoverageMap object. ```APIDOC ## getCoverageMapFromAllCoverageFiles() ### Description Asynchronously loads and merges coverage data from all V8 coverage files into a single Istanbul coverage map. The method is memoized, so subsequent calls return the same result. Per-file failures are non-fatal and logged via debuglog. ### Method async getCoverageMapFromAllCoverageFiles() ### Returns - **Promise** - An object responding to `files()`, `fileCoverageFor(file)`, `getCoverageSummary()`, and `merge()`. This is the shape consumed by `istanbul-lib-report` and by `checkCoverages()`. ### Behavior - Memoized: subsequent calls return `this._allCoverageFiles`. - Iterates every script in the merged V8 process coverage. - For each script: loads its source map, resolves the script path, constructs a `v8-to-istanbul` converter, loads it, applies V8 function ranges, and merges the result into the shared coverage map. - Per-file failures are non-fatal: errors are swallowed and logged through `util.debuglog('c8')` (enable with `NODE_DEBUG=c8`). ### Example ```js const { Report } = require('c8') const report = Report({ reporter: ['text'], tempDirectory: './coverage/tmp', resolve: process.cwd(), wrapperLength: 0, excludeAfterRemap: true }) report.getCoverageMapFromAllCoverageFiles().then((map) => { const summary = map.getCoverageSummary() console.log(`lines: ${summary.lines.pct}%`) }) ``` ``` -------------------------------- ### exports.command and exports.describe Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/check-coverage-command.md Defines the command name and description for the check-coverage command. ```javascript exports.command = 'check-coverage' exports.describe = 'check whether coverage is within thresholds provided' ``` -------------------------------- ### Per-file thresholds and --100 flag Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/check-coverage-command.md First command checks per-file thresholds with --per-file. Second command uses --100 to require all coverage metrics (lines, functions, branches, statements) to be at least 100. ```sh c8 check-coverage --lines 95 --per-file c8 check-coverage --100 # lines/functions/branches/statements all >= 100 ``` -------------------------------- ### package.json c8 configuration Source: https://github.com/bcoe/c8/blob/main/_autodocs/configuration.md Configure c8 coverage thresholds and reporting in package.json. The c8 section sets reporters, reports directory, line and branch thresholds, enables check-coverage, and excludes test and build files. ```json { "name": "my-app", "scripts": { "test": "c8 mocha" }, "c8": { "reporter": ["text", "html"], "reports-dir": "./coverage", "lines": 95, "branches": 90, "check-coverage": true, "exclude": ["test/**", "build/**"] } } ``` -------------------------------- ### CLI invocation shapes Source: https://github.com/bcoe/c8/blob/main/_autodocs/api-reference/cli.md Shows the various ways to invoke the c8 CLI: instrument a script, regenerate reports, check thresholds, and run with check in one step. Includes a comment noting that --reporter is hideInstrumenteeArgs'ed for c8. ```sh # instrument a script (binary pattern) c8 [c8-opts]