or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# @vitest/coverage-c8

1

2

The `@vitest/coverage-c8` package provides a C8 coverage provider integration for the Vitest testing framework. It enables comprehensive code coverage analysis using the C8 JavaScript coverage tool, which leverages V8's built-in code coverage capabilities. This provider handles source map remapping for accurate coverage reporting in TypeScript and bundled code.

3

4

## Package Information

5

6

- **Package Name**: @vitest/coverage-c8

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @vitest/coverage-c8`

10

11

## Core Imports

12

13

```typescript

14

import coverageC8 from "@vitest/coverage-c8";

15

// coverageC8 provides: getProvider, startCoverage, takeCoverage, stopCoverage

16

```

17

18

For CommonJS environments:

19

20

```javascript

21

const coverageC8 = require("@vitest/coverage-c8");

22

```

23

24

Direct import of coverage functions:

25

26

```typescript

27

import { startCoverage, takeCoverage, stopCoverage } from "@vitest/coverage-c8";

28

```

29

30

## Basic Usage

31

32

Configure Vitest to use the C8 coverage provider:

33

34

```typescript

35

// vitest.config.ts

36

import { defineConfig } from 'vitest/config';

37

38

export default defineConfig({

39

test: {

40

coverage: {

41

provider: 'c8',

42

reporter: ['text', 'html', 'json'],

43

exclude: ['node_modules/', '**/*.test.ts'],

44

allowExternal: false,

45

excludeNodeModules: true,

46

},

47

},

48

});

49

```

50

51

Run tests with coverage:

52

53

```bash

54

npx vitest run --coverage

55

```

56

57

Using coverage functions programmatically:

58

59

```typescript

60

import { startCoverage, takeCoverage, stopCoverage } from '@vitest/coverage-c8';

61

62

// Start collecting coverage

63

startCoverage();

64

65

// Your test code here...

66

67

// Take a coverage snapshot

68

const coverage = await takeCoverage();

69

console.log(coverage.result.length); // Number of covered files

70

71

// Stop coverage collection

72

stopCoverage();

73

```

74

75

## Architecture

76

77

The package is built around several key components:

78

79

- **Coverage Provider**: `C8CoverageProvider` class extending `BaseCoverageProvider` and implementing Vitest's `CoverageProvider` interface

80

- **Coverage Collection**: Functions (`startCoverage`, `takeCoverage`, `stopCoverage`) for interacting with V8 coverage data using Node.js Inspector API

81

- **Source Map Processing**: Advanced utilities for accurate coverage reporting in transformed code (TypeScript, bundled files) with Vite helper removal

82

- **Report Generation**: Integration with C8's reporting system for various output formats using Istanbul reporters

83

- **Base Provider Methods**: Inherited utilities for threshold checking, reporter resolution, and threshold auto-updating

84

85

## Capabilities

86

87

### Coverage Provider Module

88

89

The main export provides a coverage provider module that integrates with Vitest's coverage system.

90

91

```typescript { .api }

92

/**

93

* Main module export providing coverage provider and collection functions

94

*/

95

interface CoverageProviderModule {

96

/** Factory for creating a new coverage provider */

97

getProvider(): Promise<C8CoverageProvider>;

98

/** Start coverage collection using Node.js inspector */

99

startCoverage(): void;

100

/** Take coverage snapshot and return filtered results */

101

takeCoverage(): Promise<{ result: Profiler.ScriptCoverage[] }>;

102

/** Stop coverage collection and disconnect inspector */

103

stopCoverage(): void;

104

}

105

106

/**

107

* Default export object structure

108

*/

109

const coverageModule: CoverageProviderModule;

110

export default coverageModule;

111

```

112

113

### Coverage Provider Implementation

114

115

Core coverage provider class that handles collection, processing, and reporting.

116

117

```typescript { .api }

118

/**

119

* C8 coverage provider implementing CoverageProvider interface

120

*/

121

class C8CoverageProvider extends BaseCoverageProvider implements CoverageProvider {

122

name: string; // Always 'c8'

123

ctx: Vitest;

124

options: ResolvedCoverageOptions<'c8'>;

125

coverages: Profiler.TakePreciseCoverageReturnType[];

126

127

/** Initialize the provider with Vitest context and configuration */

128

initialize(ctx: Vitest): void;

129

130

/** Get resolved coverage options */

131

resolveOptions(): ResolvedCoverageOptions<'c8'>;

132

133

/** Clean coverage directory and reset coverage data */

134

clean(clean?: boolean): Promise<void>;

135

136

/** Collect coverage data after suite run */

137

onAfterSuiteRun(meta: AfterSuiteRunMeta): void;

138

139

/** Generate and write coverage reports */

140

reportCoverage(reportContext?: ReportContext): Promise<void>;

141

142

/** Resolve reporters from various configuration options */

143

resolveReporters(configReporters: NonNullable<BaseCoverageOptions['reporter']>): ResolvedCoverageOptions['reporter'];

144

145

/** Check collected coverage against configured thresholds */

146

checkThresholds({ coverageMap, thresholds, perFile }: {

147

coverageMap: CoverageMap;

148

thresholds: Record<'lines' | 'functions' | 'statements' | 'branches', number | undefined>;

149

perFile?: boolean;

150

}): void;

151

152

/** Update thresholds when current coverage is above configured thresholds */

153

updateThresholds({ configurationFile, coverageMap, thresholds, perFile }: {

154

coverageMap: CoverageMap;

155

thresholds: Record<'lines' | 'functions' | 'statements' | 'branches', number | undefined>;

156

perFile?: boolean;

157

configurationFile?: string;

158

}): void;

159

}

160

```

161

162

### Coverage Collection Functions

163

164

Low-level functions for interacting with V8's coverage system through Node.js Inspector API.

165

166

```typescript { .api }

167

/**

168

* Start coverage collection using Node.js inspector

169

* Connects to inspector and enables precise coverage tracking

170

*/

171

function startCoverage(): void;

172

173

/**

174

* Take a coverage snapshot and return filtered results

175

* Filters out node_modules and non-file URLs using internal filterResult function

176

* Only includes files that start with 'file://' and don't contain '/node_modules/'

177

* @returns Promise resolving to coverage data with filtered script coverage

178

*/

179

function takeCoverage(): Promise<{ result: Profiler.ScriptCoverage[] }>;

180

181

/**

182

* Stop coverage collection and disconnect inspector

183

* Disables profiler and closes inspector session

184

*/

185

function stopCoverage(): void;

186

```

187

188

### Configuration Options

189

190

C8-specific coverage configuration options extending base coverage options.

191

192

```typescript { .api }

193

/**

194

* Configuration options specific to C8 coverage provider

195

*/

196

interface CoverageC8Options extends BaseCoverageOptions {

197

/** Allow files from outside of current working directory */

198

allowExternal?: boolean; // default: false

199

200

/** Exclude coverage under /node_modules/ */

201

excludeNodeModules?: boolean; // default: true

202

203

/** Directories used when --all is enabled */

204

src?: string[];

205

206

/** Shortcut for 100% coverage thresholds on all metrics */

207

100?: boolean; // default: false

208

209

/** Watermarks for statements, lines, branches and functions */

210

watermarks?: {

211

statements?: [number, number];

212

functions?: [number, number];

213

branches?: [number, number];

214

lines?: [number, number];

215

};

216

}

217

218

/**

219

* Base coverage options shared across all providers

220

*/

221

interface BaseCoverageOptions {

222

/** Enable coverage collection */

223

enabled?: boolean; // default: false

224

225

/** Files included in coverage as glob patterns */

226

include?: string[]; // default: ['**']

227

228

/** File extensions to include in coverage */

229

extension?: string | string[]; // default: ['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.vue', '.svelte']

230

231

/** Files excluded from coverage as glob patterns */

232

exclude?: string[];

233

234

/** Include all files, including untested ones */

235

all?: boolean; // default: false

236

237

/** Clean coverage results before running tests */

238

clean?: boolean; // default: true

239

240

/** Clean coverage report on watch rerun */

241

cleanOnRerun?: boolean; // default: true

242

243

/** Directory to write coverage report to */

244

reportsDirectory?: string;

245

246

/** Coverage reporters to use */

247

reporter?: CoverageReporter | CoverageReporter[] | CoverageReporterWithOptions[];

248

249

/** Skip files with 100% coverage in reports */

250

skipFull?: boolean; // default: false

251

252

/** Check thresholds per file */

253

perFile?: boolean; // default: false

254

255

/** Coverage thresholds */

256

lines?: number;

257

functions?: number;

258

branches?: number;

259

statements?: number;

260

261

/** Update thresholds automatically when coverage is higher */

262

thresholdAutoUpdate?: boolean; // default: false

263

264

/** Generate coverage report even when tests fail */

265

reportOnFailure?: boolean; // default: true

266

}

267

```

268

269

### Coverage Reporter Types

270

271

Available coverage report formats and their configuration.

272

273

```typescript { .api }

274

/**

275

* Available coverage reporters from Istanbul

276

*/

277

type CoverageReporter =

278

| 'clover'

279

| 'cobertura'

280

| 'html'

281

| 'html-spa'

282

| 'json'

283

| 'json-summary'

284

| 'lcov'

285

| 'lcovonly'

286

| 'none'

287

| 'teamcity'

288

| 'text'

289

| 'text-lcov'

290

| 'text-summary';

291

292

/**

293

* Reporter with configuration options

294

*/

295

type CoverageReporterWithOptions = [CoverageReporter, object];

296

```

297

298

### Coverage Metadata Types

299

300

Types for coverage collection and reporting context.

301

302

```typescript { .api }

303

/**

304

* Context passed to reportCoverage method

305

*/

306

interface ReportContext {

307

/** Indicates whether all tests were run (false for selective test runs) */

308

allTestsRun?: boolean;

309

}

310

311

/**

312

* Metadata from suite run containing coverage data

313

*/

314

interface AfterSuiteRunMeta {

315

/** Coverage data collected during suite execution */

316

coverage: Profiler.TakePreciseCoverageReturnType;

317

}

318

319

/**

320

* Coverage map from Istanbul library

321

*/

322

interface CoverageMap {

323

files(): string[];

324

fileCoverageFor(filename: string): FileCoverage;

325

getCoverageSummary(): CoverageSummary;

326

}

327

328

/**

329

* Coverage summary with metrics

330

*/

331

interface CoverageSummary {

332

data: {

333

lines: { pct: number };

334

functions: { pct: number };

335

statements: { pct: number };

336

branches: { pct: number };

337

};

338

lines: { pct: number };

339

functions: { pct: number };

340

statements: { pct: number };

341

branches: { pct: number };

342

}

343

344

/**

345

* File coverage information

346

*/

347

interface FileCoverage {

348

toSummary(): CoverageSummary;

349

}

350

351

/**

352

* V8 profiler types from Node.js inspector

353

*/

354

namespace Profiler {

355

interface TakePreciseCoverageReturnType {

356

result: ScriptCoverage[];

357

}

358

359

interface ScriptCoverage {

360

scriptId: string;

361

url: string;

362

functions: FunctionCoverage[];

363

}

364

365

interface FunctionCoverage {

366

functionName: string;

367

ranges: CoverageRange[];

368

isBlockCoverage: boolean;

369

}

370

371

interface CoverageRange {

372

startOffset: number;

373

endOffset: number;

374

count: number;

375

}

376

}

377

```

378

379

## Error Handling

380

381

The package handles several error scenarios:

382

383

- **Stackblitz Environment**: Gracefully handles Stackblitz limitations by returning empty coverage and logging appropriate messages

384

- **File System Errors**: Robust error handling for report directory operations with retry logic (maxRetries: 10)

385

- **Inspector API Errors**: Proper error handling in coverage collection functions with promise rejection

386

- **Source Map Processing**: Fallback behavior when source maps are unavailable or malformed

387

- **Configuration File Updates**: Error handling for threshold auto-update when configuration file is missing

388

389

## Deprecation Notice

390

391

**Important**: This package is deprecated and being replaced by `@vitest/coverage-v8`. The provider automatically displays a deprecation warning when initialized:

392

393

```

394

DEPRECATION @vitest/coverage-c8 is being replaced by @vitest/coverage-v8.

395

See https://github.com/vitest-dev/vitest/pull/3339 for more information.

396

```

397

398

Users should migrate to the newer V8 coverage provider for better performance and maintainability.