@c9up/helix 0.1.3

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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -0
  3. package/bin/helix.js +432 -0
  4. package/package.json +66 -0
  5. package/src/cli/coverage/aggregate.ts +231 -0
  6. package/src/cli/coverage/collect.ts +63 -0
  7. package/src/cli/coverage/diff/base.ts +46 -0
  8. package/src/cli/coverage/diff/index.ts +160 -0
  9. package/src/cli/coverage/diff/overlay.ts +62 -0
  10. package/src/cli/coverage/diff/parse.ts +121 -0
  11. package/src/cli/coverage/diff/reporters.ts +82 -0
  12. package/src/cli/coverage/diff/types.ts +46 -0
  13. package/src/cli/coverage/filter.ts +71 -0
  14. package/src/cli/coverage/glob.ts +0 -0
  15. package/src/cli/coverage/index.ts +126 -0
  16. package/src/cli/coverage/reporters/json.ts +40 -0
  17. package/src/cli/coverage/reporters/lcov.ts +54 -0
  18. package/src/cli/coverage/reporters/text.ts +48 -0
  19. package/src/cli/coverage/thresholds.ts +73 -0
  20. package/src/cli/coverage/types.ts +93 -0
  21. package/src/cli/discover.ts +174 -0
  22. package/src/cli/native.ts +104 -0
  23. package/src/cli/pool.ts +486 -0
  24. package/src/cli/reporter.ts +155 -0
  25. package/src/cli/run.ts +440 -0
  26. package/src/cli/summary.ts +42 -0
  27. package/src/cli/watch/loop.ts +159 -0
  28. package/src/cli/watch/types.ts +22 -0
  29. package/src/cli/watch/watcher.ts +145 -0
  30. package/src/container/index.ts +16 -0
  31. package/src/container/override.ts +86 -0
  32. package/src/container/spy.ts +25 -0
  33. package/src/index.ts +42 -0
  34. package/src/runtime/assertion-error.ts +38 -0
  35. package/src/runtime/cli-worker.ts +140 -0
  36. package/src/runtime/equals.ts +400 -0
  37. package/src/runtime/expect.ts +173 -0
  38. package/src/runtime/index.ts +50 -0
  39. package/src/runtime/lifecycle.ts +17 -0
  40. package/src/runtime/matchers.ts +452 -0
  41. package/src/runtime/run.ts +573 -0
  42. package/src/runtime/suite.ts +310 -0
  43. package/src/runtime/test-context.ts +59 -0
  44. package/src/runtime/vi/fake-timers.ts +410 -0
  45. package/src/runtime/vi/index.ts +254 -0
  46. package/src/runtime/vi/spy.ts +224 -0
  47. package/src/runtime/vi/spyOn.ts +155 -0
  48. package/src/runtime/vi/system-time.ts +121 -0
  49. package/src/runtime/worker.ts +239 -0
  50. package/src/time/freeze.ts +229 -0
  51. package/src/time/index.ts +16 -0
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Aggregation: merge N raw coverage entries (possibly for the same file
3
+ * from different workers) into a single `CoverageSummary` with per-file
4
+ * and total line / function counts.
5
+ *
6
+ * Range merging strategy mirrors `v8-to-istanbul`:
7
+ * - Walk ranges OUTERMOST-first so inner ranges OVERWRITE the outer
8
+ * count for the lines they cover. A `count: 0` inner range carved
9
+ * out of a `count: 5` outer correctly marks those inner lines as
10
+ * uncovered, matching V8's block-coverage semantics. The previous
11
+ * `Math.max` strategy hid uncovered branches behind their outer
12
+ * function's hit count.
13
+ * - V8 emits BYTE offsets (UTF-8); we convert via Buffer.byteLength
14
+ * so non-ASCII source code maps lines correctly.
15
+ * - When two workers cover the same file:
16
+ * - if their `source` differs (cache-busting query loaded different
17
+ * content), we keep the longer source (best-effort) but emit a
18
+ * warning — offsets are only consistent within one source.
19
+ * - functions are deduplicated by `(name, startOffset)` so the
20
+ * lcov FNF count doesn't double.
21
+ */
22
+
23
+ import type {
24
+ CoverageSummary,
25
+ FileSummary,
26
+ RawFileCoverage,
27
+ Totals,
28
+ V8Function,
29
+ } from "./types.js";
30
+
31
+ /**
32
+ * Build a function `byteOffset → 1-based line number` over `source`.
33
+ * V8 offsets are UTF-8 byte offsets, so we walk the string code-unit by
34
+ * code-unit and accumulate byte length to keep both indices in sync.
35
+ *
36
+ * Returns `[mapper, totalBytes]`. `totalBytes` is needed so callers can
37
+ * detect offsets pointing past EOF (corrupt input) and clamp.
38
+ */
39
+ function buildOffsetToLine(
40
+ source: string,
41
+ ): [(offset: number) => number, number] {
42
+ const lineStarts: number[] = [0];
43
+ let byteIndex = 0;
44
+ for (let i = 0; i < source.length; i += 1) {
45
+ const code = source.charCodeAt(i);
46
+ // UTF-16 surrogate pair → encodes a single 4-byte UTF-8 char.
47
+ if (code >= 0xd800 && code <= 0xdbff && i + 1 < source.length) {
48
+ const next = source.charCodeAt(i + 1);
49
+ if (next >= 0xdc00 && next <= 0xdfff) {
50
+ byteIndex += 4;
51
+ i += 1;
52
+ continue;
53
+ }
54
+ }
55
+ // Lone surrogate or BMP char — Buffer.byteLength of one code unit:
56
+ // < 0x80 → 1 byte
57
+ // < 0x800 → 2 bytes
58
+ // else → 3 bytes (BMP non-surrogate)
59
+ if (code < 0x80) {
60
+ byteIndex += 1;
61
+ if (code === 10 /* \n */) lineStarts.push(byteIndex);
62
+ } else if (code < 0x800) {
63
+ byteIndex += 2;
64
+ } else {
65
+ byteIndex += 3;
66
+ }
67
+ }
68
+ const totalBytes = byteIndex;
69
+ const mapper = (offset: number): number => {
70
+ const clamped = Math.max(0, Math.min(offset, totalBytes));
71
+ // Binary search for the largest lineStart <= clamped.
72
+ let lo = 0;
73
+ let hi = lineStarts.length - 1;
74
+ while (lo < hi) {
75
+ const mid = (lo + hi + 1) >>> 1;
76
+ if (lineStarts[mid] <= clamped) lo = mid;
77
+ else hi = mid - 1;
78
+ }
79
+ return lo + 1;
80
+ };
81
+ return [mapper, totalBytes];
82
+ }
83
+
84
+ function computeFileSummary(entry: RawFileCoverage): FileSummary {
85
+ const [offsetToLine] = buildOffsetToLine(entry.source);
86
+ const lineHitsMap = new Map<number, number>();
87
+ const functionHits: FileSummary["functionHits"] = [];
88
+ let fnCovered = 0;
89
+ // Apply ranges across ALL functions in one global pass, sorted by
90
+ // span DESC. The whole-file pseudo-function (largest span) lands
91
+ // first; inner functions and their inner ranges overwrite — so a
92
+ // never-called inner function correctly drops its lines back to
93
+ // count=0 even though the script itself executed at count=1.
94
+ const allRanges: Array<{
95
+ startOffset: number;
96
+ endOffset: number;
97
+ count: number;
98
+ }> = [];
99
+ for (const fn of entry.functions) {
100
+ for (const r of fn.ranges) {
101
+ if (r.endOffset > r.startOffset) allRanges.push(r);
102
+ }
103
+ }
104
+ allRanges.sort((a, b) => {
105
+ const spanA = a.endOffset - a.startOffset;
106
+ const spanB = b.endOffset - b.startOffset;
107
+ if (spanA !== spanB) return spanB - spanA;
108
+ return a.startOffset - b.startOffset;
109
+ });
110
+ for (const r of allRanges) {
111
+ const startLine = offsetToLine(r.startOffset);
112
+ const endLine = offsetToLine(r.endOffset - 1);
113
+ for (let line = startLine; line <= endLine; line += 1) {
114
+ lineHitsMap.set(line, r.count);
115
+ }
116
+ }
117
+ for (const fn of entry.functions) {
118
+ const firstRange = fn.ranges[0];
119
+ // Skip pseudo-functions / synthetic entries with no usable range so
120
+ // reports don't carry `FN:0,name` (lcov rejects line < 1).
121
+ if (!firstRange) continue;
122
+ const fnCount = firstRange.count;
123
+ const fnLine = offsetToLine(firstRange.startOffset);
124
+ if (fnCount > 0) fnCovered += 1;
125
+ functionHits.push({
126
+ name: fn.functionName || "(anonymous)",
127
+ line: Math.max(1, fnLine),
128
+ count: fnCount,
129
+ });
130
+ }
131
+ const lineHits = Array.from(lineHitsMap.entries())
132
+ .map(([line, count]) => ({ line, count }))
133
+ .sort((a, b) => a.line - b.line);
134
+ const linesCovered = lineHits.filter((h) => h.count > 0).length;
135
+ const linesTotal = lineHits.length;
136
+ const fnTotal = functionHits.length;
137
+ return {
138
+ file: entry.file,
139
+ lines: { covered: linesCovered, total: linesTotal },
140
+ // Statements ≈ lines (V8 doesn't expose AST statement boundaries —
141
+ // matches Vitest's v8 provider).
142
+ statements: { covered: linesCovered, total: linesTotal },
143
+ functions: { covered: fnCovered, total: fnTotal },
144
+ // Branches deferred; report 0/0 so reporters / thresholds can still
145
+ // format the field consistently.
146
+ branches: { covered: 0, total: 0 },
147
+ lineHits,
148
+ functionHits,
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Merge two raw entries for the same file. Functions are deduplicated by
154
+ * `(name, startOffset)` so concatenation doesn't double FNF in lcov.
155
+ * If `source` differs, we keep the longer one (best effort) and emit a
156
+ * stderr advisory — offsets only line up within one source.
157
+ */
158
+ function mergeRaw(a: RawFileCoverage, b: RawFileCoverage): RawFileCoverage {
159
+ if (a.source && b.source && a.source !== b.source) {
160
+ process.stderr.write(
161
+ `helix-coverage: ${a.file} has divergent source content across workers — line attribution may be off\n`,
162
+ );
163
+ }
164
+ const seen = new Set<string>();
165
+ const merged: V8Function[] = [];
166
+ for (const fn of [...a.functions, ...b.functions]) {
167
+ const startOffset = fn.ranges[0]?.startOffset ?? -1;
168
+ const key = `${fn.functionName}@${startOffset}`;
169
+ if (seen.has(key)) continue;
170
+ seen.add(key);
171
+ merged.push(fn);
172
+ }
173
+ return {
174
+ file: a.file,
175
+ source: a.source.length >= b.source.length ? a.source : b.source,
176
+ functions: merged,
177
+ };
178
+ }
179
+
180
+ function pct(covered: number, total: number): number {
181
+ if (total === 0) return 100;
182
+ return Math.round((covered / total) * 10000) / 100;
183
+ }
184
+
185
+ export function aggregate(raw: RawFileCoverage[]): CoverageSummary {
186
+ const byFile = new Map<string, RawFileCoverage>();
187
+ for (const entry of raw) {
188
+ // Skip files we couldn't read source for — emitting a 1-line ghost
189
+ // summary based on collapsed line=1 mapping is worse than omission.
190
+ if (!entry.source) {
191
+ process.stderr.write(
192
+ `helix-coverage: skipping ${entry.file} — source unreadable\n`,
193
+ );
194
+ continue;
195
+ }
196
+ const prev = byFile.get(entry.file);
197
+ byFile.set(entry.file, prev ? mergeRaw(prev, entry) : entry);
198
+ }
199
+ const files = Array.from(byFile.values())
200
+ .map(computeFileSummary)
201
+ // Files that ended up with 0 lines / 0 functions (no V8 data) are
202
+ // dropped — they distort per-file averages and clutter the table.
203
+ .filter((f) => f.lines.total > 0 || f.functions.total > 0)
204
+ .sort((a, b) => a.file.localeCompare(b.file));
205
+
206
+ const totals: Totals = {
207
+ lines: { covered: 0, total: 0, pct: 0 },
208
+ statements: { covered: 0, total: 0, pct: 0 },
209
+ functions: { covered: 0, total: 0, pct: 0 },
210
+ branches: { covered: 0, total: 0, pct: 0 },
211
+ };
212
+ for (const f of files) {
213
+ totals.lines.covered += f.lines.covered;
214
+ totals.lines.total += f.lines.total;
215
+ totals.statements.covered += f.statements.covered;
216
+ totals.statements.total += f.statements.total;
217
+ totals.functions.covered += f.functions.covered;
218
+ totals.functions.total += f.functions.total;
219
+ totals.branches.covered += f.branches.covered;
220
+ totals.branches.total += f.branches.total;
221
+ }
222
+ totals.lines.pct = pct(totals.lines.covered, totals.lines.total);
223
+ totals.statements.pct = pct(
224
+ totals.statements.covered,
225
+ totals.statements.total,
226
+ );
227
+ totals.functions.pct = pct(totals.functions.covered, totals.functions.total);
228
+ totals.branches.pct = pct(totals.branches.covered, totals.branches.total);
229
+
230
+ return { files, total: totals };
231
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Reads every `coverage-*.json` produced by the V8 profiler in a given
3
+ * directory, decodes `file://` URLs, and returns a normalised list of
4
+ * `RawFileCoverage` entries (one per unique script URL).
5
+ *
6
+ * Workers write coverage via `NODE_V8_COVERAGE=<dir>` — the orchestrator
7
+ * sets this env var on every spawn and reads the directory after all
8
+ * workers exit. Multiple workers may record the same file; we return ALL
9
+ * entries here and let `aggregate.ts` merge.
10
+ */
11
+
12
+ import { readdir, readFile } from "node:fs/promises";
13
+ import path from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import type { RawFileCoverage, V8CoverageFile } from "./types.js";
16
+
17
+ export async function collect(dir: string): Promise<RawFileCoverage[]> {
18
+ let entries: string[];
19
+ try {
20
+ entries = await readdir(dir);
21
+ } catch {
22
+ return [];
23
+ }
24
+ const jsonFiles = entries.filter((e) => e.endsWith(".json"));
25
+ const all: RawFileCoverage[] = [];
26
+ for (const name of jsonFiles) {
27
+ const p = path.join(dir, name);
28
+ let parsed: V8CoverageFile;
29
+ try {
30
+ const raw = await readFile(p, "utf8");
31
+ parsed = JSON.parse(raw) as V8CoverageFile;
32
+ } catch {
33
+ continue;
34
+ }
35
+ for (const script of parsed.result ?? []) {
36
+ if (!script.url?.startsWith("file://")) continue;
37
+ // V8 sometimes appends `?query` params (our worker uses them as
38
+ // cache-busters) — strip them so the same file from two workers
39
+ // merges correctly.
40
+ const cleanUrl = script.url.split("?")[0];
41
+ let file: string;
42
+ try {
43
+ file = fileURLToPath(cleanUrl);
44
+ } catch {
45
+ continue;
46
+ }
47
+ let source = "";
48
+ try {
49
+ source = await readFile(file, "utf8");
50
+ } catch {
51
+ // Source read may fail for transient temp files or modules that
52
+ // have been GC'd — leave empty; downstream stages fall back to
53
+ // offset-only computation.
54
+ }
55
+ all.push({
56
+ file,
57
+ source,
58
+ functions: script.functions ?? [],
59
+ });
60
+ }
61
+ }
62
+ return all;
63
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Resolve the default base ref to diff against. Tries, in order:
3
+ * 1. `origin/main`
4
+ * 2. `origin/master`
5
+ * 3. local `main`
6
+ * 4. local `master`
7
+ *
8
+ * Returns `undefined` if none of those exist (so the caller can warn
9
+ * instead of failing the run). Throws when the `git` binary itself is
10
+ * missing — the caller distinguishes "no repo / no ref" (skip
11
+ * gracefully) from "git not installed" (configuration error).
12
+ */
13
+
14
+ import { spawnSync } from "node:child_process";
15
+
16
+ const CANDIDATES = ["origin/main", "origin/master", "main", "master"];
17
+
18
+ export class GitMissingError extends Error {
19
+ constructor() {
20
+ super("git binary not found on PATH");
21
+ this.name = "GitMissingError";
22
+ }
23
+ }
24
+
25
+ function runGit(cwd: string, args: string[]): { ok: boolean } {
26
+ const result = spawnSync("git", args, {
27
+ cwd,
28
+ stdio: ["ignore", "pipe", "pipe"],
29
+ });
30
+ const err = result.error as NodeJS.ErrnoException | undefined;
31
+ if (err?.code === "ENOENT") throw new GitMissingError();
32
+ return { ok: result.status === 0 };
33
+ }
34
+
35
+ function refExists(cwd: string, ref: string): boolean {
36
+ return runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])
37
+ .ok;
38
+ }
39
+
40
+ export function resolveBaseRef(cwd: string): string | undefined {
41
+ if (!runGit(cwd, ["rev-parse", "--git-dir"]).ok) return undefined;
42
+ for (const cand of CANDIDATES) {
43
+ if (refExists(cwd, cand)) return cand;
44
+ }
45
+ return undefined;
46
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Diff-coverage facade — wires base resolution → git diff → parser →
3
+ * overlay → reporters → thresholds. Called by `run.ts` after the
4
+ * full-tree finalise.
5
+ */
6
+
7
+ import { mkdir, writeFile } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { enforce } from "../thresholds.js";
10
+ import type {
11
+ CoverageSummary,
12
+ Thresholds,
13
+ ThresholdViolation,
14
+ } from "../types.js";
15
+ import { GitMissingError, resolveBaseRef } from "./base.js";
16
+ import { overlay } from "./overlay.js";
17
+ import { parseDiff } from "./parse.js";
18
+ import { diffJson, diffTextSummary } from "./reporters.js";
19
+ import type { DiffOptions, DiffSummary } from "./types.js";
20
+
21
+ export type { DiffOptions, DiffSummary } from "./types.js";
22
+
23
+ export interface DiffFinaliseInput extends DiffOptions {
24
+ root: string;
25
+ coverage: CoverageSummary;
26
+ }
27
+
28
+ export interface DiffFinaliseResult {
29
+ summary: DiffSummary;
30
+ violations: ThresholdViolation[];
31
+ textReport: string;
32
+ reportFiles: string[];
33
+ /** When `undefined`, the diff stage was skipped (not in a repo, no
34
+ * base ref, etc.) — callers should print `warning` and move on. */
35
+ warning?: string;
36
+ }
37
+
38
+ /**
39
+ * Wrap the diff totals into a `CoverageSummary`-shaped object so we can
40
+ * reuse the full-tree `enforce()` helper. Only `lines`/`statements` are
41
+ * populated; `functions`/`branches` are unsupported in diff mode and are
42
+ * rejected upfront in `validateDiffThresholds`.
43
+ */
44
+ function toCoverageSummary(diff: DiffSummary): CoverageSummary {
45
+ return {
46
+ files: [],
47
+ total: {
48
+ lines: {
49
+ covered: diff.total.covered,
50
+ total: diff.total.added,
51
+ pct: diff.total.pct,
52
+ },
53
+ statements: {
54
+ covered: diff.total.covered,
55
+ total: diff.total.added,
56
+ pct: diff.total.pct,
57
+ },
58
+ functions: { covered: 0, total: 0, pct: 100 },
59
+ branches: { covered: 0, total: 0, pct: 100 },
60
+ },
61
+ };
62
+ }
63
+
64
+ function violationLine(
65
+ metric: keyof Thresholds,
66
+ actual: number,
67
+ threshold: number,
68
+ ): string {
69
+ return `coverage-diff: ${metric} ${actual.toFixed(1)} < threshold ${threshold}`;
70
+ }
71
+
72
+ /**
73
+ * Reject `functions`/`branches` thresholds in diff mode — we only track
74
+ * line-level diff coverage today, so silently passing those metrics
75
+ * would let users gate on metrics that always read 100%.
76
+ */
77
+ function validateDiffThresholds(t: Thresholds | undefined): void {
78
+ if (!t) return;
79
+ const unsupported: string[] = [];
80
+ if (typeof t.functions === "number" && t.functions > 0)
81
+ unsupported.push("functions");
82
+ if (typeof t.branches === "number" && t.branches > 0)
83
+ unsupported.push("branches");
84
+ if (unsupported.length > 0) {
85
+ throw new Error(
86
+ `diff-cov thresholds: ${unsupported.join(", ")} are not supported (line-only). Drop those keys.`,
87
+ );
88
+ }
89
+ }
90
+
91
+ export async function finaliseDiff(
92
+ input: DiffFinaliseInput,
93
+ ): Promise<DiffFinaliseResult> {
94
+ validateDiffThresholds(input.thresholds);
95
+
96
+ const cwd = input.cwd ?? input.root;
97
+ let base: string | undefined;
98
+ try {
99
+ base = input.base ?? resolveBaseRef(cwd);
100
+ } catch (err) {
101
+ if (err instanceof GitMissingError) {
102
+ return {
103
+ summary: { files: [], total: { added: 0, covered: 0, pct: 100 } },
104
+ violations: [],
105
+ textReport: "",
106
+ reportFiles: [],
107
+ warning: "diff-cov: git binary not found on PATH. Skipping.",
108
+ };
109
+ }
110
+ throw err;
111
+ }
112
+ if (!base) {
113
+ return {
114
+ summary: { files: [], total: { added: 0, covered: 0, pct: 100 } },
115
+ violations: [],
116
+ textReport: "",
117
+ reportFiles: [],
118
+ warning:
119
+ "diff-cov: no git base ref resolved (origin/main, main, master). Skipping.",
120
+ };
121
+ }
122
+
123
+ let diffMap: ReturnType<typeof parseDiff>;
124
+ try {
125
+ diffMap = parseDiff({ cwd, base });
126
+ } catch (err) {
127
+ return {
128
+ summary: { files: [], total: { added: 0, covered: 0, pct: 100 } },
129
+ violations: [],
130
+ textReport: "",
131
+ reportFiles: [],
132
+ warning: `diff-cov: ${err instanceof Error ? err.message : String(err)}`,
133
+ };
134
+ }
135
+
136
+ const summary = overlay(input.coverage, diffMap);
137
+
138
+ const reportFiles: string[] = [];
139
+ const outputDir = input.outputDir ?? path.join(input.root, "coverage");
140
+ await mkdir(outputDir, { recursive: true });
141
+ const file = path.join(outputDir, "coverage-diff.json");
142
+ await writeFile(file, diffJson(summary, input.root), "utf8");
143
+ reportFiles.push(file);
144
+
145
+ const textReport = diffTextSummary(summary, input.root);
146
+
147
+ let violations: ThresholdViolation[] = [];
148
+ if (input.thresholds) {
149
+ violations = enforce(toCoverageSummary(summary), input.thresholds);
150
+ }
151
+
152
+ return { summary, violations, textReport, reportFiles };
153
+ }
154
+
155
+ /** Reformat threshold violations with the `coverage-diff:` prefix. */
156
+ export function diffViolationSummary(violations: ThresholdViolation[]): string {
157
+ return violations
158
+ .map((v) => violationLine(v.metric, v.actual, v.threshold))
159
+ .join("\n");
160
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Overlay the diff map onto a `CoverageSummary` to compute per-file
3
+ * "added vs covered" totals.
4
+ *
5
+ * For each file in the diff:
6
+ * - find the matching coverage entry by absolute path
7
+ * - intersect the added line numbers with `lineHits` (count > 0 means
8
+ * covered)
9
+ * - emit a `DiffFileSummary`
10
+ *
11
+ * Files in the diff with no coverage entry are still reported (added
12
+ * lines, 0 covered) so a freshly-added module without any tests shows
13
+ * up red. Files in coverage but not in the diff are skipped (the PR
14
+ * didn't touch them, so they don't move the diff-coverage needle).
15
+ */
16
+
17
+ import type { CoverageSummary } from "../types.js";
18
+ import type { DiffFileSummary, DiffMap, DiffSummary } from "./types.js";
19
+
20
+ function pct(covered: number, added: number): number {
21
+ if (added === 0) return 100;
22
+ return Math.round((covered / added) * 10000) / 100;
23
+ }
24
+
25
+ export function overlay(coverage: CoverageSummary, diff: DiffMap): DiffSummary {
26
+ const coverageByFile = new Map(coverage.files.map((f) => [f.file, f]));
27
+ const files: DiffFileSummary[] = [];
28
+ let totalAdded = 0;
29
+ let totalCovered = 0;
30
+
31
+ for (const [file, addedLines] of diff) {
32
+ if (addedLines.size === 0) continue;
33
+ const cov = coverageByFile.get(file);
34
+ const hitsByLine = cov
35
+ ? new Map(cov.lineHits.map((h) => [h.line, h.count]))
36
+ : undefined;
37
+ const sortedAdded = [...addedLines].sort((a, b) => a - b);
38
+ const lineHits: DiffFileSummary["lineHits"] = sortedAdded.map((line) => {
39
+ const count = hitsByLine?.get(line);
40
+ return { line, covered: typeof count === "number" && count > 0 };
41
+ });
42
+ const covered = lineHits.filter((h) => h.covered).length;
43
+ files.push({
44
+ file,
45
+ added: addedLines.size,
46
+ covered,
47
+ lineHits,
48
+ });
49
+ totalAdded += addedLines.size;
50
+ totalCovered += covered;
51
+ }
52
+
53
+ files.sort((a, b) => a.file.localeCompare(b.file));
54
+ return {
55
+ files,
56
+ total: {
57
+ added: totalAdded,
58
+ covered: totalCovered,
59
+ pct: pct(totalCovered, totalAdded),
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Parse `git diff --unified=0 --no-color <base>...HEAD` output into a
3
+ * `DiffMap`. Why three-dot: it computes the diff at the merge-base, so
4
+ * commits made on `base` AFTER our branch diverged are excluded. That's
5
+ * the "what this PR contributes" semantic users expect.
6
+ *
7
+ * We force `--src-prefix=a/ --dst-prefix=b/` and `core.quotepath=false`
8
+ * so the parser doesn't have to guess at user-side `diff.noprefix` or
9
+ * non-ASCII path quoting.
10
+ *
11
+ * Renames produce `+++ b/<new path>` so they're picked up at the new
12
+ * location. Deletes produce `+++ /dev/null` and are skipped. Binary
13
+ * files produce no `+` lines so they contribute nothing.
14
+ */
15
+
16
+ import { spawnSync } from "node:child_process";
17
+ import { realpathSync } from "node:fs";
18
+ import path from "node:path";
19
+ import type { DiffMap } from "./types.js";
20
+
21
+ const HUNK_HEADER = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
22
+ const FILE_HEADER_PLUS = /^\+\+\+ (?:b\/(.*)|\/dev\/null)$/;
23
+
24
+ export interface ParseOptions {
25
+ cwd: string;
26
+ base: string;
27
+ }
28
+
29
+ function tryRealpath(p: string): string {
30
+ try {
31
+ return realpathSync(p);
32
+ } catch {
33
+ return p;
34
+ }
35
+ }
36
+
37
+ export function parseDiff(opts: ParseOptions): DiffMap {
38
+ const result = spawnSync(
39
+ "git",
40
+ [
41
+ "-c",
42
+ "core.quotepath=false",
43
+ "diff",
44
+ "--unified=0",
45
+ "--no-color",
46
+ "--src-prefix=a/",
47
+ "--dst-prefix=b/",
48
+ `${opts.base}...HEAD`,
49
+ ],
50
+ {
51
+ cwd: opts.cwd,
52
+ encoding: "utf8",
53
+ maxBuffer: 64 * 1024 * 1024,
54
+ },
55
+ );
56
+ if (result.error) {
57
+ const err = result.error as NodeJS.ErrnoException;
58
+ if (err.code === "ENOENT") {
59
+ throw new Error("git binary not found on PATH");
60
+ }
61
+ if (err.code === "ENOBUFS") {
62
+ throw new Error(
63
+ "diff output exceeded 64 MB — branch is too divergent to overlay",
64
+ );
65
+ }
66
+ throw new Error(`git diff failed: ${err.message}`);
67
+ }
68
+ if (result.status !== 0) {
69
+ throw new Error(
70
+ `git diff exited ${result.status}: ${result.stderr?.trim() || "(no stderr — likely shallow clone or pruned ref)"}`,
71
+ );
72
+ }
73
+ return parseDiffString(result.stdout, opts.cwd);
74
+ }
75
+
76
+ /**
77
+ * Pure parser — exposed separately so tests can feed canned diff
78
+ * strings without spawning git. Keys are canonicalised via realpath so
79
+ * they line up with V8 coverage paths (which `filter.ts` realpaths).
80
+ */
81
+ export function parseDiffString(diff: string, cwd: string): DiffMap {
82
+ const map: DiffMap = new Map();
83
+ let currentFile: string | undefined;
84
+ let nextAddedLine = 0;
85
+ const lines = diff.split(/\r?\n/);
86
+ for (const line of lines) {
87
+ const fileMatch = line.match(FILE_HEADER_PLUS);
88
+ if (fileMatch) {
89
+ const newPath = fileMatch[1];
90
+ if (!newPath) {
91
+ currentFile = undefined;
92
+ nextAddedLine = 0;
93
+ continue;
94
+ }
95
+ currentFile = tryRealpath(path.resolve(cwd, newPath));
96
+ nextAddedLine = 0;
97
+ continue;
98
+ }
99
+ if (!currentFile) continue;
100
+ const hunkMatch = line.match(HUNK_HEADER);
101
+ if (hunkMatch) {
102
+ nextAddedLine = Number.parseInt(hunkMatch[1], 10);
103
+ continue;
104
+ }
105
+ if (line.startsWith("+") && !line.startsWith("+++")) {
106
+ if (nextAddedLine < 1) {
107
+ // `+0,0` deletion-only hunks set nextAddedLine = 0; ignore stray
108
+ // `+` lines rather than emit invalid line numbers.
109
+ continue;
110
+ }
111
+ let set = map.get(currentFile);
112
+ if (!set) {
113
+ set = new Set();
114
+ map.set(currentFile, set);
115
+ }
116
+ set.add(nextAddedLine);
117
+ nextAddedLine += 1;
118
+ }
119
+ }
120
+ return map;
121
+ }