flashtrace 0.12.0 → 0.13.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.
@@ -1,1429 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/main.mjs
4
- import { realpathSync } from "node:fs";
5
- import process4 from "node:process";
6
- import { fileURLToPath, pathToFileURL } from "node:url";
7
-
8
- // src/cli.mjs
9
- import { promises as fs2, readFileSync } from "node:fs";
10
- import path5 from "node:path";
11
- import process3 from "node:process";
12
-
13
- // src/errors.mjs
14
- var UsageError = class extends Error {
15
- };
16
-
17
- // src/files.mjs
18
- import { existsSync, promises as fs } from "node:fs";
19
- import path from "node:path";
20
- import { execFileSync } from "node:child_process";
21
-
22
- // src/languages.mjs
23
- var cLike = { line: ["//"], block: [["/*", "*/"]] };
24
- var cLikeNested = { line: ["//"], block: [["/*", "*/", true]] };
25
- var php = { line: ["//", "#"], block: [["/*", "*/"]] };
26
- var hash = { line: ["#"], block: [] };
27
- var coffee = { line: ["#", "####"], block: [["###", "###"]] };
28
- var julia = { line: ["#"], block: [["#=", "=#", true]] };
29
- var nim = { line: ["#"], block: [["#[", "]#", true], ["##[", "]##", true]] };
30
- var cmake = { line: ["#"], block: [["#[[", "]]"]] };
31
- var powershell = { line: ["#"], block: [["<#", "#>"]] };
32
- var sql = { line: ["--"], block: [["/*", "*/"]] };
33
- var lua = { line: ["--"], block: [["--[[", "]]"]] };
34
- var haskell = { line: ["--"], block: [["{-", "-}", true]] };
35
- var css = { line: [], block: [["/*", "*/"]] };
36
- var xml = { line: [], block: [["<!--", "-->"]] };
37
- var none = { line: [], block: [] };
38
- var semicolon = { line: [";"], block: [] };
39
- var scheme = { line: [";"], block: [["#|", "|#", true]] };
40
- var percent = { line: ["%"], block: [] };
41
- var dashLine = { line: ["--"], block: [] };
42
- var ml = { line: [], block: [["(*", "*)", true]] };
43
- var fsharp = { line: ["//"], block: [["(*", "*)", true]] };
44
- var pascal = { line: ["//"], block: [["{", "}"], ["(*", "*)"]] };
45
- var hcl = { line: ["#", "//"], block: [["/*", "*/"]] };
46
- function attrOf(tag, name) {
47
- const m = new RegExp(String.raw`\s${name}\s*=\s*["']?([^"'\s>]+)`, "i").exec(tag);
48
- return m ? m[1].toLowerCase() : "";
49
- }
50
- function scriptGrammar(tag) {
51
- const type = attrOf(tag, "type");
52
- if (/json|importmap/.test(type)) return none;
53
- if (/template|html/.test(type)) return xml;
54
- if (/coffee/.test(attrOf(tag, "lang"))) return coffee;
55
- return cLike;
56
- }
57
- function styleGrammar(tag) {
58
- return /s[ac]ss|less|stylus|styl/.test(attrOf(tag, "lang")) ? cLike : css;
59
- }
60
- var html = {
61
- default: xml,
62
- regions: [
63
- { enter: /<script\b[^>]*>/gi, exit: /<\/script\s*>/gi, grammar: scriptGrammar },
64
- { enter: /<style\b[^>]*>/gi, exit: /<\/style\s*>/gi, grammar: styleGrammar }
65
- ]
66
- };
67
- var BY_EXT = {
68
- // C-family: // line, /* */ block
69
- ".ts": cLike,
70
- ".js": cLike,
71
- ".mjs": cLike,
72
- ".cjs": cLike,
73
- ".jsx": cLike,
74
- ".tsx": cLike,
75
- ".cts": cLike,
76
- ".mts": cLike,
77
- ".c": cLike,
78
- ".h": cLike,
79
- ".cpp": cLike,
80
- ".cc": cLike,
81
- ".hpp": cLike,
82
- ".cxx": cLike,
83
- ".hxx": cLike,
84
- ".ino": cLike,
85
- ".inl": cLike,
86
- ".tpp": cLike,
87
- ".cs": cLike,
88
- ".java": cLike,
89
- ".go": cLike,
90
- ".groovy": cLike,
91
- ".gradle": cLike,
92
- ".sol": cLike,
93
- ".dart": cLike,
94
- ".php": php,
95
- ".proto": cLike,
96
- ".scss": cLike,
97
- ".less": cLike,
98
- // C-family with nested block comments
99
- ".rs": cLikeNested,
100
- ".swift": cLikeNested,
101
- ".kt": cLikeNested,
102
- ".kts": cLikeNested,
103
- ".scala": cLikeNested,
104
- // hash line comments
105
- ".py": hash,
106
- ".rb": hash,
107
- ".sh": hash,
108
- ".bash": hash,
109
- ".zsh": hash,
110
- ".yaml": hash,
111
- ".yml": hash,
112
- ".toml": hash,
113
- ".r": hash,
114
- ".pm": hash,
115
- ".ex": hash,
116
- ".exs": hash,
117
- ".tcl": hash,
118
- ".cr": hash,
119
- ".gd": hash,
120
- ".awk": hash,
121
- ".graphql": hash,
122
- ".gql": hash,
123
- // hash line comments plus a block pair of their own
124
- ".jl": julia,
125
- ".nim": nim,
126
- ".coffee": coffee,
127
- ".cmake": cmake,
128
- ".ps1": powershell,
129
- ".psm1": powershell,
130
- ".tf": hcl,
131
- ".tfvars": hcl,
132
- ".hcl": hcl,
133
- // semicolon (Lisp family)
134
- ".clj": semicolon,
135
- ".cljs": semicolon,
136
- ".cljc": semicolon,
137
- ".edn": semicolon,
138
- ".el": semicolon,
139
- ".lisp": semicolon,
140
- // Scheme/Racket: ; lines plus nestable #| |# blocks
141
- ".scm": scheme,
142
- ".ss": scheme,
143
- ".rkt": scheme,
144
- // percent (Erlang, LaTeX)
145
- ".erl": percent,
146
- ".hrl": percent,
147
- ".tex": percent,
148
- ".sty": percent,
149
- // dash line-only (Ada, VHDL)
150
- ".adb": dashLine,
151
- ".ads": dashLine,
152
- ".vhd": dashLine,
153
- ".vhdl": dashLine,
154
- // ML-family
155
- ".ml": ml,
156
- ".mli": ml,
157
- ".fs": fsharp,
158
- ".fsi": fsharp,
159
- ".fsx": fsharp,
160
- ".pas": pascal,
161
- ".dpr": pascal,
162
- // dashes and others
163
- ".sql": sql,
164
- ".lua": lua,
165
- ".hs": haskell,
166
- ".elm": haskell,
167
- ".purs": haskell,
168
- ".css": css,
169
- ".xml": xml,
170
- ".svg": xml,
171
- // composite: HTML markup with embedded <script>/<style> regions
172
- ".vue": html,
173
- ".html": html,
174
- ".htm": html,
175
- ".svelte": html
176
- };
177
- var CODE_EXT = new Set(Object.keys(BY_EXT));
178
- var grammarFor = (ext) => BY_EXT[ext] ?? null;
179
-
180
- // src/files.mjs
181
- var SPEC_EXT = /* @__PURE__ */ new Set([".md", ".markdown"]);
182
- var GIT_LOCATIONS = process.platform === "win32" ? [
183
- String.raw`C:\Program Files\Git\cmd\git.exe`,
184
- String.raw`C:\Program Files (x86)\Git\cmd\git.exe`
185
- ] : ["/usr/bin/git", "/bin/git"];
186
- var gitBin;
187
- function findGit() {
188
- if (gitBin === void 0) {
189
- gitBin = GIT_LOCATIONS.find((p) => existsSync(p)) ?? null;
190
- }
191
- return gitBin;
192
- }
193
- function compareStrings(a, b) {
194
- if (a < b) return -1;
195
- if (a > b) return 1;
196
- return 0;
197
- }
198
- async function walk(dir, out) {
199
- let entries;
200
- try {
201
- entries = await fs.readdir(dir, { withFileTypes: true });
202
- } catch {
203
- return out;
204
- }
205
- for (const entry of entries) {
206
- if (entry.name === ".git" || entry.name === "node_modules") continue;
207
- const entryPath = path.join(dir, entry.name);
208
- if (entry.isDirectory()) await walk(entryPath, out);
209
- else if (entry.isFile()) out.push(entryPath);
210
- }
211
- return out;
212
- }
213
- async function collectFiles(dirs) {
214
- const files = /* @__PURE__ */ new Set();
215
- for (const dir of dirs) {
216
- const abs = path.resolve(dir);
217
- const stats = await fs.stat(abs).catch(() => null);
218
- if (!stats) throw new UsageError(`input path does not exist: ${dir}`);
219
- if (stats.isFile()) {
220
- files.add(abs);
221
- continue;
222
- }
223
- let list = null;
224
- const git = findGit();
225
- try {
226
- if (!git) throw new Error("git not found");
227
- const out = execFileSync(
228
- git,
229
- ["-C", abs, "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
230
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
231
- );
232
- list = out.split("\0").filter(Boolean).map((f) => path.join(abs, f));
233
- } catch {
234
- list = await walk(abs, []);
235
- }
236
- for (const file of list) files.add(file);
237
- }
238
- return [...files].filter((file) => {
239
- const ext = path.extname(file).toLowerCase();
240
- return SPEC_EXT.has(ext) || CODE_EXT.has(ext);
241
- }).sort(compareStrings);
242
- }
243
-
244
- // src/ids.mjs
245
- var SEGMENT_SRC = "[A-Za-z][A-Za-z0-9_.-]*";
246
- var REV_SRC = String.raw`\d+(?:\.\d+){0,2}`;
247
- var WILDCARD_SRC = String.raw`(?:\d+\.){0,2}[x*]`;
248
- var REV_REF_SRC = `(?:${WILDCARD_SRC}|${REV_SRC})`;
249
- var ID_SRC = String.raw`([A-Za-z]+):(?:((?:${SEGMENT_SRC}\/)*${SEGMENT_SRC})\/)?(${SEGMENT_SRC})#(${REV_SRC})`;
250
- var ID_RE = new RegExp(`^${ID_SRC}$`);
251
- var PATH_SRC = String.raw`(?:${SEGMENT_SRC}\/)*${SEGMENT_SRC}`;
252
- var REF_SRC = `([A-Za-z]+)(?::(${PATH_SRC}))?(?:#(${REV_REF_SRC}))?`;
253
- var REF_RE = new RegExp(`^${REF_SRC}$`);
254
- var COVER_REF_RE = new RegExp(`^([A-Za-z]+)(?::(${PATH_SRC}))?(?:#(${REV_SRC}))?$`);
255
- var FORWARD_SRC = String.raw`\[\s*${ID_SRC}\s*-->\s*${ID_SRC}\s*\]`;
256
- var makeId = (type, group, name, rev) => `${type}:${group ? group + "/" : ""}${name}#${rev}`;
257
- var makeForward = (m, base, file, line, character) => ({
258
- from: makeId(m[base], m[base + 1], m[base + 2], m[base + 3]),
259
- to: makeId(m[base + 4], m[base + 5], m[base + 6], m[base + 7]),
260
- file,
261
- line,
262
- character
263
- });
264
- var keyOf = (id) => id.slice(0, id.lastIndexOf("#"));
265
- var revOf = (id) => id.slice(id.lastIndexOf("#") + 1);
266
- var pathOf = (id) => id.slice(id.indexOf(":") + 1, id.lastIndexOf("#"));
267
- var resolveRef = (type, path6, rev, ownerId) => `${type}:${path6 ?? pathOf(ownerId)}#${rev ?? revOf(ownerId)}`;
268
- function canonicalRev(rev) {
269
- const layers = rev.split(".").map((layer) => String(Number(layer)));
270
- while (layers.length < 3) layers.push("0");
271
- return layers.join(".");
272
- }
273
- var canonicalId = (id) => `${keyOf(id)}#${canonicalRev(revOf(id))}`;
274
- function compareRev(a, b) {
275
- const layersA = canonicalRev(a).split(".");
276
- const layersB = canonicalRev(b).split(".");
277
- for (let i = 0; i < 3; i++) {
278
- if (layersA[i] !== layersB[i]) return Number(layersA[i]) - Number(layersB[i]);
279
- }
280
- return 0;
281
- }
282
- var isWildcardLayer = (layer) => layer === "x" || layer === "*";
283
- var isWildcardRev = (rev) => /[x*]/.test(rev);
284
- function revMatches(pattern, concrete) {
285
- const patternLayers = pattern.split(".");
286
- while (patternLayers.length < 3) patternLayers.push(isWildcardLayer(patternLayers.at(-1)) ? "x" : "0");
287
- const concreteLayers = canonicalRev(concrete).split(".");
288
- for (let i = 0; i < 3; i++) {
289
- if (isWildcardLayer(patternLayers[i])) continue;
290
- if (Number(patternLayers[i]) !== Number(concreteLayers[i])) return false;
291
- }
292
- return true;
293
- }
294
- var idMatches = (need, id) => keyOf(need) === keyOf(id) && revMatches(revOf(need), revOf(id));
295
- function parseNeedEntry(raw, ownerId) {
296
- const cleaned = raw.replaceAll("`", "").trim();
297
- const m = cleaned.match(REF_RE);
298
- return m ? resolveRef(m[1], m[2], m[3], ownerId) : null;
299
- }
300
- function parseCoverEntry(raw, ownerId) {
301
- const cleaned = raw.replaceAll("`", "").trim();
302
- const m = cleaned.match(COVER_REF_RE);
303
- return m ? resolveRef(m[1], m[2], m[3], ownerId) : null;
304
- }
305
- function newItem(id, origin, file, line, character) {
306
- return {
307
- id,
308
- key: keyOf(id),
309
- revision: revOf(id),
310
- canonicalId: canonicalId(id),
311
- // the SemVer-equal identity every exact-ID lookup keys on
312
- origin,
313
- // 'spec' | 'code'
314
- file,
315
- line,
316
- character,
317
- // 1-based column of the first character of the defining construct
318
- title: null,
319
- description: [],
320
- needs: [],
321
- covers: [],
322
- tags: [],
323
- defects: [],
324
- forwardsTo: null
325
- // effective forwarding target, set by analyze
326
- };
327
- }
328
-
329
- // src/parse-markdown.mjs
330
- var DEFINITION_RE = new RegExp(String.raw`^\s*\`${ID_SRC}\`\s*$`);
331
- var HEADING_RE = /^(#{1,6})\s+(\S(?:.*\S)?)\s*$/;
332
- var SETEXT_UNDERLINE_RE = /^ {0,3}(?:=+|-+)[ \t]*$/;
333
- var THEMATIC_BREAK_RE = /^ {0,3}-{3,}[ \t]*$/;
334
- var KEYWORD_RE = /^(Needs|Covers|Tags):\s*((?:\S.*)?)$/;
335
- var BULLET_RE = /^\s*[-*+]\s+(\S(?:.*\S)?)\s*$/;
336
- var DELIMITER_CELL_RE = /^:?-+:?$/;
337
- var FORWARD_LINE_RE = new RegExp(String.raw`^\s*(\`?)${FORWARD_SRC}\1\s*$`);
338
- var firstNonBlankColumn = (line) => line.search(/\S/) + 1;
339
- function takeForward(line, file, lineIndex, forwards) {
340
- const forward = line.match(FORWARD_LINE_RE);
341
- if (forward) forwards.push(makeForward(forward, 2, file, lineIndex + 1, firstNonBlankColumn(line)));
342
- return !!forward;
343
- }
344
- function isParagraphLine(line) {
345
- return line.trim() !== "" && !HEADING_RE.test(line) && !BULLET_RE.test(line) && !SETEXT_UNDERLINE_RE.test(line);
346
- }
347
- var isParagraphAt = (lines, inTable, j) => !inTable[j] && isParagraphLine(lines[j]);
348
- var isSetextHeading = (lines, inTable, titleIndex) => titleIndex + 1 < lines.length && SETEXT_UNDERLINE_RE.test(lines[titleIndex + 1]) && isParagraphAt(lines, inTable, titleIndex);
349
- function scanSetextHeadings(lines, inTable) {
350
- const opensHeading = new Array(lines.length).fill(false);
351
- let j = 0;
352
- while (j < lines.length) {
353
- if (!isParagraphAt(lines, inTable, j)) {
354
- j++;
355
- continue;
356
- }
357
- const start = j;
358
- while (j + 1 < lines.length && isParagraphAt(lines, inTable, j + 1)) j++;
359
- if (isSetextHeading(lines, inTable, j)) opensHeading.fill(true, start, j + 1);
360
- j++;
361
- }
362
- return opensHeading;
363
- }
364
- var isBoundary = (lines, inTable, opensHeading, j) => !inTable[j] && DEFINITION_RE.test(lines[j]) || HEADING_RE.test(lines[j]) || opensHeading[j];
365
- function foldSetextTitle(lines, inTable, lastIndex) {
366
- let first = lastIndex;
367
- while (first > 0 && isParagraphAt(lines, inTable, first - 1)) first--;
368
- let title = "";
369
- for (let k = first; k <= lastIndex; k++) {
370
- title += lines[k].trim();
371
- if (k < lastIndex) title += / {2}$/.test(lines[k]) ? "\n" : " ";
372
- }
373
- return title;
374
- }
375
- function titleAbove(lines, inTable, definitionIndex) {
376
- for (let k = definitionIndex - 1; k >= 0; k--) {
377
- const line = lines[k];
378
- if (line.trim() === "") continue;
379
- const heading = line.match(HEADING_RE);
380
- if (heading) return heading[2];
381
- if (k > 0 && isSetextHeading(lines, inTable, k - 1)) {
382
- return foldSetextTitle(lines, inTable, k - 1);
383
- }
384
- return null;
385
- }
386
- return null;
387
- }
388
- function keywordEntries(lines, j, inline) {
389
- if (inline.trim() !== "") {
390
- const inlineStart = lines[j].length - inline.length;
391
- const entries2 = [];
392
- let pos = 0;
393
- for (const part of inline.split(",")) {
394
- const value = part.trim();
395
- if (value) {
396
- const leading = part.length - part.trimStart().length;
397
- entries2.push({ value, line: j + 1, character: inlineStart + pos + leading + 1 });
398
- }
399
- pos += part.length + 1;
400
- }
401
- return { entries: entries2, j };
402
- }
403
- const entries = [];
404
- while (j + 1 < lines.length) {
405
- const bullet = lines[j + 1].match(BULLET_RE);
406
- if (!bullet) break;
407
- entries.push({ value: bullet[1].trim(), line: j + 2, character: lines[j + 1].indexOf(bullet[1]) + 1 });
408
- j++;
409
- }
410
- return { entries, j };
411
- }
412
- function rowCells(line) {
413
- let row = line.trim();
414
- if (!row.includes("|")) return null;
415
- if (row.startsWith("|")) row = row.slice(1);
416
- if (row.endsWith("|")) row = row.slice(0, -1);
417
- return row.split("|").map((cell) => cell.trim());
418
- }
419
- function rowCellColumns(line) {
420
- if (rowCells(line) === null) return [firstNonBlankColumn(line)];
421
- let base = line.length - line.trimStart().length;
422
- const trimmed = line.trim();
423
- let body = trimmed;
424
- if (body.startsWith("|")) {
425
- body = body.slice(1);
426
- base += 1;
427
- }
428
- if (body.endsWith("|")) body = body.slice(0, -1);
429
- const columns = [];
430
- let pos = 0;
431
- for (const part of body.split("|")) {
432
- const value = part.trim();
433
- const leading = value ? part.length - part.trimStart().length : 0;
434
- columns.push(base + pos + leading + 1);
435
- pos += part.length + 1;
436
- }
437
- return columns;
438
- }
439
- function tableStartsAt(lines, j) {
440
- const header = rowCells(lines[j]);
441
- if (!header) return false;
442
- const delimiter = j + 1 < lines.length ? rowCells(lines[j + 1]) : null;
443
- return delimiter?.length === header.length && delimiter.every((cell) => DELIMITER_CELL_RE.test(cell));
444
- }
445
- var continuesTable = (line) => line.trim() !== "" && !HEADING_RE.test(line) && !THEMATIC_BREAK_RE.test(line) && (line.includes("|") || SETEXT_UNDERLINE_RE.test(line) || DEFINITION_RE.test(line));
446
- var rowCellsInTable = (line) => rowCells(line) ?? [line.trim()];
447
- var isKeywordCell = (cell) => cell === "Needs" || cell === "Covers" || cell === "Tags";
448
- function scanTables(lines, file, problems) {
449
- const inTable = new Array(lines.length).fill(false);
450
- let j = 0;
451
- while (j < lines.length) {
452
- if (!tableStartsAt(lines, j)) {
453
- j++;
454
- continue;
455
- }
456
- const keywordColumns = /* @__PURE__ */ new Set();
457
- rowCells(lines[j]).forEach((cell, col) => {
458
- if (isKeywordCell(cell)) keywordColumns.add(col);
459
- });
460
- const start = j;
461
- let end = j + 1;
462
- while (end + 1 < lines.length && continuesTable(lines[end + 1])) end++;
463
- for (let k = start; k <= end; k++) {
464
- inTable[k] = true;
465
- if (k === start + 1) continue;
466
- const columns = rowCellColumns(lines[k]);
467
- rowCellsInTable(lines[k]).forEach((cell, col) => {
468
- const definition = keywordColumns.has(col) ? null : cell.match(DEFINITION_RE);
469
- if (definition)
470
- problems.push({
471
- file,
472
- line: k + 1,
473
- character: columns[col],
474
- message: `item ${makeId(definition[1], definition[2], definition[3], definition[4])} defined inside a table; a table cell is not an item definition`
475
- });
476
- });
477
- }
478
- j = end + 1;
479
- }
480
- return inTable;
481
- }
482
- function takeKeywordTable(lines, inTable, j, item, file, problems) {
483
- if (!inTable[j] || j > 0 && inTable[j - 1]) return null;
484
- const columns = [];
485
- rowCells(lines[j]).forEach((cell, col) => {
486
- if (isKeywordCell(cell)) columns.push([col, cell]);
487
- });
488
- if (columns.length === 0) return null;
489
- j++;
490
- while (j + 1 < lines.length && inTable[j + 1]) {
491
- j++;
492
- const cells = rowCellsInTable(lines[j]);
493
- const cellColumns = rowCellColumns(lines[j]);
494
- for (const [col, keyword] of columns) {
495
- if (cells[col])
496
- applyKeyword(
497
- item,
498
- keyword,
499
- [{ value: cells[col], line: j + 1, character: cellColumns[col] }],
500
- file,
501
- problems,
502
- `the ${keyword} column of ${item.id}`
503
- );
504
- }
505
- }
506
- return j;
507
- }
508
- function applyKeyword(item, keyword, entries, file, problems, source) {
509
- if (keyword === "Tags") {
510
- for (const entry of entries) item.tags.push(entry.value);
511
- return;
512
- }
513
- const target = keyword === "Needs" ? "needs" : "covers";
514
- const parse = keyword === "Needs" ? parseNeedEntry : parseCoverEntry;
515
- for (const entry of entries) {
516
- const id = parse(entry.value, item.id);
517
- if (id) item[target].push(id);
518
- else
519
- problems.push({
520
- file,
521
- line: entry.line,
522
- character: entry.character,
523
- message: `invalid ID "${entry.value}" in ${source}`
524
- });
525
- }
526
- }
527
- function parseItemBody(lines, boundary, start, item, file, problems, forwards) {
528
- const { inTable, opensHeading } = boundary;
529
- let j = start;
530
- let descriptionDone = false;
531
- while (j < lines.length && !isBoundary(lines, inTable, opensHeading, j)) {
532
- const line = lines[j];
533
- if (takeForward(line, file, j, forwards)) {
534
- j++;
535
- continue;
536
- }
537
- const keywordMatch = line.match(KEYWORD_RE);
538
- const tableEnd = keywordMatch ? null : takeKeywordTable(lines, inTable, j, item, file, problems);
539
- if (keywordMatch) {
540
- descriptionDone = true;
541
- const collected = keywordEntries(lines, j, keywordMatch[2]);
542
- applyKeyword(
543
- item,
544
- keywordMatch[1],
545
- collected.entries,
546
- file,
547
- problems,
548
- `${keywordMatch[1]}: list of ${item.id}`
549
- );
550
- j = collected.j;
551
- } else if (tableEnd !== null) {
552
- descriptionDone = true;
553
- j = tableEnd;
554
- } else if (line.trim() === "") {
555
- if (item.description.length > 0) descriptionDone = true;
556
- } else if (!descriptionDone) {
557
- item.description.push(line.trim());
558
- }
559
- j++;
560
- }
561
- return j;
562
- }
563
- function parseMarkdown(file, text, problems, forwards = []) {
564
- const lines = text.split(/\r?\n/);
565
- const inTable = scanTables(lines, file, problems);
566
- const opensHeading = scanSetextHeadings(lines, inTable);
567
- const boundary = { inTable, opensHeading };
568
- const items = [];
569
- let i = 0;
570
- while (i < lines.length) {
571
- const startsHeading = opensHeading[i];
572
- if (!startsHeading && takeForward(lines[i], file, i, forwards)) {
573
- i++;
574
- continue;
575
- }
576
- const definition = inTable[i] ? null : lines[i].match(DEFINITION_RE);
577
- if (definition && startsHeading) {
578
- problems.push({
579
- file,
580
- line: i + 1,
581
- character: firstNonBlankColumn(lines[i]),
582
- message: `item ${makeId(definition[1], definition[2], definition[3], definition[4])} defined inside a setext heading; a heading is not an item definition`
583
- });
584
- i++;
585
- continue;
586
- }
587
- if (!definition) {
588
- i++;
589
- continue;
590
- }
591
- const item = newItem(makeId(definition[1], definition[2], definition[3], definition[4]), "spec", file, i + 1, firstNonBlankColumn(lines[i]));
592
- item.title = titleAbove(lines, inTable, i);
593
- i = parseItemBody(lines, boundary, i + 1, item, file, problems, forwards);
594
- items.push(item);
595
- }
596
- return items;
597
- }
598
-
599
- // src/parse-code.mjs
600
- import path2 from "node:path";
601
- var TAG_RE = new RegExp(
602
- String.raw`\[(?:\s*${ID_SRC}\s*)?>>\s*${REF_SRC}\s*\]|\[\s*${ID_SRC}\s*\]`,
603
- "g"
604
- );
605
- var FORWARD_RE = new RegExp(FORWARD_SRC, "g");
606
- var URL_RE = /[A-Za-z][A-Za-z0-9+.-]{0,63}:\/\/[^\s"'`<>[\]]*/g;
607
- function urlSpans(line) {
608
- if (!line.includes("://")) return [];
609
- return [...line.matchAll(URL_RE)].map((m) => ({ start: m.index, end: m.index + m[0].length }));
610
- }
611
- function markerIndex(line, marker, pos, spans) {
612
- let idx = line.indexOf(marker, pos);
613
- for (const span of spans) {
614
- if (idx === -1 || idx < span.start) break;
615
- if (idx < span.end) idx = line.indexOf(marker, span.end);
616
- }
617
- return idx;
618
- }
619
- function activeLeaf(grammar, state) {
620
- if (state.region) return state.region.grammar;
621
- return grammar.regions ? grammar.default : grammar;
622
- }
623
- function matchAt(re, line, pos) {
624
- re.lastIndex = pos;
625
- return re.exec(line);
626
- }
627
- function* regionEvents(line, pos, grammar, state) {
628
- if (!grammar.regions) return;
629
- if (state.region) {
630
- const m = matchAt(state.region.exit, line, pos);
631
- if (m) yield { idx: m.index, kind: "exit", len: m[0].length };
632
- return;
633
- }
634
- for (const region of grammar.regions) {
635
- const m = matchAt(region.enter, line, pos);
636
- if (m) {
637
- const leaf = typeof region.grammar === "function" ? region.grammar(m[0]) : region.grammar;
638
- yield { idx: m.index, kind: "enter", len: m[0].length, region: { exit: region.exit, grammar: leaf } };
639
- }
640
- }
641
- }
642
- function nextEvent(line, pos, grammar, state, spans) {
643
- const leaf = activeLeaf(grammar, state);
644
- let best = null;
645
- const consider = (idx, event) => {
646
- if (idx === -1) return;
647
- if (best === null || idx < best.idx || idx === best.idx && event.len > best.len) {
648
- best = { ...event, idx };
649
- }
650
- };
651
- for (const marker of leaf.line) {
652
- consider(markerIndex(line, marker, pos, spans), { kind: "line", len: marker.length });
653
- }
654
- for (const [open, close, nestable] of leaf.block) {
655
- consider(markerIndex(line, open, pos, spans), {
656
- kind: "block",
657
- len: open.length,
658
- open,
659
- close,
660
- nestable: Boolean(nestable)
661
- });
662
- }
663
- for (const event of regionEvents(line, pos, grammar, state)) consider(event.idx, event);
664
- return best;
665
- }
666
- function readBlockRest(line, pos, block, limit = line.length) {
667
- const { open, close, nestable } = block;
668
- const within = (idx) => idx !== -1 && idx < limit ? idx : -1;
669
- let i = pos;
670
- while (i < limit) {
671
- const closeIdx = within(line.indexOf(close, i));
672
- const openIdx = within(nestable ? line.indexOf(open, i) : -1);
673
- if (closeIdx === -1 && openIdx === -1) break;
674
- if (openIdx !== -1 && (closeIdx === -1 || openIdx < closeIdx)) {
675
- block.depth++;
676
- i = openIdx + open.length;
677
- continue;
678
- }
679
- block.depth--;
680
- i = closeIdx + close.length;
681
- if (block.depth === 0) return { end: closeIdx, pos: i, closed: true };
682
- }
683
- return { end: limit, pos: limit, closed: false };
684
- }
685
- function regionExitAt(line, pos, region) {
686
- const m = matchAt(region.exit, line, pos);
687
- return m ? { idx: m.index, len: m[0].length } : null;
688
- }
689
- function consumeBlock(line, pos, state, exit) {
690
- const rest = readBlockRest(line, pos, state.block, exit ? exit.idx : line.length);
691
- if (rest.closed) {
692
- state.block = null;
693
- return { end: rest.end, pos: rest.pos };
694
- }
695
- if (exit) {
696
- state.block = null;
697
- state.region = null;
698
- return { end: rest.end, pos: exit.idx + exit.len };
699
- }
700
- return { end: rest.end, pos: rest.pos };
701
- }
702
- function consumeLine(line, pos, state, exit) {
703
- if (exit) {
704
- state.region = null;
705
- return { end: exit.idx, pos: exit.idx + exit.len, done: false };
706
- }
707
- return { end: line.length, pos: line.length, done: true };
708
- }
709
- function commentText(line, state, grammar) {
710
- const spans = urlSpans(line);
711
- const buffer = new Array(line.length).fill(" ");
712
- const keep = (from, to) => {
713
- for (let k = from; k < to; k++) buffer[k] = line[k];
714
- };
715
- let pos = 0;
716
- while (pos < line.length) {
717
- const exit = state.region ? regionExitAt(line, pos, state.region) : null;
718
- if (state.block) {
719
- const consumed = consumeBlock(line, pos, state, exit);
720
- keep(pos, consumed.end);
721
- pos = consumed.pos;
722
- continue;
723
- }
724
- const event = nextEvent(line, pos, grammar, state, spans);
725
- if (!event) break;
726
- pos = event.idx + event.len;
727
- if (event.kind === "line") {
728
- const consumed = consumeLine(line, pos, state, exit);
729
- keep(pos, consumed.end);
730
- pos = consumed.pos;
731
- if (consumed.done) break;
732
- } else if (event.kind === "block") {
733
- state.block = { open: event.open, close: event.close, nestable: event.nestable, depth: 1 };
734
- } else if (event.kind === "enter") {
735
- state.region = event.region;
736
- } else {
737
- state.region = null;
738
- }
739
- }
740
- return buffer.join("");
741
- }
742
- function attachNeed(m, file, line, character, state, problems) {
743
- const source = m[1] ? makeId(m[1], m[2], m[3], m[4]) : null;
744
- const anchor = source ? state.byId.get(canonicalId(source)) : state.lastItem;
745
- if (!anchor) {
746
- const written = m[5] + (m[6] ? `:${m[6]}` : "") + (m[7] ? `#${m[7]}` : "");
747
- problems.push({
748
- file,
749
- line,
750
- character,
751
- message: source ? `need tag [${source} >> ${written}] has no preceding item tag [${source}] in this file` : `need tag [>>${written}] has no preceding item tag in this file`
752
- });
753
- return;
754
- }
755
- anchor.needs.push(resolveRef(m[5], m[6], m[7], anchor.id));
756
- }
757
- function collectTags(comment, file, line, state, items, problems) {
758
- for (const m of comment.matchAll(TAG_RE)) {
759
- const character = m.index + 1;
760
- if (m[8]) {
761
- const item = newItem(makeId(m[8], m[9], m[10], m[11]), "code", file, line, character);
762
- state.lastItem = item;
763
- state.byId.set(item.canonicalId, item);
764
- items.push(item);
765
- } else {
766
- attachNeed(m, file, line, character, state, problems);
767
- }
768
- }
769
- }
770
- function parseCode(file, text, problems, forwards = []) {
771
- const ext = path2.extname(file).toLowerCase();
772
- const grammar = grammarFor(ext) ?? cLike;
773
- const lines = text.split(/\r?\n/);
774
- const items = [];
775
- const state = { lastItem: null, byId: /* @__PURE__ */ new Map(), block: null, region: null };
776
- for (let i = 0; i < lines.length; i++) {
777
- const comment = commentText(lines[i], state, grammar);
778
- for (const m of comment.matchAll(FORWARD_RE)) {
779
- forwards.push(makeForward(m, 1, file, i + 1, m.index + 1));
780
- }
781
- collectTags(comment, file, i + 1, state, items, problems);
782
- }
783
- return items;
784
- }
785
-
786
- // src/defects.mjs
787
- var DEFECT_KINDS = Object.freeze([
788
- "uncovered-need",
789
- "uncovered-forward",
790
- "orphaned-cover",
791
- "unwanted-cover",
792
- "unwanted-item",
793
- "duplicate-id",
794
- "duplicate-forwarding"
795
- ]);
796
- var uncoveredNeed = (need) => ({
797
- kind: "uncovered-need",
798
- ref: need,
799
- message: `uncovered: needs ${need}, which does not exist`
800
- });
801
- var uncoveredForward = (target) => ({
802
- kind: "uncovered-forward",
803
- ref: target,
804
- message: `uncovered: forwards to ${target}, which does not exist`
805
- });
806
- var orphanedCover = (coverId) => ({
807
- kind: "orphaned-cover",
808
- ref: coverId,
809
- message: `orphaned: covers ${coverId}, which does not exist`
810
- });
811
- var unwantedCover = (coverId, itemId) => ({
812
- kind: "unwanted-cover",
813
- ref: coverId,
814
- message: `unwanted: covers ${coverId}, but ${coverId} does not need ${itemId}`
815
- });
816
- var unwantedItem = (itemId) => ({
817
- kind: "unwanted-item",
818
- ref: itemId,
819
- message: `unwanted: no item needs ${itemId}`
820
- });
821
- var duplicateId = (id, count) => ({
822
- kind: "duplicate-id",
823
- ref: id,
824
- message: `duplicate: ID ${id} is defined ${count} times`
825
- });
826
- var duplicateForwarding = (from, count) => ({
827
- kind: "duplicate-forwarding",
828
- ref: from,
829
- message: `duplicate: forwarding for ${from} is declared ${count} times`
830
- });
831
-
832
- // src/analyze.mjs
833
- function checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, forwardTargets) {
834
- const forwardTarget = forwardTargets.get(item.canonicalId);
835
- if (forwardTarget !== void 0) {
836
- if (!byId.has(canonicalId(forwardTarget)))
837
- item.defects.push(withRevisions(uncoveredForward(forwardTarget)));
838
- } else {
839
- for (const need of item.needs) {
840
- if (matchesOf(need).length === 0)
841
- item.defects.push(withRevisions(uncoveredNeed(need)));
842
- }
843
- }
844
- for (const coverId of item.covers) {
845
- const targets = byId.get(canonicalId(coverId));
846
- if (!targets) {
847
- item.defects.push(withRevisions(orphanedCover(coverId)));
848
- } else if (!targets.some((target) => target.needs.some((need) => idMatches(need, item.id)))) {
849
- item.defects.push(unwantedCover(coverId, item.id));
850
- }
851
- }
852
- if (item.origin === "code" && !isNeeded(item.canonicalId)) {
853
- item.defects.push(unwantedItem(item.id));
854
- }
855
- }
856
- var displayedDuplicateId = (writtenIds, canonical) => writtenIds.every((id) => id === writtenIds[0]) ? writtenIds[0] : canonical;
857
- function dropCyclicForwards(forwardTargets, declarationBySource, problems) {
858
- const done = /* @__PURE__ */ new Set();
859
- for (const start of forwardTargets.keys()) {
860
- if (done.has(start)) continue;
861
- const seen = /* @__PURE__ */ new Map();
862
- const path6 = [];
863
- let current = start;
864
- while (forwardTargets.has(current) && !done.has(current) && !seen.has(current)) {
865
- seen.set(current, path6.length);
866
- path6.push(current);
867
- current = canonicalId(forwardTargets.get(current));
868
- }
869
- if (seen.has(current)) {
870
- const cycle = path6.slice(seen.get(current));
871
- const chain = [...cycle, current].map((id) => declarationBySource.get(id).from).join(" --> ");
872
- for (const id of cycle) {
873
- const declaration = declarationBySource.get(id);
874
- declaration.effective = false;
875
- declaration.voidedBy = "cycle";
876
- problems.push({
877
- file: declaration.file,
878
- line: declaration.line,
879
- character: declaration.character,
880
- message: `cyclic forwarding: ${chain}`
881
- });
882
- forwardTargets.delete(id);
883
- }
884
- }
885
- for (const id of path6) done.add(id);
886
- }
887
- }
888
- function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
889
- const forwardTargets = /* @__PURE__ */ new Map();
890
- const declarationBySource = /* @__PURE__ */ new Map();
891
- const forwardsBySource = /* @__PURE__ */ new Map();
892
- for (const forward of forwards) {
893
- const from = canonicalId(forward.from);
894
- (forwardsBySource.get(from) ?? forwardsBySource.set(from, []).get(from)).push(forward);
895
- }
896
- for (const [from, group] of forwardsBySource) {
897
- const sources = byId.get(from);
898
- if (!sources) {
899
- for (const forward of group) {
900
- forward.effective = false;
901
- forward.voidedBy = "missing-source";
902
- problems.push({
903
- file: forward.file,
904
- line: forward.line,
905
- character: forward.character,
906
- message: `forwarding from ${forward.from}, which does not exist${revHint(forward.from)}`
907
- });
908
- }
909
- continue;
910
- }
911
- if (group.length > 1) {
912
- const shown = displayedDuplicateId(group.map((forward) => forward.from), from);
913
- for (const item of sources) item.defects.push(duplicateForwarding(shown, group.length));
914
- }
915
- group[0].effective = true;
916
- for (let i = 1; i < group.length; i++) {
917
- group[i].effective = false;
918
- group[i].voidedBy = "duplicate";
919
- }
920
- forwardTargets.set(from, group[0].to);
921
- declarationBySource.set(from, group[0]);
922
- }
923
- dropCyclicForwards(forwardTargets, declarationBySource, problems);
924
- for (const to of forwardTargets.values()) neededIds.add(canonicalId(to));
925
- return forwardTargets;
926
- }
927
- function markDeepCoverage(items, byId, matchesOf, forwardTargets) {
928
- const memo = /* @__PURE__ */ new Map();
929
- const deep = (id) => {
930
- if (memo.has(id)) return memo.get(id);
931
- memo.set(id, true);
932
- const group = byId.get(id);
933
- if (!group) {
934
- memo.set(id, false);
935
- return false;
936
- }
937
- const forwardTarget = forwardTargets.get(id);
938
- let ok = true;
939
- if (forwardTarget !== void 0) {
940
- ok = deep(canonicalId(forwardTarget));
941
- } else {
942
- for (const item of group) for (const need of item.needs) if (!needDeep(need)) ok = false;
943
- }
944
- memo.set(id, ok);
945
- return ok;
946
- };
947
- const needDeep = (need) => matchesOf(need).some((id) => deep(id));
948
- for (const item of items) item.deepCovered = deep(item.canonicalId);
949
- }
950
- function groupIdsByKey(byId) {
951
- const idsByKey = /* @__PURE__ */ new Map();
952
- for (const id of byId.keys())
953
- (idsByKey.get(keyOf(id)) ?? idsByKey.set(keyOf(id), []).get(keyOf(id))).push(id);
954
- return idsByKey;
955
- }
956
- function buildWantedBy(items, byId, matchesOf) {
957
- const wantedBy = /* @__PURE__ */ new Map();
958
- for (const item of items)
959
- for (const need of item.needs)
960
- for (const id of matchesOf(need))
961
- for (const provider of byId.get(id))
962
- (wantedBy.get(provider) ?? wantedBy.set(provider, /* @__PURE__ */ new Set()).get(provider)).add(item);
963
- return wantedBy;
964
- }
965
- function buildResolver(items) {
966
- const byId = /* @__PURE__ */ new Map();
967
- for (const item of items) {
968
- (byId.get(item.canonicalId) ?? byId.set(item.canonicalId, []).get(item.canonicalId)).push(item);
969
- }
970
- const idsByKey = groupIdsByKey(byId);
971
- const matchesOf = (ref) => (idsByKey.get(keyOf(ref)) ?? []).filter((id) => idMatches(ref, id));
972
- return { byId, matchesOf, wantedBy: buildWantedBy(items, byId, matchesOf) };
973
- }
974
- function statusOf(item) {
975
- if (item.defects.length > 0) return "defective";
976
- return item.deepCovered ? "deep-covered" : "shallow-covered";
977
- }
978
- function summarize(items, problems) {
979
- const specItems = items.filter((item) => item.origin === "spec").length;
980
- const defectiveItems = items.filter((item) => item.defects.length > 0).length;
981
- const shallowCoveredItems = items.filter(
982
- (item) => item.defects.length === 0 && !item.deepCovered
983
- ).length;
984
- return {
985
- items: items.length,
986
- specItems,
987
- codeItems: items.length - specItems,
988
- okItems: items.length - defectiveItems,
989
- defectiveItems,
990
- shallowCoveredItems,
991
- problems: problems.length
992
- };
993
- }
994
- var isClean = (summary) => summary.defectiveItems === 0 && summary.problems === 0;
995
- function splitNeeds(items) {
996
- const exact = /* @__PURE__ */ new Set();
997
- const wildcard = [];
998
- for (const item of items)
999
- for (const need of item.needs) {
1000
- if (isWildcardRev(revOf(need))) wildcard.push(need);
1001
- else exact.add(canonicalId(need));
1002
- }
1003
- return { exact, wildcard };
1004
- }
1005
- function analyze(items, forwards = [], problems = []) {
1006
- const { byId, matchesOf } = buildResolver(items);
1007
- const revsByKey = /* @__PURE__ */ new Map();
1008
- for (const item of items)
1009
- (revsByKey.get(item.key) ?? revsByKey.set(item.key, /* @__PURE__ */ new Set()).get(item.key)).add(item.revision);
1010
- const { exact: exactNeeds, wildcard: wildcardNeeds } = splitNeeds(items);
1011
- const isNeeded = (canonical) => exactNeeds.has(canonical) || wildcardNeeds.some((wildcard) => idMatches(wildcard, canonical));
1012
- for (const [id, group] of byId) {
1013
- if (group.length > 1) {
1014
- const shown = displayedDuplicateId(group.map((item) => item.id), id);
1015
- for (const item of group) item.defects.push(duplicateId(shown, group.length));
1016
- }
1017
- }
1018
- const existingRevisionsOf = (id) => {
1019
- const revs = revsByKey.get(keyOf(id));
1020
- return revs ? [...revs].sort(compareRev) : null;
1021
- };
1022
- const revHint = (id) => {
1023
- const revs = existingRevisionsOf(id);
1024
- return revs ? ` (revision mismatch: existing revision(s) of ${keyOf(id)}: ${revs.join(", ")})` : "";
1025
- };
1026
- const withRevisions = (defect) => {
1027
- const existingRevisions = existingRevisionsOf(defect.ref);
1028
- if (!existingRevisions) return defect;
1029
- return {
1030
- kind: defect.kind,
1031
- ref: defect.ref,
1032
- existingRevisions,
1033
- message: `${defect.message} (revision mismatch: existing revision(s) of ${keyOf(defect.ref)}: ${existingRevisions.join(", ")})`
1034
- };
1035
- };
1036
- const forwardTargets = buildForwardMap(forwards, byId, exactNeeds, revHint, problems);
1037
- for (const item of items) {
1038
- item.forwardsTo = forwardTargets.get(item.canonicalId) ?? null;
1039
- checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, forwardTargets);
1040
- }
1041
- markDeepCoverage(items, byId, matchesOf, forwardTargets);
1042
- }
1043
-
1044
- // src/report.mjs
1045
- import path3 from "node:path";
1046
- import process2 from "node:process";
1047
- function makeStyler() {
1048
- const on = process2.stdout.isTTY && !process2.env.NO_COLOR;
1049
- const wrap = (code) => (text) => on ? `\x1B[${code}m${text}\x1B[0m` : text;
1050
- return {
1051
- red: wrap("31"),
1052
- green: wrap("32"),
1053
- yellow: wrap("33"),
1054
- cyan: wrap("36"),
1055
- dim: wrap("2"),
1056
- bold: wrap("1")
1057
- };
1058
- }
1059
- var STATUS_STYLES = {
1060
- defective: ["\u2718", "red"],
1061
- "shallow-covered": ["~", "yellow"],
1062
- "deep-covered": ["\u2714", "green"]
1063
- };
1064
- function styledStatus(item, style) {
1065
- const status = statusOf(item);
1066
- const [mark, color] = STATUS_STYLES[status];
1067
- return { mark: style[color](mark), tag: style[color](`[${status}]`) };
1068
- }
1069
- function byFileLine(a, b) {
1070
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
1071
- return a.line - b.line;
1072
- }
1073
- function forwardEdge(item, byId, style, dimLocation) {
1074
- const target = byId.get(canonicalId(item.forwardsTo))?.[0];
1075
- if (!target) return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${style.red("\u2718 missing")}`;
1076
- return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${styledStatus(target, style).mark} ${dimLocation(target.file, target.line)}`;
1077
- }
1078
- function needEdges(item, byId, matchesOf, style, dimLocation) {
1079
- const lines = [];
1080
- for (const need of item.needs) {
1081
- const ids = matchesOf(need);
1082
- if (ids.length === 0) {
1083
- lines.push(` ${style.dim("needs")} ${need} ${style.red("\u2718 missing")}`);
1084
- continue;
1085
- }
1086
- const wildcard = isWildcardRev(revOf(need));
1087
- for (const id of ids) {
1088
- const covering = byId.get(id)[0];
1089
- const arrow = style.dim(`(\u2192 ${covering.id})`);
1090
- const ref = wildcard || covering.id !== need ? `${need} ${arrow}` : need;
1091
- lines.push(` ${style.dim("needs")} ${ref} ${styledStatus(covering, style).mark} ${dimLocation(covering.file, covering.line)}`);
1092
- }
1093
- }
1094
- return lines;
1095
- }
1096
- function coverEdges(item, byId, style, dimLocation) {
1097
- const lines = [];
1098
- for (const coverId of item.covers) {
1099
- const target = byId.get(canonicalId(coverId))?.[0];
1100
- if (!target) lines.push(` ${style.dim("covers")} ${coverId} ${style.red("\u2718 missing")}`);
1101
- else lines.push(` ${style.dim("covers")} ${coverId} ${style.green("\u2714")} ${dimLocation(target.file, target.line)}`);
1102
- }
1103
- return lines;
1104
- }
1105
- function edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation) {
1106
- const lines = [];
1107
- if (item.forwardsTo !== null) lines.push(forwardEdge(item, byId, style, dimLocation));
1108
- else if (item.origin === "spec") lines.push(...needEdges(item, byId, matchesOf, style, dimLocation));
1109
- lines.push(...coverEdges(item, byId, style, dimLocation));
1110
- for (const wanting of wantedBy.get(item) ?? [])
1111
- lines.push(` ${style.dim("wanted by")} ${wanting.id} ${dimLocation(wanting.file, wanting.line)}`);
1112
- return lines;
1113
- }
1114
- function renderVerbose(items, out, style, dimLocation) {
1115
- const { byId, matchesOf, wantedBy } = buildResolver(items);
1116
- const sorted = [...items].sort(byFileLine);
1117
- let prevFile = null;
1118
- for (const item of sorted) {
1119
- if (prevFile !== null && item.file !== prevFile) out.push("");
1120
- prevFile = item.file;
1121
- const { mark, tag } = styledStatus(item, style);
1122
- const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
1123
- out.push(
1124
- `${mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)} ${tag}`,
1125
- ...edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation)
1126
- );
1127
- for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect.message}`);
1128
- }
1129
- if (sorted.length) out.push("");
1130
- }
1131
- function renderDefective(defective, out, style, dimLocation) {
1132
- for (const item of defective) {
1133
- const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
1134
- out.push(
1135
- `${styledStatus(item, style).mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)}`
1136
- );
1137
- for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect.message}`);
1138
- out.push("");
1139
- }
1140
- }
1141
- function renderSummary(summary, out, style) {
1142
- const originBreakdown = style.dim(`(${summary.specItems} from specs, ${summary.codeItems} from code)`);
1143
- const coverageBreakdown = summary.shallowCoveredItems ? " " + style.dim(
1144
- `(${summary.okItems - summary.shallowCoveredItems} deep-covered, ${summary.shallowCoveredItems} only shallow-covered)`
1145
- ) : "";
1146
- out.push(
1147
- style.bold("Summary"),
1148
- ` items ${summary.items} ${originBreakdown}`,
1149
- ` ok ${style.green(String(summary.okItems))}${coverageBreakdown}`,
1150
- ` defective ${summary.defectiveItems ? style.red(String(summary.defectiveItems)) : "0"}`
1151
- );
1152
- if (summary.problems) out.push(` problems ${style.yellow(String(summary.problems))}`);
1153
- out.push("");
1154
- }
1155
- function report(items, problems, cwd, opts = {}) {
1156
- const { verbose = false } = opts;
1157
- const style = makeStyler();
1158
- const relativePath = (file) => path3.relative(cwd, file) || file;
1159
- const dimLocation = (file, line) => style.dim(`${relativePath(file)}:${line}`);
1160
- const summary = summarize(items, problems);
1161
- const out = [];
1162
- if (verbose) renderVerbose(items, out, style, dimLocation);
1163
- else renderDefective(items.filter((item) => item.defects.length > 0), out, style, dimLocation);
1164
- for (const problem of problems) {
1165
- out.push(`${style.yellow("\u26A0")} ${problem.message} ${dimLocation(problem.file, problem.line)}`);
1166
- }
1167
- if (problems.length) out.push("");
1168
- renderSummary(summary, out, style);
1169
- const clean = isClean(summary);
1170
- out.push(clean ? style.green(style.bold("ok")) : style.red(style.bold("not ok")));
1171
- console.log(out.join("\n"));
1172
- return clean;
1173
- }
1174
-
1175
- // src/report-json.mjs
1176
- import path4 from "node:path";
1177
- var SCHEMA_VERSION = 0;
1178
- function coverStatusOf(item) {
1179
- const status = /* @__PURE__ */ new Map();
1180
- for (const defect of item.defects) {
1181
- if (defect.kind === "orphaned-cover") status.set(defect.ref, "orphaned");
1182
- else if (defect.kind === "unwanted-cover") status.set(defect.ref, "unwanted");
1183
- }
1184
- return (ref) => status.get(ref) ?? "valid";
1185
- }
1186
- function buildForwardedFrom(items, byId) {
1187
- const forwardedFrom = /* @__PURE__ */ new Map();
1188
- for (const item of items) {
1189
- if (item.forwardsTo === null) continue;
1190
- for (const target of byId.get(canonicalId(item.forwardsTo)) ?? [])
1191
- (forwardedFrom.get(target) ?? forwardedFrom.set(target, []).get(target)).push(item);
1192
- }
1193
- return forwardedFrom;
1194
- }
1195
- function defectDocument(defect) {
1196
- const out = { kind: defect.kind, ref: defect.ref };
1197
- if (defect.existingRevisions) out.existingRevisions = defect.existingRevisions;
1198
- out.message = defect.message;
1199
- return out;
1200
- }
1201
- function buildReportDocument(items, forwards, problems, cwd, opts = {}) {
1202
- const { version } = opts;
1203
- if (typeof version !== "string")
1204
- throw new TypeError(`opts.version is required: it becomes the document's "flashtrace" field`);
1205
- const relative = (file) => (path4.relative(cwd, file) || file).replaceAll("\\", "/");
1206
- const location = (x) => ({ file: relative(x.file), line: x.line, character: x.character });
1207
- const byLocation = (a, b) => {
1208
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
1209
- if (a.line !== b.line) return a.line - b.line;
1210
- return a.character - b.character;
1211
- };
1212
- const { byId, matchesOf, wantedBy } = buildResolver(items);
1213
- const forwardedFrom = buildForwardedFrom(items, byId);
1214
- const resolvedTo = (ref) => [
1215
- ...new Set(
1216
- matchesOf(ref).sort((a, b) => compareRev(revOf(a), revOf(b))).flatMap((id) => byId.get(id).map((item) => item.id))
1217
- )
1218
- ];
1219
- const itemRefs = (related) => [...related].map((other) => ({ id: other.id, ...location(other) })).sort(byLocation);
1220
- const itemDocument = (item) => {
1221
- const coverStatus = coverStatusOf(item);
1222
- return {
1223
- id: item.id,
1224
- title: item.title,
1225
- origin: item.origin,
1226
- tags: item.tags,
1227
- ...location(item),
1228
- status: statusOf(item),
1229
- defective: item.defects.length > 0,
1230
- deepCovered: item.deepCovered,
1231
- needs: item.needs.map((ref) => ({ ref, resolvedTo: resolvedTo(ref) })),
1232
- covers: item.covers.map((ref) => ({ ref, status: coverStatus(ref) })),
1233
- forwardsTo: item.forwardsTo,
1234
- forwardedFrom: itemRefs(forwardedFrom.get(item) ?? []),
1235
- defects: item.defects.map(defectDocument),
1236
- wantedBy: itemRefs(wantedBy.get(item) ?? [])
1237
- };
1238
- };
1239
- const forwardDocument = (forward) => {
1240
- const document = { from: forward.from, to: forward.to, ...location(forward), effective: forward.effective };
1241
- if (!forward.effective) document.voidedBy = forward.voidedBy;
1242
- return document;
1243
- };
1244
- const itemDocuments = items.map(itemDocument).sort(byLocation);
1245
- const problemDocuments = problems.map((problem) => ({ ...location(problem), message: problem.message })).sort(byLocation);
1246
- const summary = summarize(items, problems);
1247
- return {
1248
- schemaVersion: SCHEMA_VERSION,
1249
- flashtrace: version,
1250
- ok: isClean(summary),
1251
- items: itemDocuments,
1252
- forwards: forwards.map(forwardDocument).sort(byLocation),
1253
- problems: problemDocuments,
1254
- summary
1255
- };
1256
- }
1257
- function reportJson(items, forwards, problems, cwd, opts = {}) {
1258
- const document = buildReportDocument(items, forwards, problems, cwd, opts);
1259
- console.log(JSON.stringify(document, null, 2));
1260
- return document.ok;
1261
- }
1262
-
1263
- // src/cli.mjs
1264
- var HELP = `Usage: flashtrace [options] [directory-or-file ...]
1265
-
1266
- Traces requirement coverage between Markdown specifications and source code
1267
- (.ts, .js, .mjs, .sql, .vue). Defaults to the current directory. Files ignored
1268
- by git are excluded.
1269
-
1270
- Options:
1271
- -t, --tags <t1,t2,...> only import spec items carrying one of these
1272
- tags; add "_" to also include untagged items
1273
- -f, --format <format> report format: "text" (default) or "json"; --json
1274
- is shorthand for --format json
1275
- -v, --verbose list every item with its coverage status and trace
1276
- edges, not only the defective ones; text format only
1277
- -V, --version print the version number
1278
- -h, --help show this help
1279
-
1280
- Long options also accept "="-attached values, e.g. --tags=a,b.
1281
- The report format and the tag filter may each be selected only once.
1282
-
1283
- Exit codes: 0 clean, 1 defects or problems found, 2 usage error`;
1284
- function packageVersion() {
1285
- const pkg = new URL("../package.json", import.meta.url);
1286
- return JSON.parse(readFileSync(pkg, "utf8")).version;
1287
- }
1288
- function splitLongOption(token) {
1289
- const eqIndex = token.startsWith("--") ? token.indexOf("=") : -1;
1290
- return eqIndex === -1 ? [token, void 0] : [token.slice(0, eqIndex), token.slice(eqIndex + 1)];
1291
- }
1292
- function rejectValue(name, inline) {
1293
- if (inline !== void 0) throw new UsageError(`option ${name} does not take a value`);
1294
- }
1295
- function selectOnce(opts, raw, setting, subject) {
1296
- const selectedBy = opts.selectedBy.get(setting);
1297
- if (selectedBy !== void 0)
1298
- throw new UsageError(`${subject} is already selected by ${selectedBy}`);
1299
- opts.selectedBy.set(setting, raw);
1300
- }
1301
- function selectFormat(opts, raw, format) {
1302
- selectOnce(opts, raw, "format", "the report format");
1303
- opts.format = format;
1304
- }
1305
- function reportFormat(raw, value) {
1306
- if (value !== "text" && value !== "json")
1307
- throw new UsageError(`invalid value for ${raw}: "${value}" (expected "text" or "json")`);
1308
- return value;
1309
- }
1310
- var LONG_ALIAS = {
1311
- "-h": "--help",
1312
- "-v": "--verbose",
1313
- "-V": "--version",
1314
- "-t": "--tags",
1315
- "-f": "--format"
1316
- };
1317
- function printHelp() {
1318
- console.log(HELP);
1319
- process3.exit(0);
1320
- }
1321
- function printVersion() {
1322
- console.log(packageVersion());
1323
- process3.exit(0);
1324
- }
1325
- function enableVerbose(opts) {
1326
- opts.verbose = true;
1327
- }
1328
- function selectJsonFormat(opts, raw) {
1329
- selectFormat(opts, raw, "json");
1330
- }
1331
- var VALUELESS_OPTIONS = /* @__PURE__ */ new Map([
1332
- ["--help", printHelp],
1333
- ["--version", printVersion],
1334
- ["--verbose", enableVerbose],
1335
- ["--json", selectJsonFormat]
1336
- ]);
1337
- function setFormat(opts, raw, value) {
1338
- selectFormat(opts, raw, reportFormat(raw, value));
1339
- }
1340
- function setTags(opts, raw, value) {
1341
- selectOnce(opts, raw, "tags", "the tag filter");
1342
- opts.tags = value.split(",").map((tag) => tag.trim()).filter(Boolean);
1343
- }
1344
- var VALUED_OPTIONS = /* @__PURE__ */ new Map([
1345
- ["--format", setFormat],
1346
- ["--tags", setTags]
1347
- ]);
1348
- function parseArgs(argv) {
1349
- const opts = { dirs: [], tags: null, verbose: false, format: "text", selectedBy: /* @__PURE__ */ new Map() };
1350
- for (let i = 0; i < argv.length; i++) {
1351
- const [raw, inline] = splitLongOption(argv[i]);
1352
- const name = LONG_ALIAS[raw] ?? raw;
1353
- const applyValuelessOption = VALUELESS_OPTIONS.get(name);
1354
- const applyValuedOption = VALUED_OPTIONS.get(name);
1355
- if (applyValuelessOption) {
1356
- rejectValue(raw, inline);
1357
- applyValuelessOption(opts, raw);
1358
- } else if (applyValuedOption) {
1359
- const value = inline ?? argv[++i];
1360
- if (!value) throw new UsageError(`missing value for ${raw}`);
1361
- applyValuedOption(opts, raw, value);
1362
- } else if (raw.startsWith("-")) {
1363
- throw new UsageError(`unknown option: ${raw}`);
1364
- } else {
1365
- opts.dirs.push(raw);
1366
- }
1367
- }
1368
- if (opts.format === "json" && opts.verbose)
1369
- throw new UsageError("-v/--verbose applies to the text format only");
1370
- if (opts.dirs.length === 0) opts.dirs.push(".");
1371
- return opts;
1372
- }
1373
- async function main() {
1374
- const opts = parseArgs(process3.argv.slice(2));
1375
- const files = await collectFiles(opts.dirs);
1376
- const problems = [];
1377
- const forwards = [];
1378
- let items = [];
1379
- for (const file of files) {
1380
- const text = await fs2.readFile(file, "utf8");
1381
- const ext = path5.extname(file).toLowerCase();
1382
- items.push(
1383
- ...SPEC_EXT.has(ext) ? parseMarkdown(file, text, problems, forwards) : parseCode(file, text, problems, forwards)
1384
- );
1385
- }
1386
- if (opts.tags) {
1387
- const wantUntagged = opts.tags.includes("_");
1388
- items = items.filter(
1389
- (item) => item.origin === "code" || item.tags.some((tag) => opts.tags.includes(tag)) || wantUntagged && item.tags.length === 0
1390
- );
1391
- }
1392
- analyze(items, forwards, problems);
1393
- const clean = opts.format === "json" ? reportJson(items, forwards, problems, process3.cwd(), { version: packageVersion() }) : report(items, problems, process3.cwd(), { verbose: opts.verbose });
1394
- process3.exitCode = clean ? 0 : 1;
1395
- }
1396
- function runCli() {
1397
- main().catch((err) => {
1398
- if (err instanceof UsageError) {
1399
- console.error(`error: ${err.message}
1400
-
1401
- ${HELP}`);
1402
- process3.exit(2);
1403
- }
1404
- console.error(err);
1405
- process3.exit(2);
1406
- });
1407
- }
1408
-
1409
- // src/main.mjs
1410
- function runAsCli() {
1411
- const argvPath = process4.argv[1];
1412
- if (!argvPath) return false;
1413
- try {
1414
- return realpathSync(argvPath) === realpathSync(fileURLToPath(import.meta.url));
1415
- } catch {
1416
- return import.meta.url === pathToFileURL(argvPath).href;
1417
- }
1418
- }
1419
- if (runAsCli()) runCli();
1420
- export {
1421
- DEFECT_KINDS,
1422
- UsageError,
1423
- analyze,
1424
- buildReportDocument,
1425
- collectFiles,
1426
- parseCode,
1427
- parseMarkdown,
1428
- reportJson
1429
- };