← Back to DAGDA | Support | Source: https://github.com/fabian-barney/crap-typescript
Skip to content

About

CRAP metrics for TypeScript

Resources

Contributing

Security policy

Stars

30 stars

Watchers

0 watching

Forks

Repository files navigation

crap-typescript

crap-typescript is a shared CRAP metric toolkit for TypeScript projects.

Version 2.0.0 adopts TOON 4.4 serialization and supports Node.js 22/24/26 and Vitest 4/5. The core, CLI, Vitest, and Jest APIs follow Semantic Versioning.

It combines cyclomatic complexity with function-level coverage derived from Istanbul statement and branch counters and reports CRAP scores for concrete TypeScript function bodies. The repository publishes a standalone CLI plus dedicated Vitest and Jest adapters.

Modules

  • packages/core: analysis engine, CLI orchestration, coverage detection, and report formatting
  • packages/cli: executable crap-typescript package
  • packages/vitest: helper that enables the canonical Istanbul JSON coverage output and fails Vitest runs when the CRAP threshold is exceeded
  • packages/jest: helper and reporter for Jest runs

Runtime and Toolchain Support

Node.js 22, 24, and 26 are fully supported on Windows, macOS, and Linux. The policy covers maintained LTS lines and released lines with an official scheduled LTS transition. Node 26 entered LTS on 2026-10-28. Use current security patches within each line. Published packages retain their Node.js >=22.13.0 requirement.

Building this repository requires npm 12.2.2 and Node.js ^22.22.2 || ^24.15.0 || >=26.0.0. CI uses Node 22.23.5, 24.22.3, and 26.13.1, with separate checks at the published runtime minimums. The Vitest adapter supports Vitest 4 and 5; the Jest adapter supports Jest 30.

See the dependency baseline for tested versions, TypeScript 7 deferral, TOON migration notes for version 2.0, and dependency audit and license details.

Formula

CRAP = CC^2 * (1 - coverage)^3 + CC

  • CC is cyclomatic complexity.
  • coverage is defined separately as the minimum of the function's statement coverage and branch coverage.
  • Structural non-applicability is treated as 100% for the affected component metric only when the analyzer can prove it.
  • Unknown coverage remains N/A, and CRAP remains N/A for that function.

Coverage Pipeline

For each resolved module today:

  1. Detect the nearest module root by walking up to the closest package.json.
  2. Reuse coverage/coverage-final.json when it already exists.
  3. Otherwise auto-detect the package manager and test runner unless the CLI forces them.
  4. Run the module tests with JSON coverage enabled.
  5. Read coverage/coverage-final.json from the module root, falling back to the project root for workspace coverage.
  6. Use Istanbul fnMap as a validation and secondary matching aid when it is present.
  7. Derive function statement and branch coverage from the Istanbul coverage counters and use their minimum as CRAP coverage.

Commands run by the built-in executor, including coverage commands and changed-file discovery, time out after 300 seconds by default. Set CRAP_TYPESCRIPT_COMMAND_TIMEOUT_MS to a non-negative millisecond value to override this default; 0 disables the timeout. Captured stdout and stderr are capped at 10 MiB per stream. User-facing command failures may include truncated output, while internal commands that require complete output, such as git status --porcelain -z, fail if the cap is exceeded.

Compatibility Matrix

Verified and unverified coverage-attribution shapes are tracked in docs/compatibility-matrix.md. The matrix is backed by golden fixtures under tests/fixtures/compatibility-matrix/.

Build and Test

npm ci
npm run build
npm test
npm run crap-typescript-check
npm pack --workspaces

npm run crap-typescript-check runs the repository through its own CRAP threshold gate for the published package sources under packages/.

Install

CLI:

npm install --save-dev @barney-media/crap-typescript

Vitest adapter:

npm install --save-dev @barney-media/crap-typescript-vitest vitest@5.1.0 @vitest/coverage-v8@5.1.0 vite@^8.3.8

Jest adapter:

npm install --save-dev @barney-media/crap-typescript-jest jest

Run

From the project root you want to analyze:

npx crap-typescript

CLI

--help                       Print usage to stdout
(no args)                    Analyze all TypeScript files under any nested src/ tree
--changed                    Analyze changed TypeScript files under src/
--exclude <glob>             Exclude source paths by normalized relative glob; repeatable
--exclude-path-regex <regex> Exclude source paths by normalized relative regex; repeatable
--exclude-generated-marker <marker> Exclude leading generated-header markers; repeatable
--use-default-exclusions[=true|false] Enable generated-code defaults (`true` by default)
--package-manager <tool>     Force auto, npm, pnpm, yarn, or bun
--test-runner <runner>       Force auto, vitest, or jest
--format <format>            Emit toon, json, text, junit, or none (default: toon)
--agent                      Default primary output to toon, failures-only, omit-redundancy
--failures-only[=true|false] Emit failed methods only in the primary report
--omit-redundancy[=true|false] Omit redundant per-method status in the primary report
--output <path>              Write the primary report to a file instead of stdout
--junit-report <path>        Also write a full JUnit XML report for CI test-report UIs
--threshold <number>         Override the CRAP threshold (`6.0` by default)
<file ...>                   Analyze explicit TypeScript files
<directory ...>              Analyze TypeScript files under each directory's nested src/ tree

Examples:

npx crap-typescript --help
npx crap-typescript
npx crap-typescript --changed
npx crap-typescript --package-manager npm --test-runner vitest
npx crap-typescript --format json --output reports/crap.json
npx crap-typescript --failures-only --format json
npx crap-typescript --omit-redundancy --format toon
npx crap-typescript --agent --junit-report reports/crap-junit.xml
npx crap-typescript --threshold 6
npx crap-typescript --exclude 'packages/api/generated/**'
npx crap-typescript --exclude-path-regex '^src/proto/'
npx crap-typescript --exclude-generated-marker '@custom-generated'
npx crap-typescript --use-default-exclusions=false
npx crap-typescript src/sample.ts
npx crap-typescript packages/api packages/web

Source Selection And Exclusions

The baseline analyzability filter always skips declaration files, test/spec files, files under __tests__/, and files under dist/, coverage/, and node_modules/. The generated-code exclusion layer runs after CLI paths, --changed, or adapter paths choose the candidate source set. Disabling generated-code defaults with useDefaultExclusions: false does not disable those baseline analyzability exclusions.

Default generated-code path exclusions are conservative:

  • any source file below a directory segment containing generated
  • any source file below a directory segment exactly named gen
  • **/*.generated.ts, **/*.generated.tsx, **/*.gen.ts, **/*.gen.tsx
  • **/*Generated.ts, **/*Generated.tsx
  • **/*_pb.ts, **/*_grpc_pb.ts, **/*.pb.ts
  • **/*.ngfactory.ts, **/*.ngsummary.ts, **/*.ngtypecheck.ts

Default generated-header markers are matched only in leading comments before the first non-comment source token: @generated, @auto-generated, AUTO-GENERATED, This file was generated, This file is generated, Do not edit, and DO NOT EDIT. eslint-disable and tslint:disable are not generated markers by themselves.

Use --exclude <glob> for package/path/file globs such as packages/api/**, --exclude-path-regex <regex> for normalized relative source-path regexes, and --exclude-generated-marker <marker> for project-specific generated headers. Core, Vitest, and Jest expose the same controls as excludes, excludePathRegexes, excludeGeneratedMarkers, and useDefaultExclusions.

Full primary reports and JUnit sidecars include source-exclusion audit counts when files were excluded. Optimized primary reports from default --agent mode stay compact and omit that audit; use a full primary report or the JUnit sidecar when agent workflows need exclusion visibility.

Report Formats

The CLI defaults to TOON output for compact, agent-readable reports. --format can select toon, json, text, junit, or none. --format none suppresses primary stdout output; when used with --output, it creates an empty primary report file.

Primary reports expose overall status and the run-level threshold. Method entries use the shared fields status, crap, cc, cov, covKind, method, src, lineStart, and lineEnd. src is the project-relative source file path. Method-level entries never repeat threshold.

Use --failures-only to keep run-level metadata but emit only failed method entries in the primary report. --failures-only=true and --failures-only=false are accepted for explicit boolean configuration.

Use --omit-redundancy to keep run-level metadata but omit per-method status in the primary report. With --format junit, it omits the custom testcase status property while preserving JUnit failure and skipped elements. The value can also be assigned explicitly with --omit-redundancy=true or --omit-redundancy=false.

--agent is a composite shortcut, not a report format. It defaults primary output to --format toon, --failures-only=true, and --omit-redundancy=true. Explicit --format, --failures-only=false, or --omit-redundancy=false options override those defaults.

Use --junit-report <path> to write a full JUnit XML artifact alongside the primary report. JUnit sidecars always contain the full method set, regardless of --agent, --failures-only, or --omit-redundancy. JUnit output is shaped for GitLab's Tests tab: it wraps the suite in <testsuites>, sets testcase classname and file to src, sets testcase name to method:lineStart [CRAP=score, CC=complexity, Cov=percent (kind)], writes time="0", and includes CRAP score, threshold, coverage kind, source path, and line range in testcase-level system-out and failure or skipped element content. Custom properties remain for CI tools that read them, but GitLab-visible details do not rely on properties.

The default threshold is 6.0. Values below 4.0 print a warning because they are likely too noisy; values above 8.0 print a warning because they are too lenient even for hard gates. The warning recommends 8.0 for hard gates, targeting 6.0 during implementation, and using the 6.0 default when in doubt.

Adapter Usage

Vitest:

import { withCrapTypescriptVitest } from "@barney-media/crap-typescript-vitest";

export default withCrapTypescriptVitest({
  test: {
    include: ["test/**/*.test.ts"]
  }
});

The Vitest adapter defaults primary format to none, so it emits no primary stdout report unless configured. It enables junit by default and writes a full sidecar for CI test-report UIs. With the default coverage report path, the sidecar is coverage/crap-typescript-junit.xml; custom coverage paths derive a matching sidecar path. Pass format, agent, failuresOnly, omitRedundancy, output, junit, junitReport, threshold, excludes, excludePathRegexes, excludeGeneratedMarkers, or useDefaultExclusions in the adapter options to customize analysis and reporting. Set junit: false to disable the JUnit artifact. JUnit sidecars are full reports and are not affected by agent, failuresOnly, or omitRedundancy.

When test.reporters is omitted, the Vitest adapter keeps the default reporter and adds the CRAP reporter. An explicit reporter value or array replaces that default; the adapter preserves the configured entries and adds only the CRAP reporter. Similarly, an omitted coverage.reporter defaults to json and text, while an explicit value is preserved and augmented only with the required json reporter when needed. Use empty reporter arrays to keep only the CRAP and JSON reporters and suppress Vitest's test and coverage terminal reports.

Jest:

import { withCrapTypescriptJest } from "@barney-media/crap-typescript-jest";

export default withCrapTypescriptJest({
  testEnvironment: "node"
});

The Jest adapter defaults primary format to none, so it emits no primary stdout report unless configured. It enables junit by default and writes a full sidecar for CI test-report UIs. With the default coverage report path, the sidecar is coverage/crap-typescript-junit.xml; custom coverage paths derive a matching sidecar path. Pass format, agent, failuresOnly, omitRedundancy, output, junit, junitReport, threshold, coverageReportWaitMs, excludes, excludePathRegexes, excludeGeneratedMarkers, or useDefaultExclusions in the adapter options to customize analysis and reporting. The Jest reporter waits up to 5000ms for the coverage JSON after Jest finishes; set coverageReportWaitMs to a non-negative millisecond value to override it. Set junit: false to disable the JUnit artifact. JUnit sidecars are full reports and are not affected by agent, failuresOnly, or omitRedundancy.

Exit Codes

  • 0 success, threshold respected
  • 1 invalid CLI usage or execution failure
  • 2 CRAP threshold exceeded (> configured threshold)

Release

Merge a reviewed version-bump PR into main to release automatically after the exact commit passes all CI gates. Ordinary merges do not publish. Releases include the four npm archives, CycloneDX SBOMs, SHA-256 checksums, and keyless provenance and SBOM attestations. See RELEASING.md for preparation, verification, trusted-publisher configuration, and failure recovery.

Contributing

See CONTRIBUTING.md for the issue-linked branch, commit, and pull-request flow used in this repository.

About

CRAP metrics for TypeScript

Resources

Contributing

Security policy

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages