flashtrace 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +57 -15
  2. package/dist/flashtrace.mjs +376 -292
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,24 +1,61 @@
1
- <p align="center">
2
- <a href="https://github.com/flashtrace">
3
- <img src="https://github.com/flashtrace.png" alt="flashtrace logo" width="120">
4
- </a>
5
- </p>
1
+ <div align="center">
2
+ <table>
3
+ <tr>
4
+ <td align="center">
5
+ <a href="https://github.com/flashtrace">
6
+ <img src="https://github.com/flashtrace.png" alt="flashtrace logo" width="140">
7
+ </a>
8
+ </td>
9
+ <td align="left">
10
+ <h3>flashtrace</h3>
11
+ <p>
12
+ Lightning-fast, reference-based requirement tracing that works anywhere.
13
+ </p>
14
+ <p>
15
+ <a href="https://github.com/flashtrace/flashtrace/blob/main/docs/index.md">
16
+ <img src="https://img.shields.io/badge/Spec-Driven-8e4d13.svg?labelColor=1e1e1e" alt="Spec-driven documentation." />
17
+ </a>
18
+ <a href="https://github.com/flashtrace/flashtrace/blob/main/CLAUDE.md">
19
+ <img src="https://img.shields.io/badge/Agent-Native-d97d0e.svg?labelColor=1e1e1e" alt="This repository was created agent-native." />
20
+ </a>
21
+ <a href="https://github.com/flashtrace/flashtrace/blob/main/LICENSE">
22
+ <img src="https://img.shields.io/badge/License-Apache_2.0-f9c21d.svg?labelColor=1e1e1e" alt="Released under the Apache 2.0 license." />
23
+ </a>
24
+ </p>
25
+ </td>
26
+ </tr>
27
+ </table>
28
+ </div>
6
29
 
7
- <h3 align="center">flashtrace</h3>
30
+ ---
31
+ ---
8
32
 
9
- <p align="center">
10
- Lightning-fast, reference-based requirement tracing that works anywhere.
11
- </p>
33
+ <h4 align="center">Quality Summary</h4>
12
34
 
13
35
  <p align="center">
14
- <a href="https://github.com/flashtrace/flashtrace/blob/main/docs/index.md">
15
- <img src="https://img.shields.io/badge/Spec-Driven-8e4d13.svg?labelColor=1e1e1e" alt="Spec-driven documentation." />
36
+ <a href="https://sonarcloud.io/project/overview?id=flashtrace_flashtrace">
37
+ <img src="https://github.com/flashtrace/flashtrace/actions/workflows/ci.yml/badge.svg" alt="Continuous Integration status." />
38
+ </a>
39
+ <a href="https://sonarcloud.io/component_measures?metric=reliability_rating&id=flashtrace_flashtrace">
40
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=reliability_rating" alt="SonarCloud reliability rating." />
16
41
  </a>
17
- <a href="https://github.com/flashtrace/flashtrace/blob/main/CLAUDE.md">
18
- <img src="https://img.shields.io/badge/Agent-Native-d97d0e.svg?labelColor=1e1e1e" alt="This repository was created agent-native." />
42
+ <a href="https://sonarcloud.io/component_measures?metric=security_rating&id=flashtrace_flashtrace">
43
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=security_rating" alt="SonarCloud security rating." />
19
44
  </a>
20
- <a href="https://github.com/flashtrace/flashtrace/blob/main/LICENSE">
21
- <img src="https://img.shields.io/badge/License-Apache_2.0-f9c21d.svg?labelColor=1e1e1e" alt="Released under the Apache 2.0 license." />
45
+ <a href="https://sonarcloud.io/component_measures?metric=sqale_rating&id=flashtrace_flashtrace">
46
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=sqale_rating" alt="SonarCloud maintainability rating." />
47
+ </a>
48
+ <a href="https://sonarcloud.io/component_measures?metric=ncloc&id=flashtrace_flashtrace">
49
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=ncloc" alt="Number of lines of code." />
50
+ </a>
51
+ <a href="https://sonarcloud.io/component_measures?metric=code_smells&id=flashtrace_flashtrace">
52
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=code_smells" alt="SonarCloud amount of code smells." />
53
+ </a>
54
+ <a href="https://sonarcloud.io/component_measures?metric=duplicated_lines&id=flashtrace_flashtrace">
55
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=duplicated_lines_density" alt="SonarCloud percent of duplicated lines." />
56
+ </a>
57
+ <a href="https://sonarcloud.io/component_measures?metric=vulnerabilities&id=flashtrace_flashtrace">
58
+ <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=vulnerabilities" alt="SonarCloud amount of vulnerabilities." />
22
59
  </a>
23
60
  </p>
24
61
 
@@ -33,6 +70,11 @@ You can then execute `npx flashtrace` to run the tracing.
33
70
  Read our [Usage Guide](docs/USAGE.md) for more details.
34
71
  Node >= 18 is required for flashtrace to work.
35
72
 
73
+ Looking for a working setup to start from? The [examples/](examples/) folder
74
+ holds four self-contained example projects, from a minimal clean trace to a
75
+ deliberately broken one showing every defect flashtrace reports. Each has a
76
+ README, and the end-to-end tests verify their exact report output on every run.
77
+
36
78
  ## About flashtrace
37
79
 
38
80
  Let's be honest: This project started when I needed it myself.
@@ -187,11 +187,11 @@ async function walk(dir, out) {
187
187
  } catch {
188
188
  return out;
189
189
  }
190
- for (const e of entries) {
191
- if (e.name === ".git" || e.name === "node_modules") continue;
192
- const p = path.join(dir, e.name);
193
- if (e.isDirectory()) await walk(p, out);
194
- else if (e.isFile()) out.push(p);
190
+ for (const entry of entries) {
191
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
192
+ const entryPath = path.join(dir, entry.name);
193
+ if (entry.isDirectory()) await walk(entryPath, out);
194
+ else if (entry.isFile()) out.push(entryPath);
195
195
  }
196
196
  return out;
197
197
  }
@@ -199,9 +199,9 @@ async function collectFiles(dirs) {
199
199
  const files = /* @__PURE__ */ new Set();
200
200
  for (const dir of dirs) {
201
201
  const abs = path.resolve(dir);
202
- const st = await fs.stat(abs).catch(() => null);
203
- if (!st) throw new UsageError(`input path does not exist: ${dir}`);
204
- if (st.isFile()) {
202
+ const stats = await fs.stat(abs).catch(() => null);
203
+ if (!stats) throw new UsageError(`input path does not exist: ${dir}`);
204
+ if (stats.isFile()) {
205
205
  files.add(abs);
206
206
  continue;
207
207
  }
@@ -218,52 +218,52 @@ async function collectFiles(dirs) {
218
218
  } catch {
219
219
  list = await walk(abs, []);
220
220
  }
221
- for (const f of list) files.add(f);
221
+ for (const file of list) files.add(file);
222
222
  }
223
- return [...files].filter((f) => {
224
- const ext = path.extname(f).toLowerCase();
223
+ return [...files].filter((file) => {
224
+ const ext = path.extname(file).toLowerCase();
225
225
  return MD_EXT.has(ext) || CODE_EXT.has(ext);
226
226
  }).sort(compareStrings);
227
227
  }
228
228
 
229
229
  // src/ids.mjs
230
- var SEG_SRC = "[A-Za-z][A-Za-z0-9_.-]*";
230
+ var SEGMENT_SRC = "[A-Za-z][A-Za-z0-9_.-]*";
231
231
  var REV_SRC = String.raw`\d+(?:\.\d+){0,2}`;
232
- var WILD_SRC = String.raw`(?:\d+\.\d+\.x|\d+\.x\.y|x\.y\.z|\d+\.x|x\.y|x)`;
233
- var REVREF_SRC = `(?:${WILD_SRC}|${REV_SRC})`;
234
- var ID_SRC = String.raw`([A-Za-z]+):(?:((?:${SEG_SRC}\/)*${SEG_SRC})\/)?(${SEG_SRC})#(${REV_SRC})`;
232
+ var WILDCARD_SRC = String.raw`(?:\d+\.\d+\.x|\d+\.x\.y|x\.y\.z|\d+\.x|x\.y|x)`;
233
+ var REV_REF_SRC = `(?:${WILDCARD_SRC}|${REV_SRC})`;
234
+ var ID_SRC = String.raw`([A-Za-z]+):(?:((?:${SEGMENT_SRC}\/)*${SEGMENT_SRC})\/)?(${SEGMENT_SRC})#(${REV_SRC})`;
235
235
  var ID_RE = new RegExp(`^${ID_SRC}$`);
236
- var NEED_ID_SRC = String.raw`([A-Za-z]+):(?:((?:${SEG_SRC}\/)*${SEG_SRC})\/)?(${SEG_SRC})#(${REVREF_SRC})`;
236
+ var NEED_ID_SRC = String.raw`([A-Za-z]+):(?:((?:${SEGMENT_SRC}\/)*${SEGMENT_SRC})\/)?(${SEGMENT_SRC})#(${REV_REF_SRC})`;
237
237
  var NEED_ID_RE = new RegExp(`^${NEED_ID_SRC}$`);
238
238
  var FORWARD_SRC = String.raw`\[\s*${ID_SRC}\s*-->\s*${ID_SRC}\s*\]`;
239
- var mkId = (type, group, name, rev) => `${type}:${group ? group + "/" : ""}${name}#${rev}`;
240
- var mkForward = (m, base, file, line) => ({
241
- from: mkId(m[base], m[base + 1], m[base + 2], m[base + 3]),
242
- to: mkId(m[base + 4], m[base + 5], m[base + 6], m[base + 7]),
239
+ var makeId = (type, group, name, rev) => `${type}:${group ? group + "/" : ""}${name}#${rev}`;
240
+ var makeForward = (m, base, file, line) => ({
241
+ from: makeId(m[base], m[base + 1], m[base + 2], m[base + 3]),
242
+ to: makeId(m[base + 4], m[base + 5], m[base + 6], m[base + 7]),
243
243
  file,
244
244
  line
245
245
  });
246
246
  var keyOf = (id) => id.slice(0, id.lastIndexOf("#"));
247
247
  var revOf = (id) => id.slice(id.lastIndexOf("#") + 1);
248
248
  function compareRev(a, b) {
249
- const pa = a.split(".");
250
- const pb = b.split(".");
251
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
252
- if (i >= pa.length) return -1;
253
- if (i >= pb.length) return 1;
254
- if (pa[i] !== pb[i]) return Number(pa[i]) - Number(pb[i]);
249
+ const partsA = a.split(".");
250
+ const partsB = b.split(".");
251
+ for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
252
+ if (i >= partsA.length) return -1;
253
+ if (i >= partsB.length) return 1;
254
+ if (partsA[i] !== partsB[i]) return Number(partsA[i]) - Number(partsB[i]);
255
255
  }
256
256
  return 0;
257
257
  }
258
- var WILD_LAYER = /* @__PURE__ */ new Set(["x", "y", "z"]);
258
+ var WILDCARD_LAYERS = /* @__PURE__ */ new Set(["x", "y", "z"]);
259
259
  var isWildcardRev = (rev) => /[xyz]/.test(rev);
260
260
  function revMatches(pattern, concrete) {
261
- const pp = pattern.split(".");
262
- const cp = concrete.split(".");
263
- if (pp.length !== cp.length) return false;
264
- for (let i = 0; i < pp.length; i++) {
265
- if (WILD_LAYER.has(pp[i])) continue;
266
- if (pp[i] !== cp[i]) return false;
261
+ const patternParts = pattern.split(".");
262
+ const concreteParts = concrete.split(".");
263
+ if (patternParts.length !== concreteParts.length) return false;
264
+ for (let i = 0; i < patternParts.length; i++) {
265
+ if (WILDCARD_LAYERS.has(patternParts[i])) continue;
266
+ if (patternParts[i] !== concreteParts[i]) return false;
267
267
  }
268
268
  return true;
269
269
  }
@@ -271,12 +271,12 @@ var idMatches = (need, id) => keyOf(need) === keyOf(id) && revMatches(revOf(need
271
271
  function parseIdEntry(raw) {
272
272
  const cleaned = raw.replaceAll("`", "").trim();
273
273
  const m = cleaned.match(ID_RE);
274
- return m ? mkId(m[1], m[2], m[3], m[4]) : null;
274
+ return m ? makeId(m[1], m[2], m[3], m[4]) : null;
275
275
  }
276
276
  function parseNeedEntry(raw) {
277
277
  const cleaned = raw.replaceAll("`", "").trim();
278
278
  const m = cleaned.match(NEED_ID_RE);
279
- return m ? mkId(m[1], m[2], m[3], m[4]) : null;
279
+ return m ? makeId(m[1], m[2], m[3], m[4]) : null;
280
280
  }
281
281
  function newItem(id, origin, file, line) {
282
282
  return {
@@ -299,24 +299,51 @@ function newItem(id, origin, file, line) {
299
299
  }
300
300
 
301
301
  // src/parse-markdown.mjs
302
- var DEF_RE = new RegExp(String.raw`^\s*\`${ID_SRC}\`\s*$`);
302
+ var DEFINITION_RE = new RegExp(String.raw`^\s*\`${ID_SRC}\`\s*$`);
303
303
  var HEADING_RE = /^(#{1,6})\s+(\S(?:.*\S)?)\s*$/;
304
+ var SETEXT_UNDERLINE_RE = /^ {0,3}(?:=+|-+)[ \t]*$/;
305
+ var THEMATIC_BREAK_RE = /^ {0,3}-{3,}[ \t]*$/;
304
306
  var KEYWORD_RE = /^(Needs|Covers|Tags):\s*((?:\S.*)?)$/;
305
307
  var BULLET_RE = /^\s*[-*+]\s+(\S(?:.*\S)?)\s*$/;
306
- var DELIM_CELL_RE = /^:?-+:?$/;
308
+ var DELIMITER_CELL_RE = /^:?-+:?$/;
307
309
  var FORWARD_LINE_RE = new RegExp(String.raw`^\s*(\`?)${FORWARD_SRC}\1\s*$`);
308
- var isBoundary = (l) => DEF_RE.test(l) || HEADING_RE.test(l);
309
- function takeForward(line, file, n, forwards) {
310
- const f = line.match(FORWARD_LINE_RE);
311
- if (f) forwards.push(mkForward(f, 2, file, n + 1));
312
- return !!f;
313
- }
314
- function titleAbove(lines, defIndex) {
315
- for (let k = defIndex - 1; k >= 0; k--) {
316
- const l = lines[k];
317
- if (l.trim() === "") continue;
318
- const h = l.match(HEADING_RE);
319
- return h ? h[2] : null;
310
+ function takeForward(line, file, lineIndex, forwards) {
311
+ const forward = line.match(FORWARD_LINE_RE);
312
+ if (forward) forwards.push(makeForward(forward, 2, file, lineIndex + 1));
313
+ return !!forward;
314
+ }
315
+ function isParagraphLine(line) {
316
+ return line.trim() !== "" && !HEADING_RE.test(line) && !BULLET_RE.test(line) && !SETEXT_UNDERLINE_RE.test(line);
317
+ }
318
+ var isParagraphAt = (lines, inTable, j) => !inTable[j] && isParagraphLine(lines[j]);
319
+ var isSetextHeading = (lines, inTable, titleIndex) => titleIndex + 1 < lines.length && SETEXT_UNDERLINE_RE.test(lines[titleIndex + 1]) && isParagraphAt(lines, inTable, titleIndex);
320
+ function opensSetextHeading(lines, inTable, j) {
321
+ if (!isParagraphAt(lines, inTable, j)) return false;
322
+ let k = j;
323
+ while (k + 1 < lines.length && isParagraphAt(lines, inTable, k + 1)) k++;
324
+ return isSetextHeading(lines, inTable, k);
325
+ }
326
+ var isBoundary = (lines, inTable, j) => !inTable[j] && DEFINITION_RE.test(lines[j]) || HEADING_RE.test(lines[j]) || opensSetextHeading(lines, inTable, j);
327
+ function foldSetextTitle(lines, inTable, lastIndex) {
328
+ let first = lastIndex;
329
+ while (first > 0 && isParagraphAt(lines, inTable, first - 1)) first--;
330
+ let title = "";
331
+ for (let k = first; k <= lastIndex; k++) {
332
+ title += lines[k].trim();
333
+ if (k < lastIndex) title += / {2}$/.test(lines[k]) ? "\n" : " ";
334
+ }
335
+ return title;
336
+ }
337
+ function titleAbove(lines, inTable, definitionIndex) {
338
+ for (let k = definitionIndex - 1; k >= 0; k--) {
339
+ const line = lines[k];
340
+ if (line.trim() === "") continue;
341
+ const heading = line.match(HEADING_RE);
342
+ if (heading) return heading[2];
343
+ if (k > 0 && isSetextHeading(lines, inTable, k - 1)) {
344
+ return foldSetextTitle(lines, inTable, k - 1);
345
+ }
346
+ return null;
320
347
  }
321
348
  return null;
322
349
  }
@@ -326,81 +353,127 @@ function keywordEntries(lines, j, inline) {
326
353
  }
327
354
  const entries = [];
328
355
  while (j + 1 < lines.length) {
329
- const b = lines[j + 1].match(BULLET_RE);
330
- if (!b) break;
331
- entries.push(b[1].trim());
356
+ const bullet = lines[j + 1].match(BULLET_RE);
357
+ if (!bullet) break;
358
+ entries.push(bullet[1].trim());
332
359
  j++;
333
360
  }
334
361
  return { entries, j };
335
362
  }
336
363
  function rowCells(line) {
337
- let s = line.trim();
338
- if (!s.includes("|")) return null;
339
- if (s.startsWith("|")) s = s.slice(1);
340
- if (s.endsWith("|")) s = s.slice(0, -1);
341
- return s.split("|").map((c) => c.trim());
364
+ let row = line.trim();
365
+ if (!row.includes("|")) return null;
366
+ if (row.startsWith("|")) row = row.slice(1);
367
+ if (row.endsWith("|")) row = row.slice(0, -1);
368
+ return row.split("|").map((cell) => cell.trim());
342
369
  }
343
- function takeKeywordTable(lines, j, item, file, problems) {
370
+ function tableStartsAt(lines, j) {
344
371
  const header = rowCells(lines[j]);
345
- if (!header) return null;
372
+ if (!header) return false;
373
+ const delimiter = j + 1 < lines.length ? rowCells(lines[j + 1]) : null;
374
+ return delimiter?.length === header.length && delimiter.every((cell) => DELIMITER_CELL_RE.test(cell));
375
+ }
376
+ 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));
377
+ var rowCellsInTable = (line) => rowCells(line) ?? [line.trim()];
378
+ var isKeywordCell = (cell) => cell === "Needs" || cell === "Covers" || cell === "Tags";
379
+ function scanTables(lines, file, problems) {
380
+ const inTable = new Array(lines.length).fill(false);
381
+ let j = 0;
382
+ while (j < lines.length) {
383
+ if (!tableStartsAt(lines, j)) {
384
+ j++;
385
+ continue;
386
+ }
387
+ const keywordColumns = /* @__PURE__ */ new Set();
388
+ rowCells(lines[j]).forEach((cell, col) => {
389
+ if (isKeywordCell(cell)) keywordColumns.add(col);
390
+ });
391
+ const start = j;
392
+ let end = j + 1;
393
+ while (end + 1 < lines.length && continuesTable(lines[end + 1])) end++;
394
+ for (let k = start; k <= end; k++) {
395
+ inTable[k] = true;
396
+ if (k === start + 1) continue;
397
+ rowCellsInTable(lines[k]).forEach((cell, col) => {
398
+ const definition = keywordColumns.has(col) ? null : cell.match(DEFINITION_RE);
399
+ if (definition)
400
+ problems.push({
401
+ file,
402
+ line: k + 1,
403
+ message: `item ${makeId(definition[1], definition[2], definition[3], definition[4])} defined inside a table; a table cell is not an item definition`
404
+ });
405
+ });
406
+ }
407
+ j = end + 1;
408
+ }
409
+ return inTable;
410
+ }
411
+ function takeKeywordTable(lines, inTable, j, item, file, problems) {
412
+ if (!inTable[j] || j > 0 && inTable[j - 1]) return null;
346
413
  const columns = [];
347
- header.forEach((cell, col) => {
348
- if (cell === "Needs" || cell === "Covers" || cell === "Tags") columns.push([col, cell]);
414
+ rowCells(lines[j]).forEach((cell, col) => {
415
+ if (isKeywordCell(cell)) columns.push([col, cell]);
349
416
  });
350
417
  if (columns.length === 0) return null;
351
- const delim = j + 1 < lines.length ? rowCells(lines[j + 1]) : null;
352
- if (delim?.length !== header.length || !delim.every((c) => DELIM_CELL_RE.test(c))) return null;
353
418
  j++;
354
- while (j + 1 < lines.length && !isBoundary(lines[j + 1])) {
355
- const cells = rowCells(lines[j + 1]);
356
- if (!cells) break;
419
+ while (j + 1 < lines.length && inTable[j + 1]) {
357
420
  j++;
421
+ const cells = rowCellsInTable(lines[j]);
358
422
  for (const [col, keyword] of columns) {
359
- if (cells[col]) applyKeyword(item, keyword, [cells[col]], file, j + 1, problems);
423
+ if (cells[col])
424
+ applyKeyword(item, keyword, [cells[col]], file, j + 1, problems, `the ${keyword} column of ${item.id}`);
360
425
  }
361
426
  }
362
427
  return j;
363
428
  }
364
- function applyKeyword(item, keyword, entries, file, kwLine, problems) {
429
+ function applyKeyword(item, keyword, entries, file, keywordLine, problems, source) {
365
430
  if (keyword === "Tags") {
366
431
  item.tags.push(...entries);
367
432
  return;
368
433
  }
369
434
  const target = keyword === "Needs" ? "needs" : "covers";
370
435
  const parse = keyword === "Needs" ? parseNeedEntry : parseIdEntry;
371
- for (const e of entries) {
372
- const id = parse(e);
436
+ for (const entry of entries) {
437
+ const id = parse(entry);
373
438
  if (id) item[target].push(id);
374
439
  else
375
440
  problems.push({
376
441
  file,
377
- line: kwLine,
378
- message: `invalid ID "${e}" in ${keyword}: list of ${item.id}`
442
+ line: keywordLine,
443
+ message: `invalid ID "${entry}" in ${source}`
379
444
  });
380
445
  }
381
446
  }
382
- function parseItemBody(lines, start, item, file, problems, forwards) {
447
+ function parseItemBody(lines, inTable, start, item, file, problems, forwards) {
383
448
  let j = start;
384
- let descDone = false;
385
- while (j < lines.length && !isBoundary(lines[j])) {
449
+ let descriptionDone = false;
450
+ while (j < lines.length && !isBoundary(lines, inTable, j)) {
386
451
  const line = lines[j];
387
452
  if (takeForward(line, file, j, forwards)) {
388
453
  j++;
389
454
  continue;
390
455
  }
391
- const kw = line.match(KEYWORD_RE);
392
- const tableEnd = kw ? null : takeKeywordTable(lines, j, item, file, problems);
393
- if (kw) {
394
- descDone = true;
395
- const collected = keywordEntries(lines, j, kw[2]);
396
- applyKeyword(item, kw[1], collected.entries, file, j + 1, problems);
456
+ const keywordMatch = line.match(KEYWORD_RE);
457
+ const tableEnd = keywordMatch ? null : takeKeywordTable(lines, inTable, j, item, file, problems);
458
+ if (keywordMatch) {
459
+ descriptionDone = true;
460
+ const collected = keywordEntries(lines, j, keywordMatch[2]);
461
+ applyKeyword(
462
+ item,
463
+ keywordMatch[1],
464
+ collected.entries,
465
+ file,
466
+ j + 1,
467
+ problems,
468
+ `${keywordMatch[1]}: list of ${item.id}`
469
+ );
397
470
  j = collected.j;
398
471
  } else if (tableEnd !== null) {
399
- descDone = true;
472
+ descriptionDone = true;
400
473
  j = tableEnd;
401
474
  } else if (line.trim() === "") {
402
- if (item.description.length > 0) descDone = true;
403
- } else if (!descDone) {
475
+ if (item.description.length > 0) descriptionDone = true;
476
+ } else if (!descriptionDone) {
404
477
  item.description.push(line.trim());
405
478
  }
406
479
  j++;
@@ -409,21 +482,32 @@ function parseItemBody(lines, start, item, file, problems, forwards) {
409
482
  }
410
483
  function parseMarkdown(file, text, problems, forwards = []) {
411
484
  const lines = text.split(/\r?\n/);
485
+ const inTable = scanTables(lines, file, problems);
412
486
  const items = [];
413
487
  let i = 0;
414
488
  while (i < lines.length) {
415
- if (takeForward(lines[i], file, i, forwards)) {
489
+ const startsHeading = opensSetextHeading(lines, inTable, i);
490
+ if (!startsHeading && takeForward(lines[i], file, i, forwards)) {
491
+ i++;
492
+ continue;
493
+ }
494
+ const definition = inTable[i] ? null : lines[i].match(DEFINITION_RE);
495
+ if (definition && startsHeading) {
496
+ problems.push({
497
+ file,
498
+ line: i + 1,
499
+ message: `item ${makeId(definition[1], definition[2], definition[3], definition[4])} defined inside a setext heading; a heading is not an item definition`
500
+ });
416
501
  i++;
417
502
  continue;
418
503
  }
419
- const def = lines[i].match(DEF_RE);
420
- if (!def) {
504
+ if (!definition) {
421
505
  i++;
422
506
  continue;
423
507
  }
424
- const item = newItem(mkId(def[1], def[2], def[3], def[4]), "markdown", file, i + 1);
425
- item.title = titleAbove(lines, i);
426
- i = parseItemBody(lines, i + 1, item, file, problems, forwards);
508
+ const item = newItem(makeId(definition[1], definition[2], definition[3], definition[4]), "markdown", file, i + 1);
509
+ item.title = titleAbove(lines, inTable, i);
510
+ i = parseItemBody(lines, inTable, i + 1, item, file, problems, forwards);
427
511
  items.push(item);
428
512
  }
429
513
  return items;
@@ -440,39 +524,39 @@ function activeLeaf(grammar, state) {
440
524
  if (state.region) return state.region.grammar;
441
525
  return grammar.regions ? grammar.default : grammar;
442
526
  }
443
- function matchAt(re, s, pos) {
527
+ function matchAt(re, line, pos) {
444
528
  re.lastIndex = pos;
445
- return re.exec(s);
529
+ return re.exec(line);
446
530
  }
447
- function* regionEvents(s, pos, grammar, state) {
531
+ function* regionEvents(line, pos, grammar, state) {
448
532
  if (!grammar.regions) return;
449
533
  if (state.region) {
450
- const m = matchAt(state.region.exit, s, pos);
534
+ const m = matchAt(state.region.exit, line, pos);
451
535
  if (m) yield { idx: m.index, kind: "exit", len: m[0].length };
452
536
  return;
453
537
  }
454
- for (const r of grammar.regions) {
455
- const m = matchAt(r.enter, s, pos);
538
+ for (const region of grammar.regions) {
539
+ const m = matchAt(region.enter, line, pos);
456
540
  if (m) {
457
- const leaf = typeof r.grammar === "function" ? r.grammar(m[0]) : r.grammar;
458
- yield { idx: m.index, kind: "enter", len: m[0].length, region: { exit: r.exit, grammar: leaf } };
541
+ const leaf = typeof region.grammar === "function" ? region.grammar(m[0]) : region.grammar;
542
+ yield { idx: m.index, kind: "enter", len: m[0].length, region: { exit: region.exit, grammar: leaf } };
459
543
  }
460
544
  }
461
545
  }
462
- function nextEvent(s, pos, grammar, state) {
546
+ function nextEvent(line, pos, grammar, state) {
463
547
  const leaf = activeLeaf(grammar, state);
464
548
  let best = null;
465
- const consider = (idx, ev) => {
549
+ const consider = (idx, event) => {
466
550
  if (idx === -1) return;
467
- if (best === null || idx < best.idx || idx === best.idx && ev.len > best.len) {
468
- best = { ...ev, idx };
551
+ if (best === null || idx < best.idx || idx === best.idx && event.len > best.len) {
552
+ best = { ...event, idx };
469
553
  }
470
554
  };
471
555
  for (const marker of leaf.line) {
472
- consider(s.indexOf(marker, pos), { kind: "line", len: marker.length });
556
+ consider(line.indexOf(marker, pos), { kind: "line", len: marker.length });
473
557
  }
474
558
  for (const [open, close, nestable] of leaf.block) {
475
- consider(s.indexOf(open, pos), {
559
+ consider(line.indexOf(open, pos), {
476
560
  kind: "block",
477
561
  len: open.length,
478
562
  open,
@@ -480,16 +564,16 @@ function nextEvent(s, pos, grammar, state) {
480
564
  nestable: Boolean(nestable)
481
565
  });
482
566
  }
483
- for (const ev of regionEvents(s, pos, grammar, state)) consider(ev.idx, ev);
567
+ for (const event of regionEvents(line, pos, grammar, state)) consider(event.idx, event);
484
568
  return best;
485
569
  }
486
- function readBlockRest(s, pos, block, limit = s.length) {
570
+ function readBlockRest(line, pos, block, limit = line.length) {
487
571
  const { open, close, nestable } = block;
488
572
  const within = (idx) => idx !== -1 && idx < limit ? idx : -1;
489
573
  let i = pos;
490
574
  while (i < limit) {
491
- const closeIdx = within(s.indexOf(close, i));
492
- const openIdx = within(nestable ? s.indexOf(open, i) : -1);
575
+ const closeIdx = within(line.indexOf(close, i));
576
+ const openIdx = within(nestable ? line.indexOf(open, i) : -1);
493
577
  if (closeIdx === -1 && openIdx === -1) break;
494
578
  if (openIdx !== -1 && (closeIdx === -1 || openIdx < closeIdx)) {
495
579
  block.depth++;
@@ -498,16 +582,16 @@ function readBlockRest(s, pos, block, limit = s.length) {
498
582
  }
499
583
  block.depth--;
500
584
  i = closeIdx + close.length;
501
- if (block.depth === 0) return { text: s.slice(pos, closeIdx) + " ", pos: i, closed: true };
585
+ if (block.depth === 0) return { text: line.slice(pos, closeIdx) + " ", pos: i, closed: true };
502
586
  }
503
- return { text: s.slice(pos, limit) + " ", pos: limit, closed: false };
587
+ return { text: line.slice(pos, limit) + " ", pos: limit, closed: false };
504
588
  }
505
- function regionExitAt(s, pos, region) {
506
- const m = matchAt(region.exit, s, pos);
589
+ function regionExitAt(line, pos, region) {
590
+ const m = matchAt(region.exit, line, pos);
507
591
  return m ? { idx: m.index, len: m[0].length } : null;
508
592
  }
509
- function consumeBlock(s, pos, state, exit) {
510
- const rest = readBlockRest(s, pos, state.block, exit ? exit.idx : s.length);
593
+ function consumeBlock(line, pos, state, exit) {
594
+ const rest = readBlockRest(line, pos, state.block, exit ? exit.idx : line.length);
511
595
  if (rest.closed) {
512
596
  state.block = null;
513
597
  return { text: rest.text, pos: rest.pos };
@@ -519,36 +603,36 @@ function consumeBlock(s, pos, state, exit) {
519
603
  }
520
604
  return { text: rest.text, pos: rest.pos };
521
605
  }
522
- function consumeLine(s, pos, state, exit) {
606
+ function consumeLine(line, pos, state, exit) {
523
607
  if (exit) {
524
608
  state.region = null;
525
- return { text: s.slice(pos, exit.idx) + " ", pos: exit.idx + exit.len, done: false };
609
+ return { text: line.slice(pos, exit.idx) + " ", pos: exit.idx + exit.len, done: false };
526
610
  }
527
- return { text: s.slice(pos) + " ", pos: s.length, done: true };
611
+ return { text: line.slice(pos) + " ", pos: line.length, done: true };
528
612
  }
529
- function commentText(s, state, grammar) {
613
+ function commentText(line, state, grammar) {
530
614
  let comment = "";
531
615
  let pos = 0;
532
- while (pos < s.length) {
533
- const exit = state.region ? regionExitAt(s, pos, state.region) : null;
616
+ while (pos < line.length) {
617
+ const exit = state.region ? regionExitAt(line, pos, state.region) : null;
534
618
  if (state.block) {
535
- const r = consumeBlock(s, pos, state, exit);
536
- comment += r.text;
537
- pos = r.pos;
619
+ const consumed = consumeBlock(line, pos, state, exit);
620
+ comment += consumed.text;
621
+ pos = consumed.pos;
538
622
  continue;
539
623
  }
540
- const ev = nextEvent(s, pos, grammar, state);
541
- if (!ev) break;
542
- pos = ev.idx + ev.len;
543
- if (ev.kind === "line") {
544
- const r = consumeLine(s, pos, state, exit);
545
- comment += r.text;
546
- pos = r.pos;
547
- if (r.done) break;
548
- } else if (ev.kind === "block") {
549
- state.block = { open: ev.open, close: ev.close, nestable: ev.nestable, depth: 1 };
550
- } else if (ev.kind === "enter") {
551
- state.region = ev.region;
624
+ const event = nextEvent(line, pos, grammar, state);
625
+ if (!event) break;
626
+ pos = event.idx + event.len;
627
+ if (event.kind === "line") {
628
+ const consumed = consumeLine(line, pos, state, exit);
629
+ comment += consumed.text;
630
+ pos = consumed.pos;
631
+ if (consumed.done) break;
632
+ } else if (event.kind === "block") {
633
+ state.block = { open: event.open, close: event.close, nestable: event.nestable, depth: 1 };
634
+ } else if (event.kind === "enter") {
635
+ state.region = event.region;
552
636
  } else {
553
637
  state.region = null;
554
638
  }
@@ -558,15 +642,15 @@ function commentText(s, state, grammar) {
558
642
  function collectTags(comment, file, line, state, items, problems) {
559
643
  for (const m of comment.matchAll(TAG_RE)) {
560
644
  if (m[9]) {
561
- const item = newItem(mkId(m[9], m[10], m[11], m[12]), "code", file, line);
562
- state.last = item;
645
+ const item = newItem(makeId(m[9], m[10], m[11], m[12]), "code", file, line);
646
+ state.lastItem = item;
563
647
  state.byId.set(item.id, item);
564
648
  items.push(item);
565
649
  continue;
566
650
  }
567
- const id = mkId(m[5], m[6], m[7], m[8]);
651
+ const id = makeId(m[5], m[6], m[7], m[8]);
568
652
  if (m[1]) {
569
- const source = mkId(m[1], m[2], m[3], m[4]);
653
+ const source = makeId(m[1], m[2], m[3], m[4]);
570
654
  const anchor = state.byId.get(source);
571
655
  if (anchor) {
572
656
  anchor.needs.push(id);
@@ -577,8 +661,8 @@ function collectTags(comment, file, line, state, items, problems) {
577
661
  message: `need tag [${source} >> ${id}] has no preceding item tag [${source}] in this file`
578
662
  });
579
663
  }
580
- } else if (state.last) {
581
- state.last.needs.push(id);
664
+ } else if (state.lastItem) {
665
+ state.lastItem.needs.push(id);
582
666
  } else {
583
667
  problems.push({
584
668
  file,
@@ -593,11 +677,11 @@ function parseCode(file, text, problems, forwards = []) {
593
677
  const grammar = grammarFor(ext) ?? cLike;
594
678
  const lines = text.split(/\r?\n/);
595
679
  const items = [];
596
- const state = { last: null, byId: /* @__PURE__ */ new Map(), block: null, region: null };
680
+ const state = { lastItem: null, byId: /* @__PURE__ */ new Map(), block: null, region: null };
597
681
  for (let i = 0; i < lines.length; i++) {
598
682
  const comment = commentText(lines[i], state, grammar);
599
683
  for (const m of comment.matchAll(FORWARD_RE)) {
600
- forwards.push(mkForward(m, 1, file, i + 1));
684
+ forwards.push(makeForward(m, 1, file, i + 1));
601
685
  }
602
686
  collectTags(comment, file, i + 1, state, items, problems);
603
687
  }
@@ -605,82 +689,82 @@ function parseCode(file, text, problems, forwards = []) {
605
689
  }
606
690
 
607
691
  // src/analyze.mjs
608
- function checkItemReferences(it, byId, matchesOf, isNeeded, revHint, fwdTarget) {
609
- const fwd = fwdTarget.get(it.id);
610
- if (fwd !== void 0) {
611
- if (!byId.has(fwd))
612
- it.defects.push(`uncovered: forwards to ${fwd}, which does not exist${revHint(fwd)}`);
692
+ function checkItemReferences(item, byId, matchesOf, isNeeded, revHint, forwardTargets) {
693
+ const forwardTarget = forwardTargets.get(item.id);
694
+ if (forwardTarget !== void 0) {
695
+ if (!byId.has(forwardTarget))
696
+ item.defects.push(`uncovered: forwards to ${forwardTarget}, which does not exist${revHint(forwardTarget)}`);
613
697
  } else {
614
- for (const n of it.needs) {
615
- if (matchesOf(n).length === 0)
616
- it.defects.push(`uncovered: needs ${n}, which does not exist${revHint(n)}`);
698
+ for (const need of item.needs) {
699
+ if (matchesOf(need).length === 0)
700
+ item.defects.push(`uncovered: needs ${need}, which does not exist${revHint(need)}`);
617
701
  }
618
702
  }
619
- for (const c of it.covers) {
620
- const targets = byId.get(c);
703
+ for (const coverId of item.covers) {
704
+ const targets = byId.get(coverId);
621
705
  if (!targets) {
622
- it.defects.push(`orphaned: covers ${c}, which does not exist${revHint(c)}`);
623
- } else if (!targets.some((t) => t.needs.some((n) => idMatches(n, it.id)))) {
624
- it.defects.push(`unwanted: covers ${c}, but ${c} does not need ${it.id}`);
706
+ item.defects.push(`orphaned: covers ${coverId}, which does not exist${revHint(coverId)}`);
707
+ } else if (!targets.some((target) => target.needs.some((need) => idMatches(need, item.id)))) {
708
+ item.defects.push(`unwanted: covers ${coverId}, but ${coverId} does not need ${item.id}`);
625
709
  }
626
710
  }
627
- if (it.origin === "code" && !isNeeded(it.id)) {
628
- it.defects.push(`unwanted: no item needs ${it.id}`);
711
+ if (item.origin === "code" && !isNeeded(item.id)) {
712
+ item.defects.push(`unwanted: no item needs ${item.id}`);
629
713
  }
630
714
  }
631
- function dropCyclicForwards(fwdTarget, declBySource, problems) {
715
+ function dropCyclicForwards(forwardTargets, declarationBySource, problems) {
632
716
  const done = /* @__PURE__ */ new Set();
633
- for (const start of fwdTarget.keys()) {
717
+ for (const start of forwardTargets.keys()) {
634
718
  if (done.has(start)) continue;
635
719
  const seen = /* @__PURE__ */ new Map();
636
720
  const path5 = [];
637
- let cur = start;
638
- while (fwdTarget.has(cur) && !done.has(cur) && !seen.has(cur)) {
639
- seen.set(cur, path5.length);
640
- path5.push(cur);
641
- cur = fwdTarget.get(cur);
721
+ let current = start;
722
+ while (forwardTargets.has(current) && !done.has(current) && !seen.has(current)) {
723
+ seen.set(current, path5.length);
724
+ path5.push(current);
725
+ current = forwardTargets.get(current);
642
726
  }
643
- if (seen.has(cur)) {
644
- const cycle = path5.slice(seen.get(cur));
645
- const chain = [...cycle, cur].join(" --> ");
727
+ if (seen.has(current)) {
728
+ const cycle = path5.slice(seen.get(current));
729
+ const chain = [...cycle, current].join(" --> ");
646
730
  for (const id of cycle) {
647
- const f = declBySource.get(id);
648
- problems.push({ file: f.file, line: f.line, message: `cyclic forwarding: ${chain}` });
649
- fwdTarget.delete(id);
731
+ const declaration = declarationBySource.get(id);
732
+ problems.push({ file: declaration.file, line: declaration.line, message: `cyclic forwarding: ${chain}` });
733
+ forwardTargets.delete(id);
650
734
  }
651
735
  }
652
736
  for (const id of path5) done.add(id);
653
737
  }
654
738
  }
655
739
  function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
656
- const fwdTarget = /* @__PURE__ */ new Map();
657
- const declBySource = /* @__PURE__ */ new Map();
658
- const fwdBySource = /* @__PURE__ */ new Map();
659
- for (const f of forwards) {
660
- (fwdBySource.get(f.from) ?? fwdBySource.set(f.from, []).get(f.from)).push(f);
740
+ const forwardTargets = /* @__PURE__ */ new Map();
741
+ const declarationBySource = /* @__PURE__ */ new Map();
742
+ const forwardsBySource = /* @__PURE__ */ new Map();
743
+ for (const forward of forwards) {
744
+ (forwardsBySource.get(forward.from) ?? forwardsBySource.set(forward.from, []).get(forward.from)).push(forward);
661
745
  }
662
- for (const [from, group] of fwdBySource) {
746
+ for (const [from, group] of forwardsBySource) {
663
747
  const sources = byId.get(from);
664
748
  if (!sources) {
665
- for (const f of group)
749
+ for (const forward of group)
666
750
  problems.push({
667
- file: f.file,
668
- line: f.line,
751
+ file: forward.file,
752
+ line: forward.line,
669
753
  message: `forwarding from ${from}, which does not exist${revHint(from)}`
670
754
  });
671
755
  continue;
672
756
  }
673
757
  if (group.length > 1)
674
- for (const it of sources)
675
- it.defects.push(`duplicate: forwarding for ${from} is declared ${group.length} times`);
676
- fwdTarget.set(from, group[0].to);
677
- declBySource.set(from, group[0]);
758
+ for (const item of sources)
759
+ item.defects.push(`duplicate: forwarding for ${from} is declared ${group.length} times`);
760
+ forwardTargets.set(from, group[0].to);
761
+ declarationBySource.set(from, group[0]);
678
762
  }
679
- dropCyclicForwards(fwdTarget, declBySource, problems);
680
- for (const to of fwdTarget.values()) neededIds.add(to);
681
- return fwdTarget;
763
+ dropCyclicForwards(forwardTargets, declarationBySource, problems);
764
+ for (const to of forwardTargets.values()) neededIds.add(to);
765
+ return forwardTargets;
682
766
  }
683
- function markDeepCoverage(items, byId, matchesOf, fwdTarget) {
767
+ function markDeepCoverage(items, byId, matchesOf, forwardTargets) {
684
768
  const memo = /* @__PURE__ */ new Map();
685
769
  const deep = (id) => {
686
770
  if (memo.has(id)) return memo.get(id);
@@ -690,18 +774,18 @@ function markDeepCoverage(items, byId, matchesOf, fwdTarget) {
690
774
  memo.set(id, false);
691
775
  return false;
692
776
  }
693
- const fwd = fwdTarget.get(id);
777
+ const forwardTarget = forwardTargets.get(id);
694
778
  let ok = true;
695
- if (fwd !== void 0) {
696
- ok = deep(fwd);
779
+ if (forwardTarget !== void 0) {
780
+ ok = deep(forwardTarget);
697
781
  } else {
698
- for (const it of group) for (const n of it.needs) if (!needDeep(n)) ok = false;
782
+ for (const item of group) for (const need of item.needs) if (!needDeep(need)) ok = false;
699
783
  }
700
784
  memo.set(id, ok);
701
785
  return ok;
702
786
  };
703
- const needDeep = (n) => matchesOf(n).some((id) => deep(id));
704
- for (const it of items) it.deepCovered = deep(it.id);
787
+ const needDeep = (need) => matchesOf(need).some((id) => deep(id));
788
+ for (const item of items) item.deepCovered = deep(item.id);
705
789
  }
706
790
  function groupIdsByKey(byId) {
707
791
  const idsByKey = /* @__PURE__ */ new Map();
@@ -711,7 +795,7 @@ function groupIdsByKey(byId) {
711
795
  }
712
796
  function buildResolver(items) {
713
797
  const byId = /* @__PURE__ */ new Map();
714
- for (const it of items) (byId.get(it.id) ?? byId.set(it.id, []).get(it.id)).push(it);
798
+ for (const item of items) (byId.get(item.id) ?? byId.set(item.id, []).get(item.id)).push(item);
715
799
  const idsByKey = groupIdsByKey(byId);
716
800
  const matchesOf = (ref) => (idsByKey.get(keyOf(ref)) ?? []).filter((id) => idMatches(ref, id));
717
801
  return { byId, matchesOf };
@@ -719,34 +803,34 @@ function buildResolver(items) {
719
803
  function splitNeeds(items) {
720
804
  const exact = /* @__PURE__ */ new Set();
721
805
  const wildcard = [];
722
- for (const it of items)
723
- for (const n of it.needs) {
724
- if (isWildcardRev(revOf(n))) wildcard.push(n);
725
- else exact.add(n);
806
+ for (const item of items)
807
+ for (const need of item.needs) {
808
+ if (isWildcardRev(revOf(need))) wildcard.push(need);
809
+ else exact.add(need);
726
810
  }
727
811
  return { exact, wildcard };
728
812
  }
729
813
  function analyze(items, forwards = [], problems = []) {
730
814
  const { byId, matchesOf } = buildResolver(items);
731
815
  const revsByKey = /* @__PURE__ */ new Map();
732
- for (const it of items)
733
- (revsByKey.get(it.key) ?? revsByKey.set(it.key, /* @__PURE__ */ new Set()).get(it.key)).add(it.revision);
816
+ for (const item of items)
817
+ (revsByKey.get(item.key) ?? revsByKey.set(item.key, /* @__PURE__ */ new Set()).get(item.key)).add(item.revision);
734
818
  const { exact: exactNeeds, wildcard: wildcardNeeds } = splitNeeds(items);
735
- const isNeeded = (id) => exactNeeds.has(id) || wildcardNeeds.some((w) => idMatches(w, id));
819
+ const isNeeded = (id) => exactNeeds.has(id) || wildcardNeeds.some((wildcard) => idMatches(wildcard, id));
736
820
  for (const [id, group] of byId) {
737
821
  if (group.length > 1)
738
- for (const it of group) it.defects.push(`duplicate: ID ${id} is defined ${group.length} times`);
822
+ for (const item of group) item.defects.push(`duplicate: ID ${id} is defined ${group.length} times`);
739
823
  }
740
824
  const revHint = (id) => {
741
825
  const revs = revsByKey.get(keyOf(id));
742
826
  return revs ? ` (revision mismatch: existing revision(s) of ${keyOf(id)}: ${[...revs].sort(compareRev).join(", ")})` : "";
743
827
  };
744
- const fwdTarget = buildForwardMap(forwards, byId, exactNeeds, revHint, problems);
745
- for (const it of items) {
746
- it.forwardsTo = fwdTarget.get(it.id) ?? null;
747
- checkItemReferences(it, byId, matchesOf, isNeeded, revHint, fwdTarget);
828
+ const forwardTargets = buildForwardMap(forwards, byId, exactNeeds, revHint, problems);
829
+ for (const item of items) {
830
+ item.forwardsTo = forwardTargets.get(item.id) ?? null;
831
+ checkItemReferences(item, byId, matchesOf, isNeeded, revHint, forwardTargets);
748
832
  }
749
- markDeepCoverage(items, byId, matchesOf, fwdTarget);
833
+ markDeepCoverage(items, byId, matchesOf, forwardTargets);
750
834
  }
751
835
 
752
836
  // src/report.mjs
@@ -754,7 +838,7 @@ import path3 from "node:path";
754
838
  import process2 from "node:process";
755
839
  function makeStyler() {
756
840
  const on = process2.stdout.isTTY && !process2.env.NO_COLOR;
757
- const wrap = (code) => (s) => on ? `\x1B[${code}m${s}\x1B[0m` : s;
841
+ const wrap = (code) => (text) => on ? `\x1B[${code}m${text}\x1B[0m` : text;
758
842
  return {
759
843
  red: wrap("31"),
760
844
  green: wrap("32"),
@@ -764,124 +848,124 @@ function makeStyler() {
764
848
  bold: wrap("1")
765
849
  };
766
850
  }
767
- function statusOf(it, c) {
768
- if (it.defects.length > 0) return { mark: c.red("\u2718"), tag: c.red("[defective]") };
769
- if (!it.deepCovered) return { mark: c.yellow("~"), tag: c.yellow("[shallow-covered]") };
770
- return { mark: c.green("\u2714"), tag: c.green("[deep-covered]") };
851
+ function statusOf(item, style) {
852
+ if (item.defects.length > 0) return { mark: style.red("\u2718"), tag: style.red("[defective]") };
853
+ if (!item.deepCovered) return { mark: style.yellow("~"), tag: style.yellow("[shallow-covered]") };
854
+ return { mark: style.green("\u2714"), tag: style.green("[deep-covered]") };
771
855
  }
772
856
  function buildWantedBy(items, byId, matchesOf) {
773
857
  const wantedBy = /* @__PURE__ */ new Map();
774
- for (const it of items)
775
- for (const n of it.needs)
776
- for (const id of matchesOf(n))
777
- for (const m of byId.get(id))
778
- (wantedBy.get(m) ?? wantedBy.set(m, /* @__PURE__ */ new Set()).get(m)).add(it);
858
+ for (const item of items)
859
+ for (const need of item.needs)
860
+ for (const id of matchesOf(need))
861
+ for (const provider of byId.get(id))
862
+ (wantedBy.get(provider) ?? wantedBy.set(provider, /* @__PURE__ */ new Set()).get(provider)).add(item);
779
863
  return wantedBy;
780
864
  }
781
865
  function byFileLine(a, b) {
782
866
  if (a.file !== b.file) return a.file < b.file ? -1 : 1;
783
867
  return a.line - b.line;
784
868
  }
785
- function forwardEdge(it, byId, c, dimLoc) {
786
- const target = byId.get(it.forwardsTo)?.[0];
787
- if (!target) return ` ${c.cyan("\u2192")} ${it.forwardsTo} ${c.red("\u2718 missing")}`;
788
- return ` ${c.cyan("\u2192")} ${it.forwardsTo} ${statusOf(target, c).mark} ${dimLoc(target.file, target.line)}`;
869
+ function forwardEdge(item, byId, style, dimLocation) {
870
+ const target = byId.get(item.forwardsTo)?.[0];
871
+ if (!target) return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${style.red("\u2718 missing")}`;
872
+ return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${statusOf(target, style).mark} ${dimLocation(target.file, target.line)}`;
789
873
  }
790
- function needEdges(it, byId, matchesOf, c, dimLoc) {
874
+ function needEdges(item, byId, matchesOf, style, dimLocation) {
791
875
  const lines = [];
792
- for (const n of it.needs) {
793
- const ids = matchesOf(n);
876
+ for (const need of item.needs) {
877
+ const ids = matchesOf(need);
794
878
  if (ids.length === 0) {
795
- lines.push(` ${c.dim("needs")} ${n} ${c.red("\u2718 missing")}`);
879
+ lines.push(` ${style.dim("needs")} ${need} ${style.red("\u2718 missing")}`);
796
880
  continue;
797
881
  }
798
- const wild = isWildcardRev(revOf(n));
882
+ const wildcard = isWildcardRev(revOf(need));
799
883
  for (const id of ids) {
800
- const m = byId.get(id)[0];
801
- const arrow = c.dim(`(\u2192 ${id})`);
802
- const ref = wild ? `${n} ${arrow}` : n;
803
- lines.push(` ${c.dim("needs")} ${ref} ${statusOf(m, c).mark} ${dimLoc(m.file, m.line)}`);
884
+ const covering = byId.get(id)[0];
885
+ const arrow = style.dim(`(\u2192 ${id})`);
886
+ const ref = wildcard ? `${need} ${arrow}` : need;
887
+ lines.push(` ${style.dim("needs")} ${ref} ${statusOf(covering, style).mark} ${dimLocation(covering.file, covering.line)}`);
804
888
  }
805
889
  }
806
890
  return lines;
807
891
  }
808
- function coverEdges(it, byId, c, dimLoc) {
892
+ function coverEdges(item, byId, style, dimLocation) {
809
893
  const lines = [];
810
- for (const cv of it.covers) {
811
- const target = byId.get(cv)?.[0];
812
- if (!target) lines.push(` ${c.dim("covers")} ${cv} ${c.red("\u2718 missing")}`);
813
- else lines.push(` ${c.dim("covers")} ${cv} ${c.green("\u2714")} ${dimLoc(target.file, target.line)}`);
894
+ for (const coverId of item.covers) {
895
+ const target = byId.get(coverId)?.[0];
896
+ if (!target) lines.push(` ${style.dim("covers")} ${coverId} ${style.red("\u2718 missing")}`);
897
+ else lines.push(` ${style.dim("covers")} ${coverId} ${style.green("\u2714")} ${dimLocation(target.file, target.line)}`);
814
898
  }
815
899
  return lines;
816
900
  }
817
- function edgeLines(it, byId, matchesOf, wantedBy, c, dimLoc) {
901
+ function edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation) {
818
902
  const lines = [];
819
- if (it.forwardsTo !== null) lines.push(forwardEdge(it, byId, c, dimLoc));
820
- else if (it.origin === "markdown") lines.push(...needEdges(it, byId, matchesOf, c, dimLoc));
821
- lines.push(...coverEdges(it, byId, c, dimLoc));
822
- for (const w of wantedBy.get(it) ?? [])
823
- lines.push(` ${c.dim("wanted by")} ${w.id} ${dimLoc(w.file, w.line)}`);
903
+ if (item.forwardsTo !== null) lines.push(forwardEdge(item, byId, style, dimLocation));
904
+ else if (item.origin === "markdown") lines.push(...needEdges(item, byId, matchesOf, style, dimLocation));
905
+ lines.push(...coverEdges(item, byId, style, dimLocation));
906
+ for (const wanting of wantedBy.get(item) ?? [])
907
+ lines.push(` ${style.dim("wanted by")} ${wanting.id} ${dimLocation(wanting.file, wanting.line)}`);
824
908
  return lines;
825
909
  }
826
- function renderVerbose(items, out, c, dimLoc) {
910
+ function renderVerbose(items, out, style, dimLocation) {
827
911
  const { byId, matchesOf } = buildResolver(items);
828
912
  const wantedBy = buildWantedBy(items, byId, matchesOf);
829
913
  const sorted = [...items].sort(byFileLine);
830
914
  let prevFile = null;
831
- for (const it of sorted) {
832
- if (prevFile !== null && it.file !== prevFile) out.push("");
833
- prevFile = it.file;
834
- const { mark, tag } = statusOf(it, c);
835
- const title = it.title ? " " + c.dim(`"${it.title}"`) : "";
915
+ for (const item of sorted) {
916
+ if (prevFile !== null && item.file !== prevFile) out.push("");
917
+ prevFile = item.file;
918
+ const { mark, tag } = statusOf(item, style);
919
+ const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
836
920
  out.push(
837
- `${mark} ${c.bold(it.id)}${title} ${dimLoc(it.file, it.line)} ${tag}`,
838
- ...edgeLines(it, byId, matchesOf, wantedBy, c, dimLoc)
921
+ `${mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)} ${tag}`,
922
+ ...edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation)
839
923
  );
840
- for (const d of it.defects) out.push(` ${c.red("\u2022")} ${d}`);
924
+ for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect}`);
841
925
  }
842
926
  if (sorted.length) out.push("");
843
927
  }
844
- function renderDefective(defective, out, c, dimLoc) {
845
- for (const it of defective) {
846
- const title = it.title ? " " + c.dim(`"${it.title}"`) : "";
928
+ function renderDefective(defective, out, style, dimLocation) {
929
+ for (const item of defective) {
930
+ const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
847
931
  out.push(
848
- `${statusOf(it, c).mark} ${c.bold(it.id)}${title} ${dimLoc(it.file, it.line)}`
932
+ `${statusOf(item, style).mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)}`
849
933
  );
850
- for (const d of it.defects) out.push(` ${c.red("\u2022")} ${d}`);
934
+ for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect}`);
851
935
  out.push("");
852
936
  }
853
937
  }
854
- function renderSummary(items, defective, problems, out, c) {
938
+ function renderSummary(items, defective, problems, out, style) {
855
939
  const okCount = items.length - defective.length;
856
- const notDeep = items.filter((it) => it.defects.length === 0 && !it.deepCovered).length;
857
- const md = items.filter((i) => i.origin === "markdown").length;
858
- const originBreakdown = c.dim(`(${md} from markdown, ${items.length - md} from code)`);
940
+ const shallowCount = items.filter((item) => item.defects.length === 0 && !item.deepCovered).length;
941
+ const markdownCount = items.filter((item) => item.origin === "markdown").length;
942
+ const originBreakdown = style.dim(`(${markdownCount} from markdown, ${items.length - markdownCount} from code)`);
859
943
  out.push(
860
- c.bold("Summary"),
944
+ style.bold("Summary"),
861
945
  ` items ${items.length} ${originBreakdown}`,
862
- ` ok ${c.green(String(okCount))}`,
863
- ` defective ${defective.length ? c.red(String(defective.length)) : "0"}`
946
+ ` ok ${style.green(String(okCount))}`,
947
+ ` defective ${defective.length ? style.red(String(defective.length)) : "0"}`
864
948
  );
865
- if (notDeep) out.push(" " + c.dim(`of the ok items, ${notDeep} are only shallow-covered (an item further down the tracing chain is defective)`));
866
- if (problems.length) out.push(` problems ${c.yellow(String(problems.length))}`);
949
+ if (shallowCount) out.push(" " + style.dim(`of the ok items, ${shallowCount} are only shallow-covered (an item further down the tracing chain is defective)`));
950
+ if (problems.length) out.push(` problems ${style.yellow(String(problems.length))}`);
867
951
  out.push("");
868
952
  }
869
953
  function report(items, problems, cwd, opts = {}) {
870
954
  const { verbose = false } = opts;
871
- const c = makeStyler();
872
- const rel = (f) => path3.relative(cwd, f) || f;
873
- const dimLoc = (file, line) => c.dim(`${rel(file)}:${line}`);
874
- const defective = items.filter((it) => it.defects.length > 0);
955
+ const style = makeStyler();
956
+ const relativePath = (file) => path3.relative(cwd, file) || file;
957
+ const dimLocation = (file, line) => style.dim(`${relativePath(file)}:${line}`);
958
+ const defective = items.filter((item) => item.defects.length > 0);
875
959
  const out = [];
876
- if (verbose) renderVerbose(items, out, c, dimLoc);
877
- else renderDefective(defective, out, c, dimLoc);
878
- for (const p of problems) {
879
- out.push(`${c.yellow("\u26A0")} ${p.message} ${dimLoc(p.file, p.line)}`);
960
+ if (verbose) renderVerbose(items, out, style, dimLocation);
961
+ else renderDefective(defective, out, style, dimLocation);
962
+ for (const problem of problems) {
963
+ out.push(`${style.yellow("\u26A0")} ${problem.message} ${dimLocation(problem.file, problem.line)}`);
880
964
  }
881
965
  if (problems.length) out.push("");
882
- renderSummary(items, defective, problems, out, c);
966
+ renderSummary(items, defective, problems, out, style);
883
967
  const clean = defective.length === 0 && problems.length === 0;
884
- out.push(clean ? c.green(c.bold("ok")) : c.red(c.bold("not ok")));
968
+ out.push(clean ? style.green(style.bold("ok")) : style.red(style.bold("not ok")));
885
969
  console.log(out.join("\n"));
886
970
  return clean;
887
971
  }
@@ -909,8 +993,8 @@ function packageVersion() {
909
993
  return JSON.parse(readFileSync(pkg, "utf8")).version;
910
994
  }
911
995
  function splitLongOption(token) {
912
- const eq = token.startsWith("--") ? token.indexOf("=") : -1;
913
- return eq === -1 ? [token, null] : [token.slice(0, eq), token.slice(eq + 1)];
996
+ const eqIndex = token.startsWith("--") ? token.indexOf("=") : -1;
997
+ return eqIndex === -1 ? [token, null] : [token.slice(0, eqIndex), token.slice(eqIndex + 1)];
914
998
  }
915
999
  function rejectValue(name, inline) {
916
1000
  if (inline !== null) throw new UsageError(`option ${name} does not take a value`);
@@ -918,26 +1002,26 @@ function rejectValue(name, inline) {
918
1002
  function parseArgs(argv) {
919
1003
  const opts = { dirs: [], tags: null, verbose: false };
920
1004
  for (let i = 0; i < argv.length; i++) {
921
- const [a, inline] = splitLongOption(argv[i]);
922
- if (a === "-h" || a === "--help") {
923
- rejectValue(a, inline);
1005
+ const [name, inline] = splitLongOption(argv[i]);
1006
+ if (name === "-h" || name === "--help") {
1007
+ rejectValue(name, inline);
924
1008
  console.log(HELP);
925
1009
  process3.exit(0);
926
- } else if (a === "-v" || a === "--verbose") {
927
- rejectValue(a, inline);
1010
+ } else if (name === "-v" || name === "--verbose") {
1011
+ rejectValue(name, inline);
928
1012
  opts.verbose = true;
929
- } else if (a === "-V" || a === "--version") {
930
- rejectValue(a, inline);
1013
+ } else if (name === "-V" || name === "--version") {
1014
+ rejectValue(name, inline);
931
1015
  console.log(packageVersion());
932
1016
  process3.exit(0);
933
- } else if (a === "-t" || a === "--tags") {
934
- const v = inline ?? argv[++i];
935
- if (!v) throw new UsageError(`missing value for ${a}`);
936
- opts.tags = v.split(",").map((s) => s.trim()).filter(Boolean);
937
- } else if (a.startsWith("-")) {
938
- throw new UsageError(`unknown option: ${a}`);
1017
+ } else if (name === "-t" || name === "--tags") {
1018
+ const value = inline ?? argv[++i];
1019
+ if (!value) throw new UsageError(`missing value for ${name}`);
1020
+ opts.tags = value.split(",").map((s) => s.trim()).filter(Boolean);
1021
+ } else if (name.startsWith("-")) {
1022
+ throw new UsageError(`unknown option: ${name}`);
939
1023
  } else {
940
- opts.dirs.push(a);
1024
+ opts.dirs.push(name);
941
1025
  }
942
1026
  }
943
1027
  if (opts.dirs.length === 0) opts.dirs.push(".");
@@ -959,7 +1043,7 @@ async function main() {
959
1043
  if (opts.tags) {
960
1044
  const wantUntagged = opts.tags.includes("_");
961
1045
  items = items.filter(
962
- (it) => it.origin === "code" || it.tags.some((t) => opts.tags.includes(t)) || wantUntagged && it.tags.length === 0
1046
+ (item) => item.origin === "code" || item.tags.some((tag) => opts.tags.includes(tag)) || wantUntagged && item.tags.length === 0
963
1047
  );
964
1048
  }
965
1049
  analyze(items, forwards, problems);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flashtrace",
3
- "version": "0.7.2",
3
+ "version": "0.9.0",
4
4
  "description": "Lightning-fast, reference-based requirement tracing that works anywhere.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {