cognitive-typescript is a shared Cognitive Complexity toolkit for TypeScript projects.
It performs pure static analysis using the Sonar Cognitive Complexity white paper as the metric source of truth, reports the worst function-like bodies first, and fails when any analyzed function exceeds the configured threshold.
packages/core: analysis engine, parser, recursion handling, CLI orchestration, and report formattingpackages/cli: executablecognitive-typescriptpackagepackages/vitest: Vitest helper and reporter wrapperpackages/jest: Jest helper and reporter wrapper
- The implementation follows the SonarSource Cognitive Complexity white paper.
- It is pure static analysis.
- It does not execute tests, enable coverage, consume Istanbul or LCOV reports, or compute CRAP scores.
- The default threshold is
8, and the CLI and reporter integrations can override it.
Official support covers maintained Node.js LTS lines and released lines officially scheduled to become LTS.
Node 22, 24, and 26 are maintained LTS lines, fully supported on Windows, macOS, and Linux.
Published packages retain the installation floor >=22.13.0.
Source builds require Node ^22.22.2 || ^24.15.0 || >=26.0.0 and npm 12.2.2.
Required CI builds, tests, and runs isolated packaged consumers on Node 22.23.5, 24.22.3, and 26.13.1
across all three operating systems. Separate consumer checks verify Node 22.13.0, 24.0.0, and 26.0.0.
See the dated runtime and dependency baseline for compatibility decisions.
Locally, run:
npm ci
npm run build
npm run lint
npm run format:check
npm test
npm run cognitive-typescript-check
npm run crap-typescript-check
npm pack --workspacesnpm run cognitive-typescript-check runs the repository through its own Cognitive Complexity gate for the published package sources under packages/.
npm run crap-typescript-check runs the repository through a CRAP gate using the published Vitest adapter for the package sources under packages/.
npm run lint enforces the repository ESLint baseline.
npm run format:check verifies the Prettier-managed source and configuration surface, and npm run format:write updates it locally.
CLI:
npm install --save-dev @barney-media/cognitive-typescriptVitest adapter:
npm install --save-dev @barney-media/cognitive-typescript-vitest vitest viteJest adapter:
npm install --save-dev @barney-media/cognitive-typescript-jest jestFrom the project root you want to analyze:
npx cognitive-typescriptChanged files only:
npx cognitive-typescript --changedExplicit files or directories:
npx cognitive-typescript src/server.ts packages/web--help Print usage to stdout
(no args) Analyze all TypeScript files under any nested src/ tree
--changed Analyze changed TypeScript files under src/
<file ...> Analyze explicit TypeScript files
<directory ...> Analyze TypeScript files under each directory's nested src/ tree
--format <format> Emit toon, json, text, junit, or none (default: toon)
--exclude <glob> Exclude normalized project-relative paths from analysis (repeatable)
--exclude-name <regex> Exclude matching function or method names from analysis (repeatable)
--exclude-decorator <name> Exclude matching decorators by simple or dotted source name (repeatable)
--exclude-comment <marker> Exclude generated code with leading file/function comment markers (repeatable)
--use-default-exclusions Enable conservative generated-code exclusions (default: true)
--failures-only[=true|false] Emit failed functions 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 <integer> Override the Cognitive Complexity threshold (default: 8)
--agent Compact the primary report to actionable failures by default
Useful combinations:
# Compact actionable failures to stdout
npx cognitive-typescript --agent
# JSON primary report plus full JUnit sidecar
npx cognitive-typescript --format json --output reports/cognitive.json --junit-report reports/cognitive-junit.xml
# Generated-code exclusions plus a custom decorator exclusion
npx cognitive-typescript --exclude "packages/generated/**" --exclude-decorator Generatedimport { analyzeProject, formatAnalysisReport } from "@barney-media/cognitive-typescript-core";
const result = await analyzeProject({
projectRoot: process.cwd(),
changedOnly: true,
excludes: ["packages/generated/**"],
excludeDecorators: ["Generated"],
threshold: 12
});
const primary = formatAnalysisReport(result.metrics, {
format: "json",
threshold: result.threshold,
exclusionAudit: result.exclusionAudit
});
console.log(result.thresholdExceeded);
console.log(primary);Common analyzeProject(...) options include:
projectRootexplicitPathschangedOnlyexcludesexcludeNamesexcludeDecoratorsexcludeCommentsuseDefaultExclusionsthreshold
Primary-report formatting and filtering controls such as format, failuresOnly, and omitRedundancy belong to formatAnalysisReport(...) or the report-publishing layer, not to analyzeProject(...).
AnalysisResult returns:
metricsmaxCognitiveComplexitythresholdthresholdExceededselectedFilesexclusionAuditwarnings
Both reporter integrations stay in the static-analysis lane. They run after the test framework finishes, analyze the selected TypeScript sources, and then decide whether to fail the process based on Cognitive Complexity alone.
The Vitest adapter supports Vitest 4 and 5; the Jest adapter supports Jest 30. Install the host runner
in the consumer project. Vite is a required Vitest peer; install it explicitly, particularly with Yarn.
Coverage is optional and does not affect Cognitive Complexity analysis. If enabling V8 coverage,
install @vitest/coverage-v8 at the exact same version as Vitest.
Vitest:
import { defineConfig } from "vitest/config";
import { withCognitiveTypescriptVitest } from "@barney-media/cognitive-typescript-vitest";
export default withCognitiveTypescriptVitest(
defineConfig({
test: {
include: ["test/**/*.test.ts"]
}
}),
{
changedOnly: true,
excludes: ["packages/generated/**"],
format: "text",
output: "reports/cognitive.txt",
junitReport: "reports/cognitive-junit.xml",
threshold: 12
}
);Jest:
const { withCognitiveTypescriptJest } = require("@barney-media/cognitive-typescript-jest");
module.exports = withCognitiveTypescriptJest(
{
testEnvironment: "node"
},
{
paths: ["packages/core", "packages/cli"],
excludeComments: ["@generated"],
agent: true
}
);Reporter options support:
projectRootpathschangedOnlyexcludesexcludeNamesexcludeDecoratorsexcludeCommentsuseDefaultExclusionsformatagentfailuresOnlyomitRedundancyoutputjunitjunitReportthreshold
Reporter defaults differ from the CLI in two important ways:
- the default primary format is
none, so reporters stay quiet unless you opt into primary output oragent - the default JUnit sidecar path is
reports/cognitive-typescript/TEST-cognitive-typescript.xml
Set junit: false to disable the sidecar entirely.
toon: compact line-oriented output withstatus,threshold, method rows, and optional exclusion countsjson: structured primary report for automation and scriptingtext: human-readable table outputjunit: full XML report intended for CI test-report UIsnone: suppress the primary report entirely
--agent keeps the primary report compact by default by applying:
--format toon--failures-only=true--omit-redundancy=true
Default exclusions stay conservative and generated-code focused:
- declaration files:
*.d.ts,*.d.mts,*.d.cts - generated file names:
*.generated.ts,*.generated.tsx,*.gen.ts,*.gen.tsx - generated or build directories:
generated,__generated__,dist,build,out,coverage,node_modules,target,.next,.nuxt,.svelte-kit - existing test-file defaults such as
__tests__/,*.test.*, and*.spec.* - leading generated-code markers:
@generated,<auto-generated
User-provided exclusions compose with these defaults unless --use-default-exclusions=false.
Exclusions are applied before threshold evaluation. Full primary reports and JUnit sidecars can publish exclusion audit counts; compact agent primary output omits that detail by default.
(no args)analyzes TypeScript files under nestedsrc/trees- explicit files stay explicit
- explicit directories expand to TypeScript files under their nested
src/trees --changeduses Git status output and refuses incomplete changed-file detection instead of silently analyzing a partial set- default generated/build-output directories are pruned during source-root discovery when default exclusions are enabled
- Primary reports describe the selected functions only.
- Full primary reports and JUnit sidecars include exclusion audit counts.
- JUnit testcases include GitLab-visible metric details in
nameasmethod:lineStart [CC=complexity]and in testcase-levelsystem-out. - Compact agent primary reports stay focused on actionable failures and omit exclusion audit detail by default.
- Excluded files and functions are removed before report generation and threshold evaluation.
Report path validation is strict:
--outputand--junit-reportmust stay inside the project root- they must point to files, not the filesystem root, the project root, or an existing directory
- they must not collide with each other, including case-insensitive collisions on Windows and macOS
0success, threshold respected1invalid CLI usage or execution failure2Cognitive Complexity threshold exceeded (> threshold)3unexpected internal error
Verified and unverified syntax shapes are tracked in docs/compatibility-matrix.md. The matrix is backed by fixtures under tests/fixtures/compatibility-matrix/.
Cognitive Complexity scoring for &&, ||, ??, optional chaining, logical assignment, and JSX short-circuit rendering is documented in docs/operator-semantics.md.
A reviewed version-bump PR merged into protected main publishes all four packages automatically.
Ordinary merges are a successful no-op. Releases include the exact npm archives, four CycloneDX SBOMs,
SHA-256 checksums, and keyless Sigstore provenance and SBOM attestation bundles.
Publishing retains the existing npm Trusted Publisher identity: fabian-barney/cognitive-typescript,
workflow release.yml, with no publishing environment or token. Git tags are unsigned annotated tags;
artifact signatures bind the released bytes to the source commit and GitHub workflow.
See RELEASING.md for preparation, consumer verification commands, and failure recovery.
See CONTRIBUTING.md for the issue-linked branch, commit, and pull-request flow.