@supercat1337/coverage-to-markdown 0.0.0-stage → 1.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.
package/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Albert Bazaleev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,387 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @supercat1337/coverage-to-markdown
2
+
3
+ Turn a coverage-range string — the kind of line list that `c8`, `nyc`, or
4
+ `istanbul` print when tests don't cover a block — into a Markdown document
5
+ with copy-pasteable code snippets. For every uncovered block the tool
6
+ pulls the code together with configurable **context lines** before and
7
+ after, **appends an inline `// <lineNumber>` comment**, and picks a
8
+ **safe fence** so that backticks inside the source code never break the
9
+ Markdown.
10
+
11
+ ```text
12
+ $ cov2md --ranges "176-181,258-270" --input ./src/index.js --output ./coverage.md
13
+ Wrote 2 range(s) from /abs/path/src/index.js to /abs/path/coverage.md
14
+ ```
15
+
16
+ ## Why
17
+
18
+ When you ask someone (or an LLM) to write tests for uncovered lines, you
19
+ usually end up doing this by hand:
20
+
21
+ 1. Run coverage.
22
+ 2. Copy the offending line numbers.
23
+ 3. Open the file, find each block, copy it, note the line numbers.
24
+
25
+ This package does steps 2–3 for you and produces a stable Markdown
26
+ artifact you can attach to a PR, an issue, or a chat message.
27
+
28
+ ## Install
29
+
30
+ Global, as a CLI:
31
+
32
+ ```bash
33
+ npm i -g @supercat1337/coverage-to-markdown
34
+ ```
35
+
36
+ As a project dependency, for use in scripts or tests:
37
+
38
+ ```bash
39
+ npm i -D @supercat1337/coverage-to-markdown
40
+ ```
41
+
42
+ Requires Node.js **18 or newer**. The package has **zero runtime
43
+ dependencies** — everything is built on `node:fs`, `node:path`,
44
+ `node:url`, and `node:util`.
45
+
46
+ ## CLI
47
+
48
+ Both `coverage-to-markdown` and the shorter `cov2md` alias point to the
49
+ same script after a global install.
50
+
51
+ ```text
52
+ coverage-to-markdown --ranges <ranges> --input <source-file> --output <output-md> [options]
53
+ ```
54
+
55
+ ### Why named arguments only
56
+
57
+ All three main arguments are **required named flags**. There is no
58
+ positional form, and any leftover positional argument is rejected with a
59
+ non-zero exit code. This is deliberate: with positional arguments, a
60
+ forgotten or reordered argument can silently point `--output` at the
61
+ input file, and the source file is overwritten before you notice.
62
+
63
+ The tool also refuses to write over an existing file unless `--force`
64
+ is passed, and rejects a run where `--input` and `--output` resolve to
65
+ the same path.
66
+
67
+ ### Options
68
+
69
+ | Flag | Short | Required | Description | Default |
70
+ | --- | --- | --- | --- | --- |
71
+ | `--ranges <ranges>` | `-r` | yes | Comma-separated line ranges | |
72
+ | `--input <path>` | `-i` | yes | Source file to extract lines from | |
73
+ | `--output <path>` | `-o` | yes | Markdown file to write | |
74
+ | `--context <n>` | `-c` | | Lines of context before and after each range | `2` |
75
+ | `--title <s>` | `-t` | | Top-level heading text | `Coverage: <basename>` |
76
+ | `--fence <lang>` | | | Override fence language | Detected from extension |
77
+ | `--highlight <mode>` | | | Uncovered marker: `none`, `comment`, `gutter` | `comment` |
78
+ | `--command <cmd>` | | | Add a `Reproduce:` line to the header | |
79
+ | `--absolute-path` | | | Print the source path as absolute | off (relative) |
80
+ | `--force` | `-f` | | Overwrite the output file if it exists | off |
81
+ | `--quiet` | `-q` | | Suppress the success summary | off |
82
+ | `--help` | `-h` | | Show usage and exit | |
83
+ | `--version` | `-v` | | Print the version and exit | |
84
+
85
+ ### Examples
86
+
87
+ ```bash
88
+ # Default context of two lines
89
+ cov2md \
90
+ --ranges "176-181,258-270,286-287" \
91
+ --input ./src/index.js \
92
+ --output ./coverage.md
93
+
94
+ # Ten lines of context, custom heading
95
+ cov2md -c 10 -t "Uncovered @ abc123" \
96
+ -r "176-181" -i ./src/index.js -o ./cov.md
97
+
98
+ # Diff-style gutter, with a reproduce hint
99
+ cov2md -r "10-20" -i ./src/client.js -o ./cov.md \
100
+ --highlight gutter \
101
+ --command "npm test && npx c8 report --reporter=text"
102
+
103
+ # Force Python highlighting for a file with an unknown extension
104
+ cov2md --fence python -r "10-20" -i ./script -o ./cov.md
105
+
106
+ # Overwrite an existing output file on purpose
107
+ cov2md -r "1-5" -i ./src/index.js -o ./existing.md --force
108
+ ```
109
+
110
+ ### Output format
111
+
112
+ The document has one top-level heading (customisable via `--title`),
113
+ a short metadata block, then one `## R1 · line 56` or
114
+ `## R1 · lines 111–112` section per normalised range. Each section
115
+ contains a fenced code block with the language inferred from the file
116
+ extension, lines from `start - contextLines` through
117
+ `end + contextLines` (clamped to the file bounds), and markers on
118
+ uncovered lines (controlled by `--highlight`).
119
+
120
+ The metadata block looks like this:
121
+
122
+ ```text
123
+ Source: `src/client.js`
124
+ Reproduce: `npm test && npx c8 report`
125
+
126
+ 3 ranges · one contiguous uncovered block each · sorted by line
127
+ Labels R1..RN are assigned per run and may change when lines shift.
128
+ ```
129
+
130
+ - **`Source:`** is the input path. By default it is printed **relative to
131
+ the current working directory** with forward slashes, so it is portable
132
+ across machines and does not leak local file-system structure. Use
133
+ `--absolute-path` to print the absolute path instead.
134
+ - **`Reproduce:`** appears only when `--command` is given. Backticks and
135
+ newlines inside the command are replaced with single quotes and spaces
136
+ respectively to keep the Markdown valid.
137
+ - **`N range(s) · …`** states the count and the range convention.
138
+ - **`Labels R1..RN …`** warns that section labels are per-run and should
139
+ not be treated as stable references across regenerations.
140
+
141
+ ### Highlight modes
142
+
143
+ `--highlight` controls how uncovered lines are marked inside each
144
+ snippet.
145
+
146
+ `comment` (default) keeps every line copy-pasteable and appends a marker
147
+ to the trailing line-number comment on uncovered lines:
148
+
149
+ ```js
150
+ const pattern = ... // 174
151
+ const entries = ... // 175
152
+ for (const item of entries) { // 176 ← UNCOVERED
153
+ if (!item) continue; // 177 ← UNCOVERED
154
+ total += item.weight; // 178 ← UNCOVERED
155
+ } // 179 ← UNCOVERED
156
+ return total; // 180 ← UNCOVERED
157
+ } // 181 ← UNCOVERED
158
+ ```
159
+
160
+ `gutter` moves the line number to the left, right-aligns it, and uses
161
+ `>` for uncovered lines. Reads like a diff, but the snippet is no longer
162
+ directly pasteable into an editor:
163
+
164
+ ```js
165
+ 174 │ const pattern = ...
166
+ 175 │ const entries = ...
167
+ > 176 │ for (const item of entries) {
168
+ > 177 │ if (!item) continue;
169
+ > 178 │ total += item.weight;
170
+ > 179 │ }
171
+ > 180 │ return total;
172
+ > 181 │ }
173
+ 182 │ // (context after)
174
+ ```
175
+
176
+ `none` produces the pre-2.1 snippet format: `// <n>` comments on every
177
+ line, no uncovered marker. Useful when downstream tooling parses the
178
+ snippet and does not expect a marker.
179
+
180
+ ### Ranges format
181
+
182
+ Comma-separated segments; each segment is either `x-y` (inclusive) or a
183
+ single line `x`:
184
+
185
+ ```text
186
+ 176-181,258-270,286-287,305,338-344
187
+ ```
188
+
189
+ Rules:
190
+
191
+ - Whitespace around segments is ignored.
192
+ - Empty segments (`,,`) are silently dropped.
193
+ - **Overlapping and directly adjacent ranges are merged.** `5-7,8-10`
194
+ becomes a single `5-10` block. Coverage tools occasionally report
195
+ overlapping blocks, and rendering them separately duplicates the same
196
+ code.
197
+ - Invalid segments (non-numeric, `end < start`, zero, negative) throw a
198
+ descriptive error before any file is written.
199
+
200
+ ### Output format
201
+
202
+ The document has one top-level heading (customisable via `--title`),
203
+ then one `## Range (start, end)` section per normalised range. Each
204
+ section contains a fenced code block with the language inferred from
205
+ the file extension, lines from `start - contextLines` through
206
+ `end + contextLines` (clamped to the file bounds), and each line
207
+ suffixed with `// <lineNumber>`.
208
+
209
+ ````markdown
210
+ # Coverage: index.js
211
+
212
+ Source: `/abs/path/src/index.js`
213
+
214
+ Ranges: 1
215
+
216
+ ## Range (176, 181)
217
+
218
+ ```js
219
+ const pattern = ... // 174
220
+ const entries = ... // 175
221
+ for (const item of entries) { // 176
222
+ if (!item) continue; // 177
223
+ total += item.weight; // 178
224
+ } // 179
225
+ return total; // 180
226
+ } // 181
227
+ // (context after) // 182
228
+ ```
229
+
230
+ ### Fence language
231
+
232
+ The fence language is detected from the source file extension:
233
+ `.js` → `js`, `.ts` → `ts`, `.tsx` → `tsx`, `.py` → `python`,
234
+ `.go` → `go`, `.rs` → `rust`, `.md` → `markdown`, and so on. Unknown
235
+ extensions fall back to a bare fence. Override with `--fence <lang>` or
236
+ pass `--fence ""` to disable highlighting entirely.
237
+
238
+ ### Fence length
239
+
240
+ If a snippet contains backtick runs, the fence automatically grows to be
241
+ one backtick longer than the longest run inside the block. Source code
242
+ containing literal ` ``` ` (for example, Markdown fixtures or shell
243
+ scripts that print fences) will not break the rendered document.
244
+
245
+ ## Safety guarantees
246
+
247
+ - **Named arguments only.** A stray positional argument is a hard error.
248
+ - **No silent overwrites.** An existing `--output` file is left intact
249
+ unless `--force` is given.
250
+ - **No input/output collision.** `--input` and `--output` that resolve
251
+ to the same file are rejected, even with `--force`.
252
+ - **Pre-flight validation.** `--input` must exist and be a regular file;
253
+ `--ranges` must yield at least one range; all checks run before any
254
+ file is opened for writing.
255
+ - **Clean errors.** Failures print a single message to stderr and exit
256
+ with code `1` — no stack traces.
257
+
258
+ ## Programmatic API
259
+
260
+ ```js
261
+ import {
262
+ parseRanges,
263
+ normalizeRanges,
264
+ detectFenceLanguage,
265
+ buildMarkdown,
266
+ } from '@supercat1337/coverage-to-markdown';
267
+ ```
268
+ ````
269
+
270
+ ### `parseRanges(input: string): Range[]`
271
+
272
+ Pure parser: splits a range string into `{ start, end }` objects.
273
+ Throws on invalid input. Does **not** merge overlapping or adjacent
274
+ ranges — that's `normalizeRanges`'s job.
275
+
276
+ ```js
277
+ parseRanges('176-181,305');
278
+ // => [
279
+ // { start: 176, end: 181 },
280
+ // { start: 305, end: 305 },
281
+ // ]
282
+ ```
283
+
284
+ ### `normalizeRanges(ranges: Range[]): Range[]`
285
+
286
+ Sorts ranges by start and merges overlapping or directly adjacent ones.
287
+
288
+ ```js
289
+ normalizeRanges([
290
+ { start: 5, end: 7 },
291
+ { start: 8, end: 10 },
292
+ { start: 15, end: 15 },
293
+ ]);
294
+ // => [
295
+ // { start: 5, end: 10 },
296
+ // { start: 15, end: 15 },
297
+ // ]
298
+ ```
299
+
300
+ ### `detectFenceLanguage(filePath: string): string`
301
+
302
+ Maps a file extension to a Markdown fence language identifier. Returns
303
+ an empty string for unknown extensions or dotfiles. Handles Windows
304
+ paths and is case-insensitive.
305
+
306
+ ```js
307
+ detectFenceLanguage('/abs/path/file.ts'); // => 'ts'
308
+ detectFenceLanguage('C:\\foo\\bar.py'); // => 'python'
309
+ detectFenceLanguage('file.unknownext'); // => ''
310
+ ```
311
+
312
+ ### `buildMarkdown(sourcePath, lines, ranges, options?): string`
313
+
314
+ Builds the Markdown document. Normalizes ranges internally before
315
+ rendering, so overlapping input produces a single merged section.
316
+
317
+ `options` (all optional):
318
+
319
+ - `contextLines?: number` — lines of context before and after each range (default `2`).
320
+ - `title?: string` — top-level heading text (default `Coverage: <basename>`).
321
+ - `fence?: string` — fence language override. Pass `''` to disable highlighting.
322
+
323
+ ```js
324
+ import { readFileSync } from 'node:fs';
325
+ import { parseRanges, buildMarkdown } from '@supercat1337/coverage-to-markdown';
326
+
327
+ const content = readFileSync('./src/index.js', 'utf8');
328
+ const lines = content.split('\n').map(line => line.replace(/\r$/, ''));
329
+ const md = buildMarkdown('./src/index.js', lines, parseRanges('10-12,20'), {
330
+ contextLines: 5,
331
+ title: 'My review notes',
332
+ });
333
+ ```
334
+
335
+ ### Types
336
+
337
+ Public types live in `src/types.d.ts`:
338
+
339
+ ```ts
340
+ export interface Range {
341
+ start: number;
342
+ end: number;
343
+ }
344
+
345
+ export interface BuildOptions {
346
+ contextLines?: number;
347
+ title?: string;
348
+ fence?: string;
349
+ }
350
+ ```
351
+
352
+ ## Integrating with coverage tools
353
+
354
+ ### `c8`
355
+
356
+ ```bash
357
+ npx c8 --reporter=text --reporter=json-summary npm test
358
+ ```
359
+
360
+ `c8` doesn't emit per-line ranges as a single string, so the common
361
+ workflow is: open the HTML report, copy the offending line numbers, and
362
+ pass them to `cov2md`.
363
+
364
+ ### `nyc` / `istanbul`
365
+
366
+ ```bash
367
+ npx nyc --reporter=json npm test
368
+ ```
369
+
370
+ The per-file JSON report contains `statementMap` / `fnMap` / `branchMap`
371
+ that you can diff against the `s` / `f` / `b` counts to derive uncovered
372
+ lines, then join them into a range string and hand it over.
373
+
374
+ ## Limitations
375
+
376
+ - **Multi-line template literals:** the inline `// <n>` comment is
377
+ appended as plain text. If a snippet lands inside a multi-line
378
+ template literal, the comment becomes part of the string value.
379
+ - **CRLF:** trailing `\r` characters are stripped before the line-number
380
+ comment is appended, so Windows-formatted files render correctly.
381
+ - **Out-of-bounds ranges:** a range that starts after the end of the
382
+ file produces an empty fence rather than an error. This matches
383
+ coverage tools that occasionally report phantom lines.
384
+
385
+ ## License
386
+
387
+ MIT © Albert Bazaleev
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
- {
2
- "name": "@supercat1337/coverage-to-markdown",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@supercat1337/coverage-to-markdown",
3
+ "version": "1.1.0",
4
+ "description": "Convert coverage ranges into markdown snippets with line numbers, surrounding context lines, and automatic fence language detection.",
5
+ "type": "module",
6
+ "bin": {
7
+ "coverage-to-markdown": "./src/coverage-to-markdown.js",
8
+ "cov2md": "./src/coverage-to-markdown.js"
9
+ },
10
+ "main": "./src/coverage-to-markdown.js",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./src/types.d.ts",
14
+ "default": "./src/coverage-to-markdown.js"
15
+ }
16
+ },
17
+ "engines": {
18
+ "node": ">=18"
19
+ },
20
+ "files": [
21
+ "src/"
22
+ ],
23
+ "scripts": {
24
+ "start": "node ./src/coverage-to-markdown.js",
25
+ "test": "node --test",
26
+ "lint": "eslint .",
27
+ "prepublishOnly": "npm test && npm run lint"
28
+ },
29
+ "keywords": [
30
+ "coverage",
31
+ "test-coverage",
32
+ "code-coverage",
33
+ "c8",
34
+ "istanbul",
35
+ "nyc",
36
+ "markdown",
37
+ "uncovered-lines",
38
+ "line-ranges",
39
+ "coverage-reporter",
40
+ "cli"
41
+ ],
42
+ "author": "Albert Bazaleev",
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/supercat1337/coverage-to-markdown.git"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/supercat1337/coverage-to-markdown/issues"
50
+ },
51
+ "homepage": "https://github.com/supercat1337/coverage-to-markdown#readme",
52
+ "dependencies": {},
53
+ "devDependencies": {
54
+ "eslint-plugin-jsdoc": "^63.3.3"
55
+ }
56
+ }
@@ -0,0 +1,649 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Coverage-to-markdown utility.
4
+ *
5
+ * Reads a source file and a coverage range string like
6
+ * "176-181,258-270,305" and writes a markdown document where each range
7
+ * is rendered as a fenced code block with configurable context lines
8
+ * around it, an R-label, and uncovered lines marked according to the
9
+ * `highlight` option.
10
+ *
11
+ * The fence language is inferred from the source file extension, and the
12
+ * fence length grows automatically when the snippet contains backtick
13
+ * runs so that markdown fences never break.
14
+ */
15
+ import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
16
+ import { dirname, extname, isAbsolute, relative, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { parseArgs } from 'node:util';
19
+
20
+ /**
21
+ * @typedef {import('./types.js').Range} Range
22
+ * @typedef {import('./types.js').BuildOptions} BuildOptions
23
+ * @typedef {import('./types.js').HighlightMode} HighlightMode
24
+ */
25
+
26
+ /** @type {number} */
27
+ const DEFAULT_CONTEXT_LINES = 2;
28
+
29
+ /** @type {number} */
30
+ const MIN_FENCE_LENGTH = 3;
31
+
32
+ /** @type {HighlightMode[]} */
33
+ const VALID_HIGHLIGHTS = ['none', 'comment', 'gutter'];
34
+
35
+ /**
36
+ * File extension to markdown fence language identifier.
37
+ * @type {Record<string, string>}
38
+ */
39
+ const EXTENSION_TO_FENCE = {
40
+ '.js': 'js',
41
+ '.mjs': 'js',
42
+ '.cjs': 'js',
43
+ '.jsx': 'jsx',
44
+ '.ts': 'ts',
45
+ '.mts': 'ts',
46
+ '.cts': 'ts',
47
+ '.tsx': 'tsx',
48
+ '.py': 'python',
49
+ '.rb': 'ruby',
50
+ '.go': 'go',
51
+ '.rs': 'rust',
52
+ '.java': 'java',
53
+ '.kt': 'kotlin',
54
+ '.kts': 'kotlin',
55
+ '.swift': 'swift',
56
+ '.c': 'c',
57
+ '.h': 'c',
58
+ '.cc': 'cpp',
59
+ '.cpp': 'cpp',
60
+ '.cxx': 'cpp',
61
+ '.hpp': 'cpp',
62
+ '.cs': 'csharp',
63
+ '.php': 'php',
64
+ '.sh': 'bash',
65
+ '.bash': 'bash',
66
+ '.zsh': 'bash',
67
+ '.ps1': 'powershell',
68
+ '.sql': 'sql',
69
+ '.html': 'html',
70
+ '.htm': 'html',
71
+ '.css': 'css',
72
+ '.scss': 'scss',
73
+ '.json': 'json',
74
+ '.yaml': 'yaml',
75
+ '.yml': 'yaml',
76
+ '.toml': 'toml',
77
+ '.md': 'markdown',
78
+ '.xml': 'xml',
79
+ '.lua': 'lua',
80
+ '.dart': 'dart',
81
+ '.ex': 'elixir',
82
+ '.exs': 'elixir',
83
+ '.erl': 'erlang',
84
+ '.hs': 'haskell',
85
+ '.clj': 'clojure',
86
+ '.vue': 'vue',
87
+ '.svelte': 'svelte',
88
+ };
89
+
90
+ const HELP_TEXT = `coverage-to-markdown — convert coverage ranges to markdown snippets
91
+
92
+ Usage:
93
+ coverage-to-markdown --ranges <ranges> --input <source-file> --output <output-md> [options]
94
+
95
+ Required arguments:
96
+ -r, --ranges <ranges> Comma-separated list of line ranges (e.g. "1-5,10,20-25")
97
+ -i, --input <path> Path to the source file whose lines will be extracted
98
+ -o, --output <path> Path to the markdown file that will be written
99
+
100
+ Options:
101
+ -c, --context <n> Lines of context before and after each range (default: 2)
102
+ -t, --title <s> Top-level heading text (default: "Coverage: <basename>")
103
+ --fence <lang> Override fence language (default: from file extension)
104
+ --highlight <mode> Marker for uncovered lines: none | comment | gutter (default: comment)
105
+ --command <cmd> Add a "Reproduce:" line with the given command
106
+ --absolute-path Print the source path as absolute (default: relative to cwd)
107
+ -f, --force Overwrite the output file if it already exists
108
+ -q, --quiet Suppress the success summary on stdout
109
+ -h, --help Show this help and exit
110
+ -v, --version Print version and exit
111
+
112
+ Safety:
113
+ All arguments must be named. Positional arguments are rejected on
114
+ purpose so that a forgotten flag cannot silently overwrite the input
115
+ file. The tool refuses to write over an existing file unless --force
116
+ is given, and rejects --input and --output pointing at the same path.
117
+
118
+ Examples:
119
+ coverage-to-markdown --ranges "176-181,258-270" --input ./src/index.js --output ./coverage.md
120
+ coverage-to-markdown -r "10-20" -i ./src/util.ts -o ./ctx.md -c 5
121
+ coverage-to-markdown -r "1-5" -i ./src/index.js -o ./existing.md --force
122
+ coverage-to-markdown -r "10-20" -i ./src/client.js -o ./cov.md \\
123
+ --highlight gutter --command "npm test && npx c8 report"
124
+ `;
125
+
126
+ /**
127
+ * Parse a coverage range string into an array of ranges.
128
+ * @param {string} input
129
+ * @returns {Range[]}
130
+ */
131
+ function parseRanges(input) {
132
+ return input
133
+ .split(',')
134
+ .map(segment => segment.trim())
135
+ .filter(segment => segment.length > 0)
136
+ .map(segment => parseRangeSegment(segment));
137
+ }
138
+
139
+ /**
140
+ * @param {string} segment
141
+ * @returns {Range}
142
+ */
143
+ function parseRangeSegment(segment) {
144
+ const dashIndex = segment.indexOf('-');
145
+ if (dashIndex === -1) {
146
+ const line = parseLineNumber(segment);
147
+ return { start: line, end: line };
148
+ }
149
+ const start = parseLineNumber(segment.slice(0, dashIndex));
150
+ const end = parseLineNumber(segment.slice(dashIndex + 1));
151
+ if (end < start) {
152
+ throw new Error(`Invalid range (end < start): "${segment}"`);
153
+ }
154
+ return { start, end };
155
+ }
156
+
157
+ /**
158
+ * @param {string} raw
159
+ * @returns {number}
160
+ */
161
+ function parseLineNumber(raw) {
162
+ const value = Number(raw);
163
+ if (!Number.isInteger(value) || value < 1) {
164
+ throw new Error(`Invalid line number: "${raw}"`);
165
+ }
166
+ return value;
167
+ }
168
+
169
+ /**
170
+ * Sort ranges and merge overlapping or directly adjacent ones.
171
+ * @param {Range[]} ranges
172
+ * @returns {Range[]}
173
+ */
174
+ function normalizeRanges(ranges) {
175
+ if (!Array.isArray(ranges) || ranges.length === 0) {
176
+ return [];
177
+ }
178
+ const sorted = [...ranges].sort((a, b) => a.start - b.start || a.end - b.end);
179
+ const merged = [{ start: sorted[0].start, end: sorted[0].end }];
180
+ for (let i = 1; i < sorted.length; i += 1) {
181
+ const last = merged[merged.length - 1];
182
+ const current = sorted[i];
183
+ if (current.start <= last.end + 1) {
184
+ if (current.end > last.end) {
185
+ last.end = current.end;
186
+ }
187
+ } else {
188
+ merged.push({ start: current.start, end: current.end });
189
+ }
190
+ }
191
+ return merged;
192
+ }
193
+
194
+ /**
195
+ * @param {string} filePath
196
+ * @returns {string}
197
+ */
198
+ function detectFenceLanguage(filePath) {
199
+ const normalized = filePath.replace(/\\/g, '/');
200
+ const ext = extname(normalized).toLowerCase();
201
+ return EXTENSION_TO_FENCE[ext] ?? '';
202
+ }
203
+
204
+ /**
205
+ * @param {string[]} lines
206
+ * @param {number} start
207
+ * @param {number} end
208
+ * @returns {number}
209
+ */
210
+ function pickFenceLength(lines, start, end) {
211
+ let maxRun = 0;
212
+ const from = Math.max(0, start - 1);
213
+ const to = Math.min(end, lines.length);
214
+ for (let i = from; i < to; i += 1) {
215
+ const line = lines[i] ?? '';
216
+ const runs = line.match(/`+/g);
217
+ if (runs) {
218
+ for (const run of runs) {
219
+ if (run.length > maxRun) {
220
+ maxRun = run.length;
221
+ }
222
+ }
223
+ }
224
+ }
225
+ return Math.max(MIN_FENCE_LENGTH, maxRun + 1);
226
+ }
227
+
228
+ /**
229
+ * @param {string} content
230
+ * @returns {string[]}
231
+ */
232
+ function splitLines(content) {
233
+ return content.split('\n').map(line => line.replace(/\r$/, ''));
234
+ }
235
+
236
+ /**
237
+ * @param {string[]} lines
238
+ * @param {Range} range
239
+ * @param {number} contextLines
240
+ * @returns {{ start: number, end: number }}
241
+ */
242
+ function snippetBounds(lines, range, contextLines) {
243
+ return {
244
+ start: Math.max(1, range.start - contextLines),
245
+ end: Math.min(lines.length, range.end + contextLines),
246
+ };
247
+ }
248
+
249
+ /**
250
+ * Format a range as a heading label: "line 56" or "lines 111–112".
251
+ * Uses an en-dash between range endpoints.
252
+ * @param {Range} range
253
+ * @returns {string}
254
+ */
255
+ function formatRangeLabel(range) {
256
+ if (range.start === range.end) {
257
+ return `line ${range.start}`;
258
+ }
259
+ return `lines ${range.start}–${range.end}`;
260
+ }
261
+
262
+ /**
263
+ * Render snippet in `none` mode: every line gets `// <n>`, no marker.
264
+ * @param {string[]} lines
265
+ * @param {number} snippetStart
266
+ * @param {number} snippetEnd
267
+ * @returns {string}
268
+ */
269
+ function renderSnippetNone(lines, snippetStart, snippetEnd) {
270
+ const parts = [];
271
+ for (let n = snippetStart; n <= snippetEnd; n += 1) {
272
+ parts.push(`${lines[n - 1] ?? ''} // ${n}`);
273
+ }
274
+ return parts.join('\n');
275
+ }
276
+
277
+ /**
278
+ * Render snippet in `comment` mode: context lines get `// <n>`,
279
+ * uncovered lines get `// <n> ← UNCOVERED`.
280
+ * @param {string[]} lines
281
+ * @param {Range} range
282
+ * @param {number} snippetStart
283
+ * @param {number} snippetEnd
284
+ * @returns {string}
285
+ */
286
+ function renderSnippetComment(lines, range, snippetStart, snippetEnd) {
287
+ const parts = [];
288
+ for (let n = snippetStart; n <= snippetEnd; n += 1) {
289
+ const isUncovered = n >= range.start && n <= range.end;
290
+ const marker = isUncovered ? ' ← UNCOVERED' : '';
291
+ parts.push(`${lines[n - 1] ?? ''} // ${n}${marker}`);
292
+ }
293
+ return parts.join('\n');
294
+ }
295
+
296
+ /**
297
+ * Render snippet in `gutter` mode: line number on the left with `│`
298
+ * separator, `>` for uncovered lines. Line numbers are right-aligned
299
+ * to the width of the largest number in the snippet.
300
+ * @param {string[]} lines
301
+ * @param {Range} range
302
+ * @param {number} snippetStart
303
+ * @param {number} snippetEnd
304
+ * @returns {string}
305
+ */
306
+ function renderSnippetGutter(lines, range, snippetStart, snippetEnd) {
307
+ const width = String(snippetEnd).length;
308
+ const parts = [];
309
+ for (let n = snippetStart; n <= snippetEnd; n += 1) {
310
+ const isUncovered = n >= range.start && n <= range.end;
311
+ const prefix = isUncovered ? '> ' : ' ';
312
+ const padded = String(n).padStart(width, ' ');
313
+ parts.push(`${prefix}${padded} │ ${lines[n - 1] ?? ''}`);
314
+ }
315
+ return parts.join('\n');
316
+ }
317
+
318
+ /**
319
+ * Dispatch to the correct snippet renderer.
320
+ * @param {string[]} lines
321
+ * @param {Range} range
322
+ * @param {number} snippetStart
323
+ * @param {number} snippetEnd
324
+ * @param {HighlightMode} highlight
325
+ * @returns {string}
326
+ */
327
+ function renderSnippet(lines, range, snippetStart, snippetEnd, highlight) {
328
+ if (highlight === 'gutter') {
329
+ return renderSnippetGutter(lines, range, snippetStart, snippetEnd);
330
+ }
331
+ if (highlight === 'none') {
332
+ return renderSnippetNone(lines, snippetStart, snippetEnd);
333
+ }
334
+ return renderSnippetComment(lines, range, snippetStart, snippetEnd);
335
+ }
336
+
337
+ /**
338
+ * Build the markdown document body for all ranges.
339
+ * @param {string} sourcePath
340
+ * @param {string[]} lines
341
+ * @param {Range[]} ranges
342
+ * @param {BuildOptions} [options]
343
+ * @returns {string}
344
+ */
345
+ function buildMarkdown(sourcePath, lines, ranges, options = {}) {
346
+ const contextLines = options.contextLines ?? DEFAULT_CONTEXT_LINES;
347
+ if (!Number.isInteger(contextLines) || contextLines < 0) {
348
+ throw new Error(`Invalid contextLines: ${contextLines}`);
349
+ }
350
+
351
+ const highlight = options.highlight ?? 'comment';
352
+ if (!VALID_HIGHLIGHTS.includes(highlight)) {
353
+ throw new Error(
354
+ `Invalid highlight mode: "${highlight}". ` +
355
+ `Expected one of: ${VALID_HIGHLIGHTS.join(', ')}.`
356
+ );
357
+ }
358
+
359
+ const normalized = normalizeRanges(ranges);
360
+ const title = options.title ?? `Coverage: ${basenameOf(sourcePath)}`;
361
+ const fenceLang = options.fence !== undefined ? options.fence : detectFenceLanguage(sourcePath);
362
+
363
+ const headerLines = [`# ${title}`, '', `Source: \`${sourcePath}\``];
364
+
365
+ if (typeof options.command === 'string' && options.command.length > 0) {
366
+ const safeCommand = options.command.replace(/`/g, "'").replace(/\r?\n/g, ' ');
367
+ headerLines.push(`Reproduce: \`${safeCommand}\``);
368
+ }
369
+
370
+ headerLines.push('');
371
+
372
+ const count = normalized.length;
373
+ const noun = count === 1 ? 'range' : 'ranges';
374
+ headerLines.push(`${count} ${noun} · one contiguous uncovered block each · sorted by line`);
375
+ headerLines.push('Labels R1..RN are assigned per run and may change when lines shift.');
376
+
377
+ const header = headerLines.join('\n');
378
+
379
+ const sections = normalized.map((range, index) => {
380
+ const bounds = snippetBounds(lines, range, contextLines);
381
+ const fenceLength = pickFenceLength(lines, bounds.start, bounds.end);
382
+ const fence = '`'.repeat(fenceLength);
383
+ const snippet = renderSnippet(lines, range, bounds.start, bounds.end, highlight);
384
+
385
+ const block = [`${fence}${fenceLang}`];
386
+ if (snippet.length > 0) {
387
+ block.push(snippet);
388
+ }
389
+ block.push(fence);
390
+
391
+ return [`## R${index + 1} · ${formatRangeLabel(range)}`, '', ...block].join('\n');
392
+ });
393
+
394
+ return [header, ...sections].join('\n\n') + '\n';
395
+ }
396
+
397
+ /**
398
+ * Take the final path component regardless of the separator style.
399
+ * @param {string} filePath
400
+ * @returns {string}
401
+ */
402
+ function basenameOf(filePath) {
403
+ const normalized = filePath.replace(/\\/g, '/');
404
+ const lastSlash = normalized.lastIndexOf('/');
405
+ return lastSlash >= 0 ? normalized.slice(lastSlash + 1) : normalized;
406
+ }
407
+
408
+ /**
409
+ * Return a display form of `absPath`: relative to cwd with forward
410
+ * slashes when possible, otherwise the original absolute path.
411
+ * @param {string} absPath
412
+ * @returns {string}
413
+ */
414
+ function toRelativeDisplay(absPath) {
415
+ const rel = relative(process.cwd(), absPath);
416
+ if (rel === '' || isAbsolute(rel)) {
417
+ return absPath;
418
+ }
419
+ return rel.replace(/\\/g, '/');
420
+ }
421
+
422
+ /**
423
+ * Read the package version from package.json.
424
+ * @returns {string}
425
+ */
426
+ function readVersion() {
427
+ const pkgUrl = new URL('../package.json', import.meta.url);
428
+ const pkg = JSON.parse(readFileSync(pkgUrl, 'utf8'));
429
+ return pkg.version;
430
+ }
431
+
432
+ /**
433
+ * @param {string} raw
434
+ * @returns {number}
435
+ */
436
+ function parseContextOption(raw) {
437
+ const value = Number(raw);
438
+ if (!Number.isInteger(value) || value < 0) {
439
+ throw new Error(`Invalid --context value: "${raw}" (expected a non-negative integer)`);
440
+ }
441
+ return value;
442
+ }
443
+
444
+ /**
445
+ * @param {string} raw
446
+ * @returns {HighlightMode}
447
+ */
448
+ function parseHighlightOption(raw) {
449
+ if (!VALID_HIGHLIGHTS.includes(raw)) {
450
+ throw new Error(
451
+ `Invalid --highlight value: "${raw}". ` +
452
+ `Expected one of: ${VALID_HIGHLIGHTS.join(', ')}.`
453
+ );
454
+ }
455
+ return /** @type {HighlightMode} */ (raw);
456
+ }
457
+
458
+ /**
459
+ * @param {string[]} positionals
460
+ * @returns {void}
461
+ */
462
+ function rejectPositionals(positionals) {
463
+ if (positionals.length === 0) {
464
+ return;
465
+ }
466
+ throw new Error(
467
+ `Unexpected positional argument(s): ${positionals.join(' ')}. ` +
468
+ 'All arguments must be named. Run with --help for usage.'
469
+ );
470
+ }
471
+
472
+ /**
473
+ * @param {Record<string, unknown>} values
474
+ * @returns {{ ranges: string, input: string, output: string }}
475
+ */
476
+ function readRequiredFlags(values) {
477
+ const missing = [];
478
+ if (values.ranges === undefined) {missing.push('--ranges');}
479
+ if (values.input === undefined) {missing.push('--input');}
480
+ if (values.output === undefined) {missing.push('--output');}
481
+ if (missing.length > 0) {
482
+ throw new Error(
483
+ `Missing required argument(s): ${missing.join(', ')}. ` + 'Run with --help for usage.'
484
+ );
485
+ }
486
+ return {
487
+ ranges: String(values.ranges),
488
+ input: String(values.input),
489
+ output: String(values.output),
490
+ };
491
+ }
492
+
493
+ /**
494
+ * Validate input and output paths before any file is written.
495
+ * @param {string} sourcePath
496
+ * @param {string} outputPath
497
+ * @param {boolean} force
498
+ * @returns {void}
499
+ */
500
+ function guardFilePaths(sourcePath, outputPath, force) {
501
+ if (sourcePath === outputPath) {
502
+ throw new Error(
503
+ '--input and --output must point at different files. ' +
504
+ 'Refusing to overwrite the source file.'
505
+ );
506
+ }
507
+ if (!existsSync(sourcePath)) {
508
+ throw new Error(`Input file not found: ${sourcePath}`);
509
+ }
510
+ if (!statSync(sourcePath).isFile()) {
511
+ throw new Error(`Input path is not a regular file: ${sourcePath}`);
512
+ }
513
+ if (existsSync(outputPath) && !force) {
514
+ throw new Error(
515
+ `Output file already exists: ${outputPath}. ` + 'Pass --force to overwrite it.'
516
+ );
517
+ }
518
+ }
519
+
520
+ /**
521
+ * Check whether the current module was started as the main script.
522
+ * Compares real (symlink-resolved) paths instead of file URLs, because
523
+ * on Windows process.argv[1] and import.meta.url can disagree on drive
524
+ * letter case, on short (8.3) names, and on junction resolution when
525
+ * launched through an npm bin shim (`npm link`).
526
+ * @returns {boolean}
527
+ */
528
+ function isMainModule() {
529
+ const entry = process.argv[1];
530
+ if (entry === undefined) {
531
+ return false;
532
+ }
533
+ try {
534
+ const selfPath = realpathSync(fileURLToPath(import.meta.url));
535
+ const entryPath = realpathSync(resolve(entry));
536
+ if (process.platform === 'win32') {
537
+ return selfPath.toLowerCase() === entryPath.toLowerCase();
538
+ }
539
+ return selfPath === entryPath;
540
+ } catch {
541
+ return false;
542
+ }
543
+ }
544
+
545
+ /**
546
+ * CLI entry point.
547
+ * @param {string[]} argv
548
+ * @returns {void}
549
+ */
550
+ function main(argv) {
551
+ try {
552
+ const { values, positionals } = parseArgs({
553
+ args: argv,
554
+ allowPositionals: true,
555
+ options: {
556
+ ranges: { type: 'string', short: 'r' },
557
+ input: { type: 'string', short: 'i' },
558
+ output: { type: 'string', short: 'o' },
559
+ context: { type: 'string', short: 'c' },
560
+ title: { type: 'string', short: 't' },
561
+ fence: { type: 'string' },
562
+ highlight: { type: 'string' },
563
+ command: { type: 'string' },
564
+ force: { type: 'boolean', short: 'f' },
565
+ quiet: { type: 'boolean', short: 'q' },
566
+ 'absolute-path': { type: 'boolean' },
567
+ help: { type: 'boolean', short: 'h' },
568
+ version: { type: 'boolean', short: 'v' },
569
+ },
570
+ });
571
+
572
+ if (values.help) {
573
+ process.stdout.write(HELP_TEXT);
574
+ return;
575
+ }
576
+
577
+ if (values.version) {
578
+ process.stdout.write(`${readVersion()}\n`);
579
+ return;
580
+ }
581
+
582
+ rejectPositionals(positionals);
583
+ const flags = readRequiredFlags(values);
584
+
585
+ const contextLines =
586
+ values.context !== undefined
587
+ ? parseContextOption(values.context)
588
+ : DEFAULT_CONTEXT_LINES;
589
+ const highlight =
590
+ values.highlight !== undefined ? parseHighlightOption(values.highlight) : 'comment';
591
+
592
+ const sourcePath = resolve(flags.input);
593
+ const outputPath = resolve(flags.output);
594
+ guardFilePaths(sourcePath, outputPath, values.force === true);
595
+
596
+ const outputDir = dirname(outputPath);
597
+ if (!existsSync(outputDir)) {
598
+ throw new Error(
599
+ `Output directory does not exist: ${outputDir}. ` +
600
+ 'Create it first, or choose a different --output path.'
601
+ );
602
+ }
603
+
604
+ const rawRanges = parseRanges(flags.ranges);
605
+ if (rawRanges.length === 0) {
606
+ throw new Error('--ranges produced no ranges; check the input string.');
607
+ }
608
+
609
+ const content = readFileSync(sourcePath, 'utf8');
610
+ const lines = splitLines(content);
611
+
612
+ const displayPath =
613
+ values['absolute-path'] === true ? sourcePath : toRelativeDisplay(sourcePath);
614
+
615
+ const markdown = buildMarkdown(displayPath, lines, rawRanges, {
616
+ contextLines,
617
+ highlight,
618
+ title: values.title,
619
+ fence: values.fence,
620
+ command: values.command,
621
+ });
622
+
623
+ writeFileSync(outputPath, markdown, 'utf8');
624
+ const written = statSync(outputPath);
625
+
626
+ if (!values.quiet) {
627
+ const count = normalizeRanges(rawRanges).length;
628
+ process.stdout.write(
629
+ [
630
+ 'coverage-to-markdown: wrote report',
631
+ ` input: ${sourcePath}`,
632
+ ` output: ${outputPath}`,
633
+ ` ranges: ${count} (from ${rawRanges.length} parsed)`,
634
+ ` size: ${written.size} bytes`,
635
+ ].join('\n') + '\n'
636
+ );
637
+ }
638
+ } catch (error) {
639
+ const message = error instanceof Error ? error.message : String(error);
640
+ process.stderr.write(`coverage-to-markdown: error: ${message}\n`);
641
+ process.exit(1);
642
+ }
643
+ }
644
+
645
+ export { parseRanges, normalizeRanges, detectFenceLanguage, buildMarkdown };
646
+
647
+ if (isMainModule()) {
648
+ main(process.argv.slice(2));
649
+ }
package/src/types.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Inclusive line range in a source file (1-based).
3
+ */
4
+ export interface Range {
5
+ /** First line of the range. */
6
+ start: number;
7
+ /** Last line of the range. */
8
+ end: number;
9
+ }
10
+
11
+ /**
12
+ * How uncovered lines are marked inside rendered snippets.
13
+ *
14
+ * - `none` — no marker, just line-number comments (pre-2.1 snippet format).
15
+ * - `comment` — append `← UNCOVERED` to the line-number comment on
16
+ * uncovered lines; keeps lines copy-pasteable.
17
+ * - `gutter` — put the line number on the left with a `│` separator and
18
+ * use `>` for uncovered lines; reads like a diff.
19
+ */
20
+ export type HighlightMode = 'none' | 'comment' | 'gutter';
21
+
22
+ /**
23
+ * Options for `buildMarkdown`.
24
+ */
25
+ export interface BuildOptions {
26
+ /** Lines of context before and after each range. Default: 2. */
27
+ contextLines?: number;
28
+ /** Custom top-level heading text. Default: `Coverage: <basename>`. */
29
+ title?: string;
30
+ /** Fence language override. Default: detected from the file extension. */
31
+ fence?: string;
32
+ /** How uncovered lines are marked. Default: `comment`. */
33
+ highlight?: HighlightMode;
34
+ /**
35
+ * Command that reproduces the coverage report. When set, a
36
+ * `Reproduce:` line is added to the header. Backticks and newlines
37
+ * are sanitised to keep the Markdown valid.
38
+ */
39
+ command?: string;
40
+ }