@supercat1337/coverage-to-markdown 0.0.0-stage → 1.0.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,308 @@
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
+ | `--force` | `-f` | | Overwrite the output file if it exists | off |
78
+ | `--help` | `-h` | | Show usage and exit | |
79
+ | `--version` | `-v` | | Print the version and exit | |
80
+
81
+ ### Examples
82
+
83
+ ```bash
84
+ # Default context of two lines
85
+ cov2md \
86
+ --ranges "176-181,258-270,286-287" \
87
+ --input ./src/index.js \
88
+ --output ./coverage.md
89
+
90
+ # Ten lines of context, custom heading
91
+ cov2md -c 10 -t "Uncovered @ abc123" \
92
+ -r "176-181" -i ./src/index.js -o ./cov.md
93
+
94
+ # Force Python highlighting for a file with an unknown extension
95
+ cov2md --fence python -r "10-20" -i ./script -o ./cov.md
96
+
97
+ # Overwrite an existing output file on purpose
98
+ cov2md -r "1-5" -i ./src/index.js -o ./existing.md --force
99
+ ```
100
+
101
+ ### Ranges format
102
+
103
+ Comma-separated segments; each segment is either `x-y` (inclusive) or a
104
+ single line `x`:
105
+
106
+ ```text
107
+ 176-181,258-270,286-287,305,338-344
108
+ ```
109
+
110
+ Rules:
111
+
112
+ - Whitespace around segments is ignored.
113
+ - Empty segments (`,,`) are silently dropped.
114
+ - **Overlapping and directly adjacent ranges are merged.** `5-7,8-10`
115
+ becomes a single `5-10` block. Coverage tools occasionally report
116
+ overlapping blocks, and rendering them separately duplicates the same
117
+ code.
118
+ - Invalid segments (non-numeric, `end < start`, zero, negative) throw a
119
+ descriptive error before any file is written.
120
+
121
+ ### Output format
122
+
123
+ The document has one top-level heading (customisable via `--title`),
124
+ then one `## Range (start, end)` section per normalised range. Each
125
+ section contains a fenced code block with the language inferred from
126
+ the file extension, lines from `start - contextLines` through
127
+ `end + contextLines` (clamped to the file bounds), and each line
128
+ suffixed with `// <lineNumber>`.
129
+
130
+ ````markdown
131
+ # Coverage: index.js
132
+
133
+ Source: `/abs/path/src/index.js`
134
+
135
+ Ranges: 1
136
+
137
+ ## Range (176, 181)
138
+
139
+ ```js
140
+ const pattern = ... // 174
141
+ const entries = ... // 175
142
+ for (const item of entries) { // 176
143
+ if (!item) continue; // 177
144
+ total += item.weight; // 178
145
+ } // 179
146
+ return total; // 180
147
+ } // 181
148
+ // (context after) // 182
149
+ ```
150
+
151
+ ### Fence language
152
+
153
+ The fence language is detected from the source file extension:
154
+ `.js` → `js`, `.ts` → `ts`, `.tsx` → `tsx`, `.py` → `python`,
155
+ `.go` → `go`, `.rs` → `rust`, `.md` → `markdown`, and so on. Unknown
156
+ extensions fall back to a bare fence. Override with `--fence <lang>` or
157
+ pass `--fence ""` to disable highlighting entirely.
158
+
159
+ ### Fence length
160
+
161
+ If a snippet contains backtick runs, the fence automatically grows to be
162
+ one backtick longer than the longest run inside the block. Source code
163
+ containing literal ` ``` ` (for example, Markdown fixtures or shell
164
+ scripts that print fences) will not break the rendered document.
165
+
166
+ ## Safety guarantees
167
+
168
+ - **Named arguments only.** A stray positional argument is a hard error.
169
+ - **No silent overwrites.** An existing `--output` file is left intact
170
+ unless `--force` is given.
171
+ - **No input/output collision.** `--input` and `--output` that resolve
172
+ to the same file are rejected, even with `--force`.
173
+ - **Pre-flight validation.** `--input` must exist and be a regular file;
174
+ `--ranges` must yield at least one range; all checks run before any
175
+ file is opened for writing.
176
+ - **Clean errors.** Failures print a single message to stderr and exit
177
+ with code `1` — no stack traces.
178
+
179
+ ## Programmatic API
180
+
181
+ ```js
182
+ import {
183
+ parseRanges,
184
+ normalizeRanges,
185
+ detectFenceLanguage,
186
+ buildMarkdown,
187
+ } from '@supercat1337/coverage-to-markdown';
188
+ ```
189
+ ````
190
+
191
+ ### `parseRanges(input: string): Range[]`
192
+
193
+ Pure parser: splits a range string into `{ start, end }` objects.
194
+ Throws on invalid input. Does **not** merge overlapping or adjacent
195
+ ranges — that's `normalizeRanges`'s job.
196
+
197
+ ```js
198
+ parseRanges('176-181,305');
199
+ // => [
200
+ // { start: 176, end: 181 },
201
+ // { start: 305, end: 305 },
202
+ // ]
203
+ ```
204
+
205
+ ### `normalizeRanges(ranges: Range[]): Range[]`
206
+
207
+ Sorts ranges by start and merges overlapping or directly adjacent ones.
208
+
209
+ ```js
210
+ normalizeRanges([
211
+ { start: 5, end: 7 },
212
+ { start: 8, end: 10 },
213
+ { start: 15, end: 15 },
214
+ ]);
215
+ // => [
216
+ // { start: 5, end: 10 },
217
+ // { start: 15, end: 15 },
218
+ // ]
219
+ ```
220
+
221
+ ### `detectFenceLanguage(filePath: string): string`
222
+
223
+ Maps a file extension to a Markdown fence language identifier. Returns
224
+ an empty string for unknown extensions or dotfiles. Handles Windows
225
+ paths and is case-insensitive.
226
+
227
+ ```js
228
+ detectFenceLanguage('/abs/path/file.ts'); // => 'ts'
229
+ detectFenceLanguage('C:\\foo\\bar.py'); // => 'python'
230
+ detectFenceLanguage('file.unknownext'); // => ''
231
+ ```
232
+
233
+ ### `buildMarkdown(sourcePath, lines, ranges, options?): string`
234
+
235
+ Builds the Markdown document. Normalizes ranges internally before
236
+ rendering, so overlapping input produces a single merged section.
237
+
238
+ `options` (all optional):
239
+
240
+ - `contextLines?: number` — lines of context before and after each range (default `2`).
241
+ - `title?: string` — top-level heading text (default `Coverage: <basename>`).
242
+ - `fence?: string` — fence language override. Pass `''` to disable highlighting.
243
+
244
+ ```js
245
+ import { readFileSync } from 'node:fs';
246
+ import { parseRanges, buildMarkdown } from '@supercat1337/coverage-to-markdown';
247
+
248
+ const content = readFileSync('./src/index.js', 'utf8');
249
+ const lines = content.split('\n').map(line => line.replace(/\r$/, ''));
250
+ const md = buildMarkdown('./src/index.js', lines, parseRanges('10-12,20'), {
251
+ contextLines: 5,
252
+ title: 'My review notes',
253
+ });
254
+ ```
255
+
256
+ ### Types
257
+
258
+ Public types live in `src/types.d.ts`:
259
+
260
+ ```ts
261
+ export interface Range {
262
+ start: number;
263
+ end: number;
264
+ }
265
+
266
+ export interface BuildOptions {
267
+ contextLines?: number;
268
+ title?: string;
269
+ fence?: string;
270
+ }
271
+ ```
272
+
273
+ ## Integrating with coverage tools
274
+
275
+ ### `c8`
276
+
277
+ ```bash
278
+ npx c8 --reporter=text --reporter=json-summary npm test
279
+ ```
280
+
281
+ `c8` doesn't emit per-line ranges as a single string, so the common
282
+ workflow is: open the HTML report, copy the offending line numbers, and
283
+ pass them to `cov2md`.
284
+
285
+ ### `nyc` / `istanbul`
286
+
287
+ ```bash
288
+ npx nyc --reporter=json npm test
289
+ ```
290
+
291
+ The per-file JSON report contains `statementMap` / `fnMap` / `branchMap`
292
+ that you can diff against the `s` / `f` / `b` counts to derive uncovered
293
+ lines, then join them into a range string and hand it over.
294
+
295
+ ## Limitations
296
+
297
+ - **Multi-line template literals:** the inline `// <n>` comment is
298
+ appended as plain text. If a snippet lands inside a multi-line
299
+ template literal, the comment becomes part of the string value.
300
+ - **CRLF:** trailing `\r` characters are stripped before the line-number
301
+ comment is appended, so Windows-formatted files render correctly.
302
+ - **Out-of-bounds ranges:** a range that starts after the end of the
303
+ file produces an empty fence rather than an error. This matches
304
+ coverage tools that occasionally report phantom lines.
305
+
306
+ ## License
307
+
308
+ 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.0.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,551 @@
1
+ #!/usr/bin/env node
2
+
3
+ // @ts-check
4
+
5
+ /**
6
+ * Coverage-to-markdown utility.
7
+ *
8
+ * Reads a source file and a coverage range string like
9
+ * "176-181,258-270,305" and writes a markdown document where each range
10
+ * is rendered as a fenced code block with configurable context lines
11
+ * around it, and each line gets an inline "// <lineNumber>" comment.
12
+ *
13
+ * All CLI arguments are named flags. There is no positional form on
14
+ * purpose: a missing or misplaced positional argument could otherwise
15
+ * silently point the output at the input file and overwrite it.
16
+ *
17
+ * The fence language is inferred from the source file extension, and the
18
+ * fence length grows automatically when the snippet contains backtick
19
+ * runs so that markdown fences never break.
20
+ */
21
+ import { existsSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
22
+ import { dirname, extname, resolve } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+ import { parseArgs } from 'node:util';
25
+
26
+ /**
27
+ * @typedef {import('./types.js').Range} Range
28
+ * @typedef {import('./types.js').BuildOptions} BuildOptions
29
+ */
30
+
31
+ /** @type {number} */
32
+ const DEFAULT_CONTEXT_LINES = 2;
33
+
34
+ /** @type {number} */
35
+ const MIN_FENCE_LENGTH = 3;
36
+
37
+ /**
38
+ * File extension to markdown fence language identifier.
39
+ * @type {Record<string, string>}
40
+ */
41
+ const EXTENSION_TO_FENCE = {
42
+ '.js': 'js',
43
+ '.mjs': 'js',
44
+ '.cjs': 'js',
45
+ '.jsx': 'jsx',
46
+ '.ts': 'ts',
47
+ '.mts': 'ts',
48
+ '.cts': 'ts',
49
+ '.tsx': 'tsx',
50
+ '.py': 'python',
51
+ '.rb': 'ruby',
52
+ '.go': 'go',
53
+ '.rs': 'rust',
54
+ '.java': 'java',
55
+ '.kt': 'kotlin',
56
+ '.kts': 'kotlin',
57
+ '.swift': 'swift',
58
+ '.c': 'c',
59
+ '.h': 'c',
60
+ '.cc': 'cpp',
61
+ '.cpp': 'cpp',
62
+ '.cxx': 'cpp',
63
+ '.hpp': 'cpp',
64
+ '.cs': 'csharp',
65
+ '.php': 'php',
66
+ '.sh': 'bash',
67
+ '.bash': 'bash',
68
+ '.zsh': 'bash',
69
+ '.ps1': 'powershell',
70
+ '.sql': 'sql',
71
+ '.html': 'html',
72
+ '.htm': 'html',
73
+ '.css': 'css',
74
+ '.scss': 'scss',
75
+ '.json': 'json',
76
+ '.yaml': 'yaml',
77
+ '.yml': 'yaml',
78
+ '.toml': 'toml',
79
+ '.md': 'markdown',
80
+ '.xml': 'xml',
81
+ '.lua': 'lua',
82
+ '.dart': 'dart',
83
+ '.ex': 'elixir',
84
+ '.exs': 'elixir',
85
+ '.erl': 'erlang',
86
+ '.hs': 'haskell',
87
+ '.clj': 'clojure',
88
+ '.vue': 'vue',
89
+ '.svelte': 'svelte',
90
+ };
91
+
92
+ const HELP_TEXT = `coverage-to-markdown — convert coverage ranges to markdown snippets
93
+
94
+ Usage:
95
+ coverage-to-markdown --ranges <ranges> --input <source-file> --output <output-md> [options]
96
+
97
+ Required arguments:
98
+ -r, --ranges <ranges> Comma-separated list of line ranges (e.g. "1-5,10,20-25")
99
+ -i, --input <path> Path to the source file whose lines will be extracted
100
+ -o, --output <path> Path to the markdown file that will be written
101
+
102
+ Options:
103
+ -c, --context <n> Lines of context before and after each range (default: 2)
104
+ -t, --title <s> Top-level heading text (default: "Coverage: <basename>")
105
+ --fence <lang> Override fence language (default: from file extension)
106
+ -f, --force Overwrite the output file if it already exists
107
+ -q, --quiet Suppress the success summary on stdout
108
+ -h, --help Show this help and exit
109
+ -v, --version Print version and exit
110
+
111
+ Safety:
112
+ All arguments must be named. Positional arguments are rejected on
113
+ purpose so that a forgotten flag cannot silently overwrite the input
114
+ file. The tool refuses to write over an existing file unless --force
115
+ is given, and rejects --input and --output pointing at the same path.
116
+
117
+ Examples:
118
+ coverage-to-markdown --ranges "176-181,258-270" --input ./src/index.js --output ./coverage.md
119
+ coverage-to-markdown -r "10-20" -i ./src/util.ts -o ./ctx.md -c 5
120
+ coverage-to-markdown -r "1-5" -i ./src/index.js -o ./existing.md --force
121
+ `;
122
+
123
+ /**
124
+ * Parse a coverage range string into an array of ranges.
125
+ * Accepts comma-separated segments in the form "x-y" or "x".
126
+ * Does not merge overlapping or adjacent ranges — use {@link normalizeRanges}
127
+ * for that.
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
+ * Parse a single segment of form "x-y" or "x" into a Range.
141
+ * @param {string} segment
142
+ * @returns {Range}
143
+ */
144
+ function parseRangeSegment(segment) {
145
+ const dashIndex = segment.indexOf('-');
146
+ if (dashIndex === -1) {
147
+ const line = parseLineNumber(segment);
148
+ return { start: line, end: line };
149
+ }
150
+ const start = parseLineNumber(segment.slice(0, dashIndex));
151
+ const end = parseLineNumber(segment.slice(dashIndex + 1));
152
+ if (end < start) {
153
+ throw new Error(`Invalid range (end < start): "${segment}"`);
154
+ }
155
+ return { start, end };
156
+ }
157
+
158
+ /**
159
+ * Parse a positive integer line number.
160
+ * @param {string} raw
161
+ * @returns {number}
162
+ */
163
+ function parseLineNumber(raw) {
164
+ const value = Number(raw);
165
+ if (!Number.isInteger(value) || value < 1) {
166
+ throw new Error(`Invalid line number: "${raw}"`);
167
+ }
168
+ return value;
169
+ }
170
+
171
+ /**
172
+ * Sort ranges and merge overlapping or directly adjacent ones.
173
+ * For example, `[5-7, 8-10, 12-14]` becomes `[5-10, 12-14]`.
174
+ * @param {Range[]} ranges
175
+ * @returns {Range[]}
176
+ */
177
+ function normalizeRanges(ranges) {
178
+ if (!Array.isArray(ranges) || ranges.length === 0) {
179
+ return [];
180
+ }
181
+ const sorted = [...ranges].sort((a, b) => a.start - b.start || a.end - b.end);
182
+ const merged = [{ start: sorted[0].start, end: sorted[0].end }];
183
+ for (let i = 1; i < sorted.length; i += 1) {
184
+ const last = merged[merged.length - 1];
185
+ const current = sorted[i];
186
+ if (current.start <= last.end + 1) {
187
+ if (current.end > last.end) {
188
+ last.end = current.end;
189
+ }
190
+ } else {
191
+ merged.push({ start: current.start, end: current.end });
192
+ }
193
+ }
194
+ return merged;
195
+ }
196
+
197
+ /**
198
+ * Detect the markdown fence language from a file path extension.
199
+ * Returns an empty string for unknown extensions or dotfiles.
200
+ * @param {string} filePath
201
+ * @returns {string}
202
+ */
203
+ function detectFenceLanguage(filePath) {
204
+ const normalized = filePath.replace(/\\/g, '/');
205
+ const ext = extname(normalized).toLowerCase();
206
+ return EXTENSION_TO_FENCE[ext] ?? '';
207
+ }
208
+
209
+ /**
210
+ * Compute the fence length needed so the snippet never breaks the fence.
211
+ * Scans the snippet lines for backtick runs and returns `maxRun + 1`,
212
+ * clamped to a minimum of three backticks.
213
+ * @param {string[]} lines
214
+ * @param {number} start
215
+ * @param {number} end
216
+ * @returns {number}
217
+ */
218
+ function pickFenceLength(lines, start, end) {
219
+ let maxRun = 0;
220
+ const from = Math.max(0, start - 1);
221
+ const to = Math.min(end, lines.length);
222
+ for (let i = from; i < to; i += 1) {
223
+ const line = lines[i] ?? '';
224
+ const runs = line.match(/`+/g);
225
+ if (runs) {
226
+ for (const run of runs) {
227
+ if (run.length > maxRun) {
228
+ maxRun = run.length;
229
+ }
230
+ }
231
+ }
232
+ }
233
+ return Math.max(MIN_FENCE_LENGTH, maxRun + 1);
234
+ }
235
+
236
+ /**
237
+ * Split file content into lines, stripping trailing CR characters.
238
+ * @param {string} content
239
+ * @returns {string[]}
240
+ */
241
+ function splitLines(content) {
242
+ return content.split('\n').map(line => line.replace(/\r$/, ''));
243
+ }
244
+
245
+ /**
246
+ * Compute the 1-based snippet boundaries for a range, clamped to file size.
247
+ * @param {string[]} lines
248
+ * @param {Range} range
249
+ * @param {number} contextLines
250
+ * @returns {{ start: number, end: number }}
251
+ */
252
+ function snippetBounds(lines, range, contextLines) {
253
+ const total = lines.length;
254
+ return {
255
+ start: Math.max(1, range.start - contextLines),
256
+ end: Math.min(total, range.end + contextLines),
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Render snippet lines with `// <lineNumber>` suffixes.
262
+ * @param {string[]} lines
263
+ * @param {number} start
264
+ * @param {number} end
265
+ * @returns {string}
266
+ */
267
+ function renderSnippet(lines, start, end) {
268
+ const parts = [];
269
+ for (let n = start; n <= end; n += 1) {
270
+ parts.push(`${lines[n - 1] ?? ''} // ${n}`);
271
+ }
272
+ return parts.join('\n');
273
+ }
274
+
275
+ /**
276
+ * Build the markdown document body for all ranges.
277
+ * Input ranges are normalized (overlapping and adjacent ranges merged)
278
+ * before rendering.
279
+ * @param {string} sourcePath
280
+ * @param {string[]} lines
281
+ * @param {Range[]} ranges
282
+ * @param {BuildOptions} [options]
283
+ * @returns {string}
284
+ */
285
+ function buildMarkdown(sourcePath, lines, ranges, options = {}) {
286
+ const contextLines = options.contextLines ?? DEFAULT_CONTEXT_LINES;
287
+ if (!Number.isInteger(contextLines) || contextLines < 0) {
288
+ throw new Error(`Invalid contextLines: ${contextLines}`);
289
+ }
290
+
291
+ const normalized = normalizeRanges(ranges);
292
+ const title = options.title ?? `Coverage: ${basenameOf(sourcePath)}`;
293
+ const fenceLang = options.fence !== undefined ? options.fence : detectFenceLanguage(sourcePath);
294
+
295
+ const header = [
296
+ `# ${title}`,
297
+ '',
298
+ `Source: \`${sourcePath}\``,
299
+ '',
300
+ `Ranges: ${normalized.length}`,
301
+ ].join('\n');
302
+
303
+ const sections = normalized.map(range => {
304
+ const bounds = snippetBounds(lines, range, contextLines);
305
+ const fenceLength = pickFenceLength(lines, bounds.start, bounds.end);
306
+ const fence = '`'.repeat(fenceLength);
307
+ const snippet = renderSnippet(lines, bounds.start, bounds.end);
308
+
309
+ const block = [`${fence}${fenceLang}`];
310
+ if (snippet.length > 0) {
311
+ block.push(snippet);
312
+ }
313
+ block.push(fence);
314
+
315
+ return [`## Range (${range.start}, ${range.end})`, '', ...block].join('\n');
316
+ });
317
+
318
+ return [header, ...sections].join('\n\n') + '\n';
319
+ }
320
+
321
+ /**
322
+ * Take the final path component regardless of the separator style.
323
+ * @param {string} filePath
324
+ * @returns {string}
325
+ */
326
+ function basenameOf(filePath) {
327
+ const normalized = filePath.replace(/\\/g, '/');
328
+ const lastSlash = normalized.lastIndexOf('/');
329
+ return lastSlash >= 0 ? normalized.slice(lastSlash + 1) : normalized;
330
+ }
331
+
332
+ /**
333
+ * Read the package version from package.json.
334
+ * @returns {string}
335
+ */
336
+ function readVersion() {
337
+ const pkgUrl = new URL('../package.json', import.meta.url);
338
+ const pkg = JSON.parse(readFileSync(pkgUrl, 'utf8'));
339
+ return pkg.version;
340
+ }
341
+
342
+ /**
343
+ * Parse and validate the `--context` option value.
344
+ * @param {string} raw
345
+ * @returns {number}
346
+ */
347
+ function parseContextOption(raw) {
348
+ const value = Number(raw);
349
+ if (!Number.isInteger(value) || value < 0) {
350
+ throw new Error(`Invalid --context value: "${raw}" (expected a non-negative integer)`);
351
+ }
352
+ return value;
353
+ }
354
+
355
+ /**
356
+ * Reject positional arguments passed to the CLI.
357
+ * Named arguments are mandatory so that a forgotten flag cannot shift
358
+ * paths around and overwrite the input file with output.
359
+ * @param {string[]} positionals
360
+ * @returns {void}
361
+ */
362
+ function rejectPositionals(positionals) {
363
+ if (positionals.length === 0) {
364
+ return;
365
+ }
366
+ throw new Error(
367
+ `Unexpected positional argument(s): ${positionals.join(' ')}. ` +
368
+ 'All arguments must be named. Run with --help for usage.'
369
+ );
370
+ }
371
+
372
+ /**
373
+ * Ensure every required flag is present.
374
+ * @param {Record<string, unknown>} values
375
+ * @returns {{ ranges: string, input: string, output: string }}
376
+ */
377
+ function readRequiredFlags(values) {
378
+ const missing = [];
379
+ if (values.ranges === undefined) {
380
+ missing.push('--ranges');
381
+ }
382
+ if (values.input === undefined) {
383
+ missing.push('--input');
384
+ }
385
+ if (values.output === undefined) {
386
+ missing.push('--output');
387
+ }
388
+ if (missing.length > 0) {
389
+ throw new Error(
390
+ `Missing required argument(s): ${missing.join(', ')}. ` + 'Run with --help for usage.'
391
+ );
392
+ }
393
+ return {
394
+ ranges: String(values.ranges),
395
+ input: String(values.input),
396
+ output: String(values.output),
397
+ };
398
+ }
399
+
400
+ /**
401
+ * Validate input and output paths before any file is written.
402
+ * @param {string} sourcePath absolute path to the source file
403
+ * @param {string} outputPath absolute path to the output file
404
+ * @param {boolean} force whether --force was passed
405
+ * @returns {void}
406
+ */
407
+ function guardFilePaths(sourcePath, outputPath, force) {
408
+ if (sourcePath === outputPath) {
409
+ throw new Error(
410
+ '--input and --output must point at different files. ' +
411
+ 'Refusing to overwrite the source file.'
412
+ );
413
+ }
414
+ if (!existsSync(sourcePath)) {
415
+ throw new Error(`Input file not found: ${sourcePath}`);
416
+ }
417
+ if (!statSync(sourcePath).isFile()) {
418
+ throw new Error(`Input path is not a regular file: ${sourcePath}`);
419
+ }
420
+ if (existsSync(outputPath) && !force) {
421
+ throw new Error(
422
+ `Output file already exists: ${outputPath}. ` + 'Pass --force to overwrite it.'
423
+ );
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Check whether the current module was started as the main script.
429
+ *
430
+ * Compares real (symlink-resolved) paths instead of file URLs, because
431
+ * on Windows process.argv[1] and import.meta.url can disagree on drive
432
+ * letter case, on short (8.3) names, and on whether junctions are
433
+ * resolved when the script is launched through an npm bin shim — the
434
+ * exact setup that `npm link` produces.
435
+ * @returns {boolean}
436
+ */
437
+ function isMainModule() {
438
+ const entry = process.argv[1];
439
+ if (entry === undefined) {
440
+ return false;
441
+ }
442
+ try {
443
+ const selfPath = realpathSync(fileURLToPath(import.meta.url));
444
+ const entryPath = realpathSync(resolve(entry));
445
+ if (process.platform === 'win32') {
446
+ return selfPath.toLowerCase() === entryPath.toLowerCase();
447
+ }
448
+ return selfPath === entryPath;
449
+ } catch {
450
+ return false;
451
+ }
452
+ }
453
+
454
+ /**
455
+ * CLI entry point.
456
+ * @param {string[]} argv
457
+ * @returns {void}
458
+ */
459
+ function main(argv) {
460
+ try {
461
+ const { values, positionals } = parseArgs({
462
+ args: argv,
463
+ allowPositionals: true,
464
+ options: {
465
+ ranges: { type: 'string', short: 'r' },
466
+ input: { type: 'string', short: 'i' },
467
+ output: { type: 'string', short: 'o' },
468
+ context: { type: 'string', short: 'c' },
469
+ title: { type: 'string', short: 't' },
470
+ fence: { type: 'string' },
471
+ force: { type: 'boolean', short: 'f' },
472
+ quiet: { type: 'boolean', short: 'q' },
473
+ help: { type: 'boolean', short: 'h' },
474
+ version: { type: 'boolean', short: 'v' },
475
+ },
476
+ });
477
+
478
+ if (values.help) {
479
+ process.stdout.write(HELP_TEXT);
480
+ return;
481
+ }
482
+
483
+ if (values.version) {
484
+ process.stdout.write(`${readVersion()}\n`);
485
+ return;
486
+ }
487
+
488
+ rejectPositionals(positionals);
489
+ const flags = readRequiredFlags(values);
490
+
491
+ const contextLines =
492
+ values.context !== undefined
493
+ ? parseContextOption(values.context)
494
+ : DEFAULT_CONTEXT_LINES;
495
+
496
+ const sourcePath = resolve(flags.input);
497
+ const outputPath = resolve(flags.output);
498
+ guardFilePaths(sourcePath, outputPath, values.force === true);
499
+
500
+ const outputDir = dirname(outputPath);
501
+ if (!existsSync(outputDir)) {
502
+ throw new Error(
503
+ `Output directory does not exist: ${outputDir}. ` +
504
+ 'Create it first, or choose a different --output path.'
505
+ );
506
+ }
507
+
508
+ const rawRanges = parseRanges(flags.ranges);
509
+ if (rawRanges.length === 0) {
510
+ throw new Error('--ranges produced no ranges; check the input string.');
511
+ }
512
+
513
+ const content = readFileSync(sourcePath, 'utf8');
514
+ const lines = splitLines(content);
515
+
516
+ const markdown = buildMarkdown(sourcePath, lines, rawRanges, {
517
+ contextLines,
518
+ title: values.title,
519
+ fence: values.fence,
520
+ });
521
+
522
+ writeFileSync(outputPath, markdown, 'utf8');
523
+
524
+ // Verify the file actually landed on disk; if it didn't, fail loudly
525
+ // rather than silently reporting success.
526
+ const written = statSync(outputPath);
527
+
528
+ if (!values.quiet) {
529
+ const count = normalizeRanges(rawRanges).length;
530
+ process.stdout.write(
531
+ [
532
+ 'coverage-to-markdown: wrote report',
533
+ ` input: ${sourcePath}`,
534
+ ` output: ${outputPath}`,
535
+ ` ranges: ${count} (from ${rawRanges.length} parsed)`,
536
+ ` size: ${written.size} bytes`,
537
+ ].join('\n') + '\n'
538
+ );
539
+ }
540
+ } catch (error) {
541
+ const message = error instanceof Error ? error.message : String(error);
542
+ process.stderr.write(`coverage-to-markdown: error: ${message}\n`);
543
+ process.exit(1);
544
+ }
545
+ }
546
+
547
+ export { parseRanges, normalizeRanges, detectFenceLanguage, buildMarkdown };
548
+
549
+ if (isMainModule()) {
550
+ main(process.argv.slice(2));
551
+ }
package/src/types.d.ts ADDED
@@ -0,0 +1,21 @@
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
+ * Options for `buildMarkdown`.
13
+ */
14
+ export interface BuildOptions {
15
+ /** Lines of context before and after each range. Default: 2. */
16
+ contextLines?: number;
17
+ /** Custom top-level heading text. Default: `Coverage: <basename>`. */
18
+ title?: string;
19
+ /** Fence language override. Default: detected from the file extension. */
20
+ fence?: string;
21
+ }