@swayamkothari/codepulse 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +240 -2
  2. package/bin/codepulse.js +6 -0
  3. package/package.json +60 -4
  4. package/src/analyzers/complexity/cognitive.js +170 -0
  5. package/src/analyzers/complexity/cyclomatic.js +96 -0
  6. package/src/analyzers/complexity/index.js +232 -0
  7. package/src/analyzers/dependencies/cycle-detector.js +107 -0
  8. package/src/analyzers/dependencies/graph-builder.js +118 -0
  9. package/src/analyzers/dependencies/import-extractor.js +85 -0
  10. package/src/analyzers/dependencies/index.js +152 -0
  11. package/src/analyzers/duplication/index.js +366 -0
  12. package/src/analyzers/duplication/normalizer.js +238 -0
  13. package/src/analyzers/index.js +9 -0
  14. package/src/analyzers/smells/index.js +213 -0
  15. package/src/cli/argument-parser.js +45 -0
  16. package/src/cli/commands/analyze.js +146 -0
  17. package/src/cli/commands/compare.js +121 -0
  18. package/src/cli/commands/history.js +91 -0
  19. package/src/cli/commands/init.js +51 -0
  20. package/src/cli/commands/rules.js +110 -0
  21. package/src/config/loader.js +142 -0
  22. package/src/config/validator.js +130 -0
  23. package/src/core/analyzer.js +198 -0
  24. package/src/core/file-filter.js +95 -0
  25. package/src/core/project-scanner.js +119 -0
  26. package/src/history/comparison-engine.js +86 -0
  27. package/src/history/snapshot-manager.js +190 -0
  28. package/src/index.js +16 -0
  29. package/src/reporters/html.js +313 -0
  30. package/src/reporters/json.js +45 -0
  31. package/src/reporters/terminal.js +197 -0
  32. package/src/rules/defaults.js +145 -0
  33. package/src/rules/registry.js +75 -0
  34. package/src/scoring/score-calculator.js +299 -0
  35. package/src/scoring/weights.js +53 -0
  36. package/src/utils/ast-utils.js +173 -0
  37. package/src/utils/file-utils.js +64 -0
  38. package/src/utils/logger.js +54 -0
@@ -0,0 +1,119 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import fg from 'fast-glob';
4
+ import { FileFilter } from './file-filter.js';
5
+ import { isSymlink } from '../utils/file-utils.js';
6
+ import * as logger from '../utils/logger.js';
7
+
8
+ // fast-glob hard-ignores; these supplement the FileFilter exclusions at the
9
+ // glob level for speed — no point even stat-ing these entries.
10
+ const FG_IGNORE = [
11
+ '**/node_modules/**',
12
+ '**/.git/**',
13
+ '**/dist/**',
14
+ '**/build/**',
15
+ '**/coverage/**',
16
+ '**/.nyc_output/**',
17
+ ];
18
+
19
+ const DEFAULT_MAX_FILE_SIZE = 1_000_000; // 1 MB
20
+
21
+ export class ProjectScanner {
22
+ /**
23
+ * @param {object} options
24
+ * @param {string} options.rootDir - Directory to scan.
25
+ * @param {string[]} [options.ignore] - Extra ignore patterns.
26
+ * @param {string[]} [options.extensions] - File extensions to include.
27
+ * @param {boolean} [options.followSymlinks] - Follow symlinks (default false).
28
+ * @param {number} [options.maxFileSize] - Max bytes per file (default 1 MB).
29
+ */
30
+ constructor(options = {}) {
31
+ this.rootDir = path.resolve(options.rootDir ?? process.cwd());
32
+ this.followSymlinks = options.followSymlinks ?? false;
33
+ this.maxFileSize = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
34
+
35
+ this._filter = new FileFilter({
36
+ rootDir: this.rootDir,
37
+ ignore: options.ignore ?? [],
38
+ extensions: options.extensions,
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Scan the project directory and return categorised file lists.
44
+ *
45
+ * Returns:
46
+ * {
47
+ * files: string[], — absolute paths to analyze
48
+ * skipped: { path: string, reason: string }[] — excluded files with reasons
49
+ * }
50
+ */
51
+ async scan() {
52
+ if (!fs.existsSync(this.rootDir)) {
53
+ throw new Error(`Directory does not exist: ${this.rootDir}`);
54
+ }
55
+
56
+ const stat = fs.statSync(this.rootDir);
57
+ if (!stat.isDirectory()) {
58
+ // Single-file mode: treat target as the only file to analyse
59
+ const reason = this._filter.exclusionReason(this.rootDir, path.dirname(this.rootDir));
60
+ if (reason) {
61
+ logger.warn(`File excluded: ${reason}`);
62
+ return { files: [], skipped: [{ path: this.rootDir, reason }] };
63
+ }
64
+ return { files: [this.rootDir], skipped: [] };
65
+ }
66
+
67
+ logger.verbose(`Scanning: ${this.rootDir}`);
68
+
69
+ const entries = await fg('**/*', {
70
+ cwd: this.rootDir,
71
+ absolute: true,
72
+ onlyFiles: true,
73
+ followSymbolicLinks: this.followSymlinks,
74
+ dot: true,
75
+ ignore: FG_IGNORE,
76
+ });
77
+
78
+ const accepted = [];
79
+ const skipped = [];
80
+
81
+ for (const entry of entries) {
82
+ // Symlink guard
83
+ if (!this.followSymlinks && isSymlink(entry)) {
84
+ logger.verbose(`Skipping symlink: ${path.relative(this.rootDir, entry)}`);
85
+ skipped.push({ path: entry, reason: 'symlink' });
86
+ continue;
87
+ }
88
+
89
+ // File size guard
90
+ let size = 0;
91
+ try {
92
+ size = fs.statSync(entry).size;
93
+ } catch {
94
+ skipped.push({ path: entry, reason: 'stat failed' });
95
+ continue;
96
+ }
97
+
98
+ if (size > this.maxFileSize) {
99
+ const rel = path.relative(this.rootDir, entry);
100
+ logger.verbose(`Skipping large file: ${rel} (${size} bytes)`);
101
+ skipped.push({ path: entry, reason: `exceeds max file size (${size} bytes > ${this.maxFileSize})` });
102
+ continue;
103
+ }
104
+
105
+ // Extension + ignore filter
106
+ const reason = this._filter.exclusionReason(entry, this.rootDir);
107
+ if (reason) {
108
+ logger.verbose(`Skipping ${path.relative(this.rootDir, entry)}: ${reason}`);
109
+ skipped.push({ path: entry, reason });
110
+ continue;
111
+ }
112
+
113
+ accepted.push(entry);
114
+ }
115
+
116
+ logger.verbose(`Accepted ${accepted.length} files, skipped ${skipped.length}`);
117
+ return { files: accepted, skipped };
118
+ }
119
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Comparison Engine
3
+ *
4
+ * Computes a structured diff between two snapshots so the CLI can show
5
+ * what improved, regressed, or stayed the same since the last run.
6
+ *
7
+ * Returned diff shape:
8
+ * {
9
+ * snapshotA: { id, timestamp, label, overall }
10
+ * snapshotB: { id, timestamp, label, overall }
11
+ * overall: ScoreDelta
12
+ * breakdown: { complexity: ScoreDelta, duplication: ScoreDelta, … }
13
+ * metrics: { totalLines: Delta, issueCount: Delta, filesAnalyzed: Delta }
14
+ * trend: 'improved' | 'regressed' | 'unchanged'
15
+ * }
16
+ *
17
+ * ScoreDelta: { before, after, delta, direction: 'up'|'down'|'same' }
18
+ * Delta: { before, after, delta }
19
+ */
20
+
21
+ const DIMENSIONS = ['complexity', 'duplication', 'maintainability', 'dependencies', 'hygiene'];
22
+
23
+ /**
24
+ * Compare two snapshots.
25
+ *
26
+ * @param {object} snapA — older snapshot (the baseline)
27
+ * @param {object} snapB — newer snapshot (the current)
28
+ * @returns {object} — diff object as described above
29
+ */
30
+ export function compare(snapA, snapB) {
31
+ const overall = _scoreDelta(snapA.scores?.overall ?? null, snapB.scores?.overall ?? null);
32
+
33
+ const breakdown = {};
34
+ for (const dim of DIMENSIONS) {
35
+ const a = snapA.scores?.breakdown?.[dim]?.score ?? null;
36
+ const b = snapB.scores?.breakdown?.[dim]?.score ?? null;
37
+ breakdown[dim] = _scoreDelta(a, b);
38
+ }
39
+
40
+ const metrics = {
41
+ totalLines: _delta(snapA.metrics?.totalLines ?? 0, snapB.metrics?.totalLines ?? 0),
42
+ issueCount: _delta(snapA.issueCount ?? 0, snapB.issueCount ?? 0),
43
+ filesAnalyzed: _delta(snapA.filesAnalyzed ?? 0, snapB.filesAnalyzed ?? 0),
44
+ };
45
+
46
+ const trend = overall.delta > 0 ? 'improved'
47
+ : overall.delta < 0 ? 'regressed'
48
+ : 'unchanged';
49
+
50
+ return {
51
+ snapshotA: _ref(snapA),
52
+ snapshotB: _ref(snapB),
53
+ overall,
54
+ breakdown,
55
+ metrics,
56
+ trend,
57
+ };
58
+ }
59
+
60
+ // ── Helpers ───────────────────────────────────────────────────────────────────
61
+
62
+ function _scoreDelta(before, after) {
63
+ if (before === null || after === null) {
64
+ return { before, after, delta: null, direction: 'same' };
65
+ }
66
+ const delta = after - before;
67
+ return {
68
+ before,
69
+ after,
70
+ delta: +delta.toFixed(1),
71
+ direction: delta > 0 ? 'up' : delta < 0 ? 'down' : 'same',
72
+ };
73
+ }
74
+
75
+ function _delta(before, after) {
76
+ return { before, after, delta: after - before };
77
+ }
78
+
79
+ function _ref(snap) {
80
+ return {
81
+ id: snap.id,
82
+ timestamp: snap.timestamp,
83
+ label: snap.label ?? null,
84
+ overall: snap.scores?.overall ?? null,
85
+ };
86
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Snapshot Manager
3
+ *
4
+ * Persists and retrieves analysis snapshots so users can track code health
5
+ * over time and compare runs.
6
+ *
7
+ * Storage layout (relative to the analysed project root):
8
+ * <rootDir>/.codepulse/snapshots/
9
+ * index.json — ordered list of snapshot metadata
10
+ * <id>.json — full snapshot data
11
+ *
12
+ * Snapshot schema:
13
+ * {
14
+ * id: string — ISO timestamp slug, e.g. "2026-11-21T10-00-00"
15
+ * timestamp: string — ISO 8601 full timestamp
16
+ * rootDir: string — absolute path of the analysed project
17
+ * label: string? — optional human label (--label flag)
18
+ * scores: object — result.scores (overall + breakdown)
19
+ * metrics: object — result.metrics (totalLines, totalFiles, …)
20
+ * filesAnalyzed: number
21
+ * issueCount: number
22
+ * issuesBySeverity: { critical, high, medium, low }
23
+ * }
24
+ */
25
+
26
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, unlinkSync } from 'node:fs';
27
+ import path from 'node:path';
28
+
29
+ const SNAPSHOTS_DIR = '.codepulse/snapshots';
30
+ const INDEX_FILE = 'index.json';
31
+
32
+ // ── Public API ────────────────────────────────────────────────────────────────
33
+
34
+ export class SnapshotManager {
35
+ /**
36
+ * @param {string} rootDir — the analysed project root (snapshots live here)
37
+ */
38
+ constructor(rootDir) {
39
+ this.rootDir = rootDir;
40
+ this.storeDir = path.join(rootDir, SNAPSHOTS_DIR);
41
+ this.indexPath = path.join(this.storeDir, INDEX_FILE);
42
+ }
43
+
44
+ // ── Write ──────────────────────────────────────────────────────────────────
45
+
46
+ /**
47
+ * Save a snapshot derived from an analysis result.
48
+ *
49
+ * @param {object} result — full analyzer result (with result.scores)
50
+ * @param {object} options — { label?: string }
51
+ * @returns {object} — the saved snapshot record
52
+ */
53
+ save(result, options = {}) {
54
+ this._ensureDir();
55
+
56
+ const ts = result.timestamp ?? new Date().toISOString();
57
+ const id = _makeId(ts);
58
+ const snap = _distil(id, ts, result, options.label);
59
+
60
+ writeFileSync(path.join(this.storeDir, `${id}.json`), JSON.stringify(snap, null, 2), 'utf8');
61
+ this._appendIndex(snap);
62
+
63
+ return snap;
64
+ }
65
+
66
+ // ── Read ───────────────────────────────────────────────────────────────────
67
+
68
+ /**
69
+ * Load a snapshot by ID.
70
+ * @param {string} id
71
+ * @returns {object|null}
72
+ */
73
+ load(id) {
74
+ if (!_safeId(id)) return null;
75
+ const p = path.join(this.storeDir, `${id}.json`);
76
+ // Ensure resolved path stays inside storeDir (path traversal guard)
77
+ if (!path.resolve(p).startsWith(path.resolve(this.storeDir) + path.sep)) return null;
78
+ if (!existsSync(p)) return null;
79
+ return JSON.parse(readFileSync(p, 'utf8'));
80
+ }
81
+
82
+ /**
83
+ * List all stored snapshots, most recent first.
84
+ * Returns lightweight metadata (not full snapshot data).
85
+ * @returns {object[]}
86
+ */
87
+ list() {
88
+ if (!existsSync(this.indexPath)) return [];
89
+ return JSON.parse(readFileSync(this.indexPath, 'utf8')).reverse();
90
+ }
91
+
92
+ /**
93
+ * Return the N most recent snapshots (full data).
94
+ * @param {number} n
95
+ * @returns {object[]}
96
+ */
97
+ recent(n = 10) {
98
+ return this.list()
99
+ .slice(0, n)
100
+ .map(meta => this.load(meta.id))
101
+ .filter(Boolean);
102
+ }
103
+
104
+ /**
105
+ * Delete a snapshot by ID.
106
+ * @param {string} id
107
+ * @returns {boolean} true if deleted, false if not found
108
+ */
109
+ delete(id) {
110
+ if (!_safeId(id)) return false;
111
+ const p = path.join(this.storeDir, `${id}.json`);
112
+ if (!path.resolve(p).startsWith(path.resolve(this.storeDir) + path.sep)) return false;
113
+ if (!existsSync(p)) return false;
114
+ unlinkSync(p);
115
+ this._removeFromIndex(id);
116
+ return true;
117
+ }
118
+
119
+ // ── Internals ──────────────────────────────────────────────────────────────
120
+
121
+ _ensureDir() {
122
+ mkdirSync(this.storeDir, { recursive: true });
123
+ if (!existsSync(this.indexPath)) {
124
+ writeFileSync(this.indexPath, '[]', 'utf8');
125
+ }
126
+ }
127
+
128
+ _appendIndex(snap) {
129
+ const index = existsSync(this.indexPath)
130
+ ? JSON.parse(readFileSync(this.indexPath, 'utf8'))
131
+ : [];
132
+ index.push(_metaOf(snap));
133
+ writeFileSync(this.indexPath, JSON.stringify(index, null, 2), 'utf8');
134
+ }
135
+
136
+ _removeFromIndex(id) {
137
+ if (!existsSync(this.indexPath)) return;
138
+ const index = JSON.parse(readFileSync(this.indexPath, 'utf8'));
139
+ const filtered = index.filter(m => m.id !== id);
140
+ writeFileSync(this.indexPath, JSON.stringify(filtered, null, 2), 'utf8');
141
+ }
142
+ }
143
+
144
+ // ── Helpers ───────────────────────────────────────────────────────────────────
145
+
146
+ /** Convert ISO timestamp to a filesystem-safe ID string. */
147
+ function _makeId(ts) {
148
+ return ts.replace(/[:.]/g, '-').replace('T', 'T').slice(0, 23).replace(/\./g, '-');
149
+ }
150
+
151
+ /** Extract the fields we store in the snapshot file. */
152
+ function _distil(id, ts, result, label) {
153
+ const bySev = (result.issues ?? []).reduce((acc, i) => {
154
+ acc[i.severity] = (acc[i.severity] ?? 0) + 1;
155
+ return acc;
156
+ }, {});
157
+
158
+ return {
159
+ id,
160
+ timestamp: ts,
161
+ label: label ?? null,
162
+ rootDir: result.rootDir,
163
+ scores: result.scores ?? null,
164
+ metrics: result.metrics ?? {},
165
+ filesAnalyzed: result.filesAnalyzed ?? 0,
166
+ issueCount: (result.issues ?? []).length,
167
+ issuesBySeverity: bySev,
168
+ };
169
+ }
170
+
171
+ /** Lightweight metadata kept in the index (no full scores breakdown). */
172
+ function _metaOf(snap) {
173
+ return {
174
+ id: snap.id,
175
+ timestamp: snap.timestamp,
176
+ label: snap.label,
177
+ overall: snap.scores?.overall ?? null,
178
+ issueCount: snap.issueCount,
179
+ filesAnalyzed: snap.filesAnalyzed,
180
+ };
181
+ }
182
+
183
+ /**
184
+ * Validate a snapshot ID before using it in a file path.
185
+ * Allows only the characters produced by _makeId(): alphanumerics, dashes, T.
186
+ * Rejects any path traversal attempts (dots, slashes, etc.).
187
+ */
188
+ function _safeId(id) {
189
+ return typeof id === 'string' && /^[A-Za-z0-9T\-]+$/.test(id);
190
+ }
package/src/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * CodePulse public API.
3
+ * Import these when using CodePulse programmatically.
4
+ */
5
+
6
+ export { Analyzer } from './core/analyzer.js';
7
+ export { ProjectScanner } from './core/project-scanner.js';
8
+ export { FileFilter } from './core/file-filter.js';
9
+
10
+ export { parseFile, walkAST, countLines, nodeLength, getFunctionName, isFunctionNode } from './utils/ast-utils.js';
11
+ export { readFileSafe, safePath, ensureDir, writeJsonSafe } from './utils/file-utils.js';
12
+
13
+ export { loadConfig, mergeConfig, DEFAULT_CONFIG } from './config/loader.js';
14
+
15
+ export { registerRule, getRule, getAllRules, getRulesByCategory, applyRulesConfig } from './rules/registry.js';
16
+ export { registerDefaultRules } from './rules/defaults.js';