JavaScript API
Top-Level Exports
version
version()
Returns the @tracecov/core package version string.
Returns: string
Example
import { version } from '@tracecov/core';
console.log(version()); // "0.24.2"
edition
edition()
Returns the build edition. The published @tracecov/core package is the Community edition and always returns "community", so recordFromHar, recordFromPostman, and recordFromVcr always throw in it.
Returns: string
Example
import { edition } from '@tracecov/core';
console.log(edition()); // "community"
CoverageMap
CoverageMap
Tracks API test coverage against an OpenAPI specification. Every example below starts with import { CoverageMap } from '@tracecov/core';.
fromDict
CoverageMap.fromDict(schema, options?)
Create a coverage map from a parsed OpenAPI specification object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema |
object |
Parsed OpenAPI specification | required |
options |
FromDictOptions | null |
Optional configuration | null |
Returns: CoverageMap
Example
import { CoverageMap } from '@tracecov/core';
const schema = { openapi: '3.0.0', info: { title: 'API', version: '1.0' }, paths: {} };
const coverage = CoverageMap.fromDict(schema);
// With base path for APIs hosted under a prefix:
// CoverageMap.fromDict(schema, { basePath: '/api/v1' })
fromPath
CoverageMap.fromPath(path, options?)
Create a coverage map from an OpenAPI specification file (JSON or YAML).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path |
string |
File path to the OpenAPI specification | required |
options |
FromPathOptions | null |
Optional configuration | null |
Returns: CoverageMap
Example
import { CoverageMap } from '@tracecov/core';
const coverage = CoverageMap.fromPath('openapi.json');
// or: CoverageMap.fromPath('openapi.yaml', { basePath: '/api/v1' })
fromUrl
CoverageMap.fromUrl(url, options?)
Fetch an OpenAPI specification from a URL and create a CoverageMap. Returns a Promise, so use await.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url |
string |
URL of the OpenAPI specification (JSON or YAML) | required |
options |
FromDictOptions | null |
Optional configuration | null |
Returns: Promise<CoverageMap>
Example
import { CoverageMap } from '@tracecov/core';
const coverage = await CoverageMap.fromUrl('https://api.example.com/openapi.json');
// With base path for APIs hosted under a prefix:
// await CoverageMap.fromUrl('https://api.example.com/openapi.json', { basePath: '/api/v1' })
record
record(request, response?, timestamp?)
Record an HTTP interaction for coverage tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request |
HttpRequest |
The HTTP request | required |
response |
HttpResponse | null |
The HTTP response | null |
timestamp |
number | null |
Unix timestamp in seconds | current time |
Returns: void
Example
const coverage = CoverageMap.fromPath('openapi.json');
coverage.record(
{
method: 'POST',
url: 'https://api.example.com/users',
headers: { 'content-type': 'application/json' },
body: Buffer.from(JSON.stringify({ name: 'Alice' })),
},
{
statusCode: 201,
elapsed: 0.42,
headers: { 'content-type': 'application/json' },
body: Buffer.from(JSON.stringify({ id: 1, name: 'Alice' })),
},
);
Response keyword coverage needs both the response body and its content-type header.
recordError
recordError(method, url, message)
Annotate the operation matching url with a request-level error, such as a network failure, without counting it as coverage. No-op if url matches no operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
string |
HTTP method | required |
url |
string |
Full request URL (matched against operations) | required |
message |
string |
Error message to record | required |
Returns: void. Throws on an invalid HTTP method.
Example
const coverage = CoverageMap.fromPath('openapi.json');
coverage.recordError('GET', 'https://api.example.com/users/1', 'ECONNREFUSED');
statistic
statistic()
Get aggregate coverage statistics.
Returns: CoverageStatistic
Example
const coverage = CoverageMap.fromPath('openapi.json');
const stats = coverage.statistic();
console.log(`Operations: ${stats.operations.seen}/${stats.operations.total}`);
console.log(`Keywords: ${stats.keywords.full}/${stats.keywords.total} fully covered`);
// Operations: 1/19
// Keywords: 0/290 fully covered
errors
errors()
Return the schema-collection errors found while building the map — invalid parameter definitions, unresolvable $refs, and similar. A non-empty result explains why part of the spec has no coverage: those operations or parameters were never registered. Empty when the spec parsed cleanly.
Returns: SchemaError[]
Example
const coverage = CoverageMap.fromPath('openapi.json');
for (const e of coverage.errors()) {
console.warn(`${e.method ?? '*'} ${e.path}: ${e.message}`);
}
// GET /users: Field `schema` is missing
diagnostics
diagnostics()
Return every problem found in the specification — invalid patterns, unresolvable references, unsatisfiable schemas, and similar — each naming the position it applies to. The same list appears as diagnostics in the JSON report.
Returns: Diagnostic[]. Each entry has severity ("error" or "warning"), kind, and at, the position: { in: 'path_item', path }, { in: 'operation', path, method }, { in: 'parameter', path, method, location, name }, or { in: 'response_body', path, method, status, media_type }. Kind-specific fields such as pattern, reference, message, or schema_path are present when relevant. Importable: import type { Diagnostic } from '@tracecov/core'.
Example
const coverage = CoverageMap.fromPath('openapi.json');
for (const d of coverage.diagnostics()) {
console.warn(`${d.severity} ${d.kind} at ${d.at.path}`);
}
// warning invalid_schema at /users
generateHtmlReport
generateHtmlReport(options?)
Generate an HTML coverage report as a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
HtmlReportOptions | null |
Optional configuration | null |
Returns: string
Example
const coverage = CoverageMap.fromPath('openapi.json');
const html = coverage.generateHtmlReport({ title: 'My API Coverage' });
generateJsonReport
generateJsonReport()
Generate a JSON coverage report as a string. See JSON Report Format for schema details.
Returns: string
Example
const coverage = CoverageMap.fromPath('openapi.json');
const data = JSON.parse(coverage.generateJsonReport());
console.log(data.summary.operations);
// { covered: 1, total: 19, percent: 5.2631578947368425 }
generateMarkdownReport
generateMarkdownReport(options?)
Generate a Markdown coverage report as a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
MarkdownReportOptions | null |
Optional configuration | null |
Returns: string
Example
const coverage = CoverageMap.fromPath('openapi.json');
// Compact format for GitHub PR comments
const md = coverage.generateMarkdownReport({ isPullRequest: true });
generateTextReport
generateTextReport(options?)
Generate a plain-text coverage report for terminal output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
TextReportOptions | null |
Optional configuration | null |
Returns: string
Example
const coverage = CoverageMap.fromPath('openapi.json');
const report = coverage.generateTextReport({ width: 120, skipCovered: true });
console.log(report);
saveHtmlReport
saveHtmlReport(options?)
Write an HTML coverage report to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
SaveHtmlOptions | null |
Optional configuration | null |
Returns: void. Default output file: tracecov.html
Example
const coverage = CoverageMap.fromPath('openapi.json');
coverage.saveHtmlReport(); // → tracecov.html
coverage.saveHtmlReport({ outputFile: 'coverage.html' });
coverage.saveHtmlReport({ title: 'My API', outputFile: 'coverage.html' });
saveJsonReport
saveJsonReport(options?)
Write a JSON coverage report to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
SaveJsonOptions | null |
Optional configuration | null |
Returns: void. Default output file: tracecov.json
Example
const coverage = CoverageMap.fromPath('openapi.json');
coverage.saveJsonReport();
coverage.saveJsonReport({ outputFile: 'report.json' });
saveMarkdownReport
saveMarkdownReport(options?)
Write a Markdown coverage report to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
SaveMarkdownOptions | null |
Optional configuration | null |
Returns: void. Default output file: tracecov.md
Example
const coverage = CoverageMap.fromPath('openapi.json');
coverage.saveMarkdownReport({ isPullRequest: true, outputFile: 'coverage.md' });
uncoveredKeywords
uncoveredKeywords()
Get a list of JSON Schema keywords that have not been fully covered.
Prefer coverageGaps()
uncoveredKeywords() reports only JSON Schema keywords. coverageGaps() returns every kind of gap — uncovered operations, responses, parameters, examples, and keywords — as a typed discriminated union. Prefer it for new code.
Returns: UncoveredKeyword[]
Example
const coverage = CoverageMap.fromPath('openapi.json');
for (const kw of coverage.uncoveredKeywords()) {
console.log(`${kw.method} ${kw.path} ${kw.parameter} ${kw.schemaPath}: ${kw.state}`);
}
// GET /api/v3/pet/findByStatus status /enum: needs_invalid
coverageGaps
coverageGaps()
Return every actionable coverage gap — uncovered operations, responses, parameters, examples, and keywords — as a typed discriminated union on kind.
Returns: CoverageGap[]
Example
const coverage = CoverageMap.fromPath('openapi.json');
for (const gap of coverage.coverageGaps()) {
if (gap.kind === 'operation_unseen') {
console.log(`never called: ${gap.method} ${gap.path}`);
} else if (gap.kind === 'response_uncovered') {
console.log(`missing ${gap.status_code} for ${gap.method} ${gap.path}`);
}
}
// never called: POST /api/v3/pet
// missing 400 for GET /api/v3/pet/findByStatus
unmatchedRequests
unmatchedRequests()
Return the requests that matched no documented operation, most frequent first. Grouped by
(method, host, path). Reporting only — never affects coverage percentages or thresholds.
Returns: UnmatchedRequest[]
At most 1000 distinct groups are tracked; see unmatchedOverflow().
Example
const coverage = CoverageMap.fromPath('openapi.json');
for (const entry of coverage.unmatchedRequests()) {
console.log(`${entry.method} ${entry.host}${entry.path}: ${entry.reason} (x${entry.count})`);
}
// GET api.example.com/v3/pet/1: no_matching_path (x1)
// PATCH api.example.com/api/v3/pet/{petId}: method_not_documented (x1)
unmatchedOverflow
unmatchedOverflow()
Requests dropped after the distinct-group cap was reached. Non-zero means
unmatchedRequests() is truncated.
Returns: number
droppedRequests
droppedRequests()
Requests discarded before matching could be attempted — an unparsable URL or an HTTP
method TraceCov does not model. Non-zero with an empty unmatchedRequests() explains
zero coverage.
Returns: number
exportCounts
exportCounts()
Everything this map recorded, as opaque bytes for mergeCounts() on a map of the same
specification in another process. The Vitest integration uses it to collect coverage from
its workers.
Returns: Buffer
mergeCounts
mergeCounts(counts)
Add counts that exportCounts() returned for a map of the same specification, as if this map
had recorded their traffic too.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts |
Buffer |
What exportCounts() returned |
required |
Throws: when counts is malformed or does not fit this map's specification. Counts from
another specification of the same shape are not detected.
checkThresholds
checkThresholds(options?)
Check whether coverage meets minimum thresholds. Returns an empty array when all thresholds are met.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
options |
CheckThresholdsOptions | null |
Minimum coverage percentages (0–100) | null |
Returns: ThresholdViolation[]. Dimensions with no data (total of 0) are skipped.
Example
const coverage = CoverageMap.fromPath('openapi.json');
const violations = coverage.checkThresholds({ operations: 80, keywords: 50 });
if (violations.length > 0) {
for (const v of violations) {
console.error(`${v.dimension}: ${v.actual.toFixed(1)}% < ${v.minimum}%`);
}
process.exit(1);
}
// Operations: 5.3% < 80%
// Keywords: 0.3% < 50%
operationReport
operationReport(method, path)
Return the per-operation coverage report for a single operation, or null if the spec has no such operation. path is the templated path as reports show it, including the base path (/api/v3/pet/{petId}), not a concrete URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method |
string |
HTTP method | required |
path |
string |
Templated spec path | required |
Returns: OperationReport | null
Example
const coverage = CoverageMap.fromPath('openapi.json');
const op = coverage.operationReport('GET', '/api/v3/pet/findByStatus');
if (op) {
console.log(`${op.method} ${op.path}: ${op.hits} hits, ${op.coverage.keywords.percent}% keywords`);
}
// GET /api/v3/pet/findByStatus: 1 hits, 50% keywords
operationReports
operationReports()
Return the per-operation coverage report for every operation in the spec.
Returns: OperationReport[]
Example
const coverage = CoverageMap.fromPath('openapi.json');
for (const op of coverage.operationReports()) {
console.log(`${op.method} ${op.path}: ${op.coverage.responses.percent}% responses`);
}
// POST /api/v3/pet: 0% responses
// PUT /api/v3/pet: 0% responses
// ...
buildJsonReport
buildJsonReport()
Return the full coverage report as a structured object — the same data as generateJsonReport(), but as a typed value instead of a JSON string. See JSON Report Format for the field-by-field schema.
Returns: JsonReport
Example
const coverage = CoverageMap.fromPath('openapi.json');
const report = coverage.buildJsonReport();
const percent = report.summary.operations.percent; // null when the spec has no operations
if (percent !== null && percent < 80) {
process.exit(1);
}
recordFromHar
recordFromHar(archive)
Not available in @tracecov/core
The published package is the Community edition, where this method always throws HAR import requires TraceCov Professional. See https://docs.tracecov.sh/editions/. The Professional CLI imports this format.
Import traffic from a parsed HAR archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
archive |
object |
Parsed HAR archive (v1.2 or v1.3) | required |
Returns: void
Example
import fs from 'node:fs';
const coverage = CoverageMap.fromPath('openapi.json');
const archive = JSON.parse(fs.readFileSync('traffic.har', 'utf-8'));
coverage.recordFromHar(archive);
recordFromPostman
recordFromPostman(collection)
Not available in @tracecov/core
The published package is the Community edition, where this method always throws Postman Collection import requires TraceCov Professional. See https://docs.tracecov.sh/editions/. The Professional CLI imports this format.
Import traffic from a parsed Postman Collection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
collection |
object |
Parsed Postman Collection (v1.0, v2.0, or v2.1) | required |
Returns: void
Example
import fs from 'node:fs';
const coverage = CoverageMap.fromPath('openapi.json');
const collection = JSON.parse(fs.readFileSync('collection.json', 'utf-8'));
coverage.recordFromPostman(collection);
recordFromVcr
recordFromVcr(cassette)
Not available in @tracecov/core
The published package is the Community edition, where this method always throws VCR cassette import requires TraceCov Professional. See https://docs.tracecov.sh/editions/. The Professional CLI imports this format.
Import traffic from a parsed VCR cassette.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cassette |
object |
Parsed VCR cassette (Ruby VCR or Schemathesis format) | required |
Returns: void
Example
import fs from 'node:fs';
const coverage = CoverageMap.fromPath('openapi.json');
const cassette = JSON.parse(fs.readFileSync('cassette.json', 'utf-8'));
coverage.recordFromVcr(cassette);
Types
HttpRequest
HttpRequest
HTTP request for coverage tracking.
| Field | Type | Required | Description |
|---|---|---|---|
method |
string |
yes | HTTP method (GET, POST, etc.) |
url |
string |
yes | Full URL including query parameters |
body |
Buffer | undefined |
no | Request body as Buffer or Uint8Array; a string throws, so pass Buffer.from(text) |
headers |
Record<string, string> | undefined |
no | Request headers |
HttpResponse
HttpResponse
HTTP response for coverage tracking.
| Field | Type | Required | Description |
|---|---|---|---|
statusCode |
number |
yes | HTTP status code |
elapsed |
number | undefined |
no | Response time in seconds (float); defaults to 0 when omitted |
body |
Buffer | undefined |
no | Response body as Buffer or Uint8Array; a string throws |
headers |
Record<string, string> | undefined |
no | Response headers |
Response keyword coverage is measured only when both body and a content-type header are present.
CoverageStatistic
CoverageStatistic
Aggregate coverage statistics returned by statistic().
| Field | Type |
|---|---|
operations |
SeenStatistic |
parameters |
ValidityStatistic |
keywords |
ValidityStatistic |
examples |
SeenStatistic |
responses |
ResponseStatistic |
responseKeywords |
ResponseKeywordStatistic |
SeenStatistic: { seen: number, total: number }
ValidityStatistic: { positive: number, negative: number, partial: number, full: number, total: number }
ResponseStatistic: { seen: number, total: number, elapsedTotalSeconds: number }
ResponseKeywordStatistic: { reached: number, violated: number, total: number }. reached counts response-schema keywords that a recorded response body exercised; violated counts those a response body failed.
UncoveredKeyword
UncoveredKeyword
A JSON Schema keyword without full coverage, as returned by uncoveredKeywords().
| Field | Type | Description |
|---|---|---|
method |
string |
HTTP method |
path |
string |
API path |
location |
string |
Parameter location (query, querystring, header, path, cookie, body, form_data) |
parameter |
string |
Parameter name |
schemaPath |
string |
JSON pointer to the keyword in the schema |
state |
string |
What is missing: "miss" (no coverage), "needs_invalid" (only valid values seen), or "needs_valid" (only invalid values seen) |
satisfiability |
string |
"Normal", "Positive", or "Negative" |
ThresholdViolation
ThresholdViolation
A coverage dimension that did not meet its minimum threshold, as returned by checkThresholds().
| Field | Type | Description |
|---|---|---|
dimension |
CoverageMetric |
The coverage dimension |
actual |
number |
Actual coverage percentage (0–100) |
minimum |
number |
Required minimum percentage (0–100) |
CoverageMetric
CoverageMetric
String enum identifying a coverage dimension.
Values: 'Operations' · 'Parameters' · 'Keywords' · 'Examples' · 'Responses' · 'ResponseKeywords'
CoverageGap
CoverageGap
A single actionable coverage gap returned by coverageGaps(). A discriminated union on kind; every variant carries method and path.
kind |
Extra fields |
|---|---|
"operation_unseen" |
— |
"response_uncovered" |
status_code: string |
"parameter_uncovered" |
location: string, parameter: string |
"keyword_miss" / "keyword_needs_valid" / "keyword_needs_invalid" |
location, parameter, schema_path, satisfiability: "Normal" | "Positive" | "Negative" |
"example_unseen" |
location: string, parameter: string |
Importable: import type { CoverageGap } from '@tracecov/core'.
OperationReport / JsonReport
OperationReport · JsonReport
Typed shapes returned by operationReport(s) and buildJsonReport(). Keys are snake_case. The field-by-field schema is documented in JSON Report Format.
Every coverage percent is typed number | null: it is null when there is nothing to cover (total is 0). Check for null before comparing it.
Importable: import type { JsonReport, OperationReport } from '@tracecov/core'.
UnmatchedRequest
UnmatchedRequest
A group of requests that matched no documented operation, as returned by unmatchedRequests().
| Field | Type | Description |
|---|---|---|
method |
string |
HTTP method |
host |
string |
Request host, including the port when present |
path |
string |
The observed request path; the spec's path template when reason is "method_not_documented" |
reason |
"no_matching_path" | "method_not_documented" |
"no_matching_path": no spec path matches. "method_not_documented": the path matches but the operation lacks this method |
count |
number |
Number of requests in the group |
first_seen_at |
number |
Unix timestamp in seconds of the first request in the group |
Importable: import type { UnmatchedRequest } from '@tracecov/core'.
SchemaError
SchemaError
A schema-collection error returned by errors().
| Field | Type | Description |
|---|---|---|
method |
string \| undefined |
HTTP method of the operation the error belongs to; absent when the error belongs to the path item (an additionalOperations key naming no known method) |
path |
string |
Templated spec path |
message |
string |
Human-readable description, such as Field `schema` is missing |
Option Types
FromDictOptions
| Field | Type | Description | Default |
|---|---|---|---|
basePath |
string | undefined |
Base path prefix for all operations | Path of servers[0].url (OpenAPI 3) or basePath (Swagger 2.0) |
location |
string | undefined |
File path or URL shown in error messages | undefined |
FromPathOptions
| Field | Type | Description | Default |
|---|---|---|---|
basePath |
string | undefined |
Base path prefix for all operations | Path of servers[0].url (OpenAPI 3) or basePath (Swagger 2.0) |
HtmlReportOptions
| Field | Type | Description | Default |
|---|---|---|---|
title |
string | undefined |
Custom title for the HTML report | "TraceCov Report" |
MarkdownReportOptions
| Field | Type | Description | Default |
|---|---|---|---|
reportUrl |
string | undefined |
Link to full HTML report | undefined |
weakThreshold |
number | undefined |
Parameter coverage ratio (0–1) below which an operation is marked ⚠ | 1.0 |
isPullRequest |
boolean | undefined |
Compact PR-optimised format | false |
subText |
string | undefined |
Footer text | undefined |
columns |
string[] | undefined |
Columns to include | all |
TextReportOptions
| Field | Type | Description | Default |
|---|---|---|---|
width |
number | undefined |
Terminal width | 120 |
colored |
boolean | undefined |
ANSI colors | true |
skipCovered |
boolean | undefined |
Hide fully covered items | false |
skipEmpty |
boolean | undefined |
Hide items with no traffic | false |
showMissing |
string[] | undefined |
Uncovered items to list after the table; only "parameter" is accepted |
undefined |
SaveHtmlOptions
| Field | Type | Description | Default |
|---|---|---|---|
outputFile |
string | undefined |
Output path | "tracecov.html" |
title |
string | undefined |
Custom report title | "TraceCov Report" |
SaveJsonOptions
| Field | Type | Description | Default |
|---|---|---|---|
outputFile |
string | undefined |
Output path | "tracecov.json" |
SaveMarkdownOptions
| Field | Type | Description | Default |
|---|---|---|---|
outputFile |
string | undefined |
Output path | "tracecov.md" |
reportUrl |
string | undefined |
Link to full HTML report | undefined |
weakThreshold |
number | undefined |
Parameter coverage ratio (0–1) below which an operation is marked ⚠ | 1.0 |
isPullRequest |
boolean | undefined |
Compact PR-optimised format | false |
subText |
string | undefined |
Footer text | undefined |
columns |
string[] | undefined |
Columns to include | all |
CheckThresholdsOptions
| Field | Type | Description | Default |
|---|---|---|---|
operations |
number | undefined |
Minimum operations coverage (0–100) | undefined |
parameters |
number | undefined |
Minimum parameters coverage (0–100) | undefined |
keywords |
number | undefined |
Minimum keywords coverage (0–100) | undefined |
examples |
number | undefined |
Minimum examples coverage (0–100) | undefined |
responses |
number | undefined |
Minimum responses coverage (0–100) | undefined |
responseKeywords |
number | undefined |
Minimum response keywords coverage (0–100) | undefined |