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()); // e.g. "0.22.0"
edition
edition()
Returns the build edition: "community" or "professional". HAR and Postman import require the professional edition.
Returns: string
Example
import { edition } from '@tracecov/core';
console.log(edition()); // e.g. "community"
CoverageMap
CoverageMap
Tracks API test coverage against an OpenAPI specification.
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
coverage.record(
{
method: 'GET',
url: 'https://api.example.com/users/1',
headers: { authorization: 'Bearer token' },
},
{ statusCode: 200, elapsed: 0.42 },
);
recordError
recordError(method, url, message)
Annotate the operation matching url with a request-level error (e.g. 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
coverage.recordError('GET', 'https://api.example.com/users/1', 'ECONNREFUSED');
statistic
statistic()
Get aggregate coverage statistics.
Returns: CoverageStatistic
Example
const stats = coverage.statistic();
console.log(`Operations: ${stats.operations.seen}/${stats.operations.total}`);
console.log(`Keywords: ${stats.keywords.full}/${stats.keywords.total} 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 problems = coverage.errors();
if (problems.length > 0) {
for (const e of problems) {
console.warn(`${e.method} ${e.path}: ${e.message}`);
}
}
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 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 data = JSON.parse(coverage.generateJsonReport());
if (data.summary.operations.percent < 80) {
throw new Error('Coverage below threshold');
}
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
// 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 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
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
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
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
for (const kw of coverage.uncoveredKeywords()) {
console.log(`${kw.method} ${kw.path} ${kw.parameter}: needs ${kw.state}`);
}
coverageGaps
coverageGaps()
Return every actionable coverage gap — uncovered operations, responses, parameters, examples, and keywords — as a typed discriminated union on kind.
Returns: CoverageGap[]
Example
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}`);
}
}
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 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);
}
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 spec path (e.g. /pets/{id}), 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 op = coverage.operationReport('GET', '/pets/{id}');
if (op) {
console.log(`${op.method} ${op.path}: ${op.hits} hits, ${op.coverage.keywords.percent}% keywords`);
}
operationReports
operationReports()
Return the per-operation coverage report for every operation in the spec.
Returns: OperationReport[]
Example
for (const op of coverage.operationReports()) {
console.log(`${op.method} ${op.path}: ${op.coverage.responses.percent}% 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 report = coverage.buildJsonReport();
if (report.summary.operations.percent < 80) {
process.exit(1);
}
recordFromHar
recordFromHar(archive)
Professional Edition
This method requires TraceCov Professional.
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 archive = JSON.parse(fs.readFileSync('traffic.har', 'utf-8'));
coverage.recordFromHar(archive);
recordFromPostman
recordFromPostman(collection)
Professional Edition
This method requires TraceCov Professional.
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 collection = JSON.parse(fs.readFileSync('collection.json', 'utf-8'));
coverage.recordFromPostman(collection);
recordFromVcr
recordFromVcr(cassette)
Professional Edition
This method requires TraceCov Professional.
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 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 (accepts Buffer or Uint8Array) |
headers |
Record<string, string> | undefined |
no | Request headers |
HttpResponse
HttpResponse
HTTP response for coverage tracking.
| Field | Type | Description |
|---|---|---|
statusCode |
number |
HTTP status code |
elapsed |
number | undefined |
Response time in seconds (float); defaults to 0 when omitted |
CoverageStatistic
CoverageStatistic
Aggregate coverage statistics returned by statistic().
| Field | Type |
|---|---|
operations |
SeenStatistic |
parameters |
ValidityStatistic |
keywords |
ValidityStatistic |
examples |
SeenStatistic |
responses |
ResponseStatistic |
SeenStatistic: { seen: number, total: number }
ValidityStatistic: { positive: number, negative: number, partial: number, full: number, total: number }
ResponseStatistic: { seen: number, total: number, elapsedTotalSeconds: number }
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, header, path, cookie, body) |
parameter |
string |
Parameter name |
schemaPath |
string |
JSON pointer to the keyword in the schema |
state |
string |
Missing coverage type: "valid" or "invalid" |
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'
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.
Importable: import type { JsonReport, OperationReport } from '@tracecov/core'.
SchemaError
SchemaError
A schema-collection error returned by errors().
| Field | Type | Description |
|---|---|---|
method |
string |
HTTP method of the operation the error belongs to |
path |
string |
Templated spec path |
message |
string |
Human-readable description (e.g. Field \schema` is missing`) |
Option Types
FromDictOptions
| Field | Type | Description | Default |
|---|---|---|---|
basePath |
string | undefined |
Base path prefix for all operations | undefined |
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 | undefined |
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 |
Ratio below which to show ⚠ | undefined |
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 |
Items to show in missing column | 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 |
Ratio below which to show ⚠ | undefined |
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 |