flashtrace 0.11.5 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -56,6 +56,18 @@
56
56
  <a href="https://sonarcloud.io/component_measures?metric=vulnerabilities&id=flashtrace_flashtrace">
57
57
  <img src="https://sonarcloud.io/api/project_badges/measure?project=flashtrace_flashtrace&metric=vulnerabilities" alt="SonarCloud amount of vulnerabilities." />
58
58
  </a>
59
+ <!--
60
+ The coverage and tests badges read from the orphan `badges` branch,
61
+ which CI rewrites on every push to main. They therefore always show
62
+ main's last published numbers - never the numbers of the branch this
63
+ README is viewed on.
64
+ -->
65
+ <a href="https://github.com/flashtrace/flashtrace/actions/workflows/ci.yml">
66
+ <img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fflashtrace%2Fflashtrace%2Fbadges%2Fcoverage.json" alt="Line coverage of src/, measured by node --test." />
67
+ </a>
68
+ <a href="https://github.com/flashtrace/flashtrace/actions/workflows/ci.yml">
69
+ <img src="https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fflashtrace%2Fflashtrace%2Fbadges%2Ftests.json" alt="Number of tests run by node --test." />
70
+ </a>
59
71
  </p>
60
72
 
61
73
  ## Getting Started
@@ -177,74 +177,10 @@ var BY_EXT = {
177
177
  var CODE_EXT = new Set(Object.keys(BY_EXT));
178
178
  var grammarFor = (ext) => BY_EXT[ext] ?? null;
179
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
180
  // src/ids.mjs
245
181
  var SEGMENT_SRC = "[A-Za-z][A-Za-z0-9_.-]*";
246
182
  var REV_SRC = String.raw`\d+(?:\.\d+){0,2}`;
247
- var WILDCARD_SRC = String.raw`(?:\d+\.\d+\.x|\d+\.x\.y|x\.y\.z|\d+\.x|x\.y|x)`;
183
+ var WILDCARD_SRC = String.raw`(?:\d+\.){0,2}[x*]`;
248
184
  var REV_REF_SRC = `(?:${WILDCARD_SRC}|${REV_SRC})`;
249
185
  var ID_SRC = String.raw`([A-Za-z]+):(?:((?:${SEGMENT_SRC}\/)*${SEGMENT_SRC})\/)?(${SEGMENT_SRC})#(${REV_SRC})`;
250
186
  var ID_RE = new RegExp(`^${ID_SRC}$`);
@@ -265,25 +201,29 @@ var keyOf = (id) => id.slice(0, id.lastIndexOf("#"));
265
201
  var revOf = (id) => id.slice(id.lastIndexOf("#") + 1);
266
202
  var pathOf = (id) => id.slice(id.indexOf(":") + 1, id.lastIndexOf("#"));
267
203
  var resolveRef = (type, path6, rev, ownerId) => `${type}:${path6 ?? pathOf(ownerId)}#${rev ?? revOf(ownerId)}`;
204
+ function canonicalRev(rev) {
205
+ const layers = rev.split(".").map((layer) => String(Number(layer)));
206
+ while (layers.length < 3) layers.push("0");
207
+ return layers.join(".");
208
+ }
209
+ var canonicalId = (id) => `${keyOf(id)}#${canonicalRev(revOf(id))}`;
268
210
  function compareRev(a, b) {
269
- const partsA = a.split(".");
270
- const partsB = b.split(".");
271
- for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
272
- if (i >= partsA.length) return -1;
273
- if (i >= partsB.length) return 1;
274
- if (partsA[i] !== partsB[i]) return Number(partsA[i]) - Number(partsB[i]);
211
+ const layersA = canonicalRev(a).split(".");
212
+ const layersB = canonicalRev(b).split(".");
213
+ for (let i = 0; i < 3; i++) {
214
+ if (layersA[i] !== layersB[i]) return Number(layersA[i]) - Number(layersB[i]);
275
215
  }
276
216
  return 0;
277
217
  }
278
- var WILDCARD_LAYERS = /* @__PURE__ */ new Set(["x", "y", "z"]);
279
- var isWildcardRev = (rev) => /[xyz]/.test(rev);
218
+ var isWildcardLayer = (layer) => layer === "x" || layer === "*";
219
+ var isWildcardRev = (rev) => /[x*]/.test(rev);
280
220
  function revMatches(pattern, concrete) {
281
- const patternParts = pattern.split(".");
282
- const concreteParts = concrete.split(".");
283
- if (patternParts.length !== concreteParts.length) return false;
284
- for (let i = 0; i < patternParts.length; i++) {
285
- if (WILDCARD_LAYERS.has(patternParts[i])) continue;
286
- if (patternParts[i] !== concreteParts[i]) return false;
221
+ const patternLayers = pattern.split(".");
222
+ while (patternLayers.length < 3) patternLayers.push(isWildcardLayer(patternLayers.at(-1)) ? "x" : "0");
223
+ const concreteLayers = canonicalRev(concrete).split(".");
224
+ for (let i = 0; i < 3; i++) {
225
+ if (isWildcardLayer(patternLayers[i])) continue;
226
+ if (Number(patternLayers[i]) !== Number(concreteLayers[i])) return false;
287
227
  }
288
228
  return true;
289
229
  }
@@ -303,6 +243,8 @@ function newItem(id, origin, file, line, character) {
303
243
  id,
304
244
  key: keyOf(id),
305
245
  revision: revOf(id),
246
+ canonicalId: canonicalId(id),
247
+ // the SemVer-equal identity every exact-ID lookup keys on
306
248
  origin,
307
249
  // 'spec' | 'code'
308
250
  file,
@@ -320,12 +262,102 @@ function newItem(id, origin, file, line, character) {
320
262
  };
321
263
  }
322
264
 
265
+ // src/defects.mjs
266
+ var DEFECT_KINDS = Object.freeze([
267
+ "invalid-reference",
268
+ "uncovered-need",
269
+ "uncovered-forward",
270
+ "orphaned-cover",
271
+ "unwanted-cover",
272
+ "unwanted-item",
273
+ "duplicate-id",
274
+ "duplicate-forwarding",
275
+ "cyclic-forwarding"
276
+ ]);
277
+ var invalidReference = (value, source, { file, line, character }) => ({
278
+ kind: "invalid-reference",
279
+ ref: value,
280
+ file,
281
+ line,
282
+ character,
283
+ message: `invalid: "${value}" in ${source} is not a valid ID and is ignored`
284
+ });
285
+ var uncoveredNeed = (need) => ({
286
+ kind: "uncovered-need",
287
+ ref: need,
288
+ message: `uncovered: needs ${need}, which does not exist`
289
+ });
290
+ var uncoveredForward = (target) => ({
291
+ kind: "uncovered-forward",
292
+ ref: target,
293
+ message: `uncovered: forwards to ${target}, which does not exist`
294
+ });
295
+ var orphanedCover = (coverId) => ({
296
+ kind: "orphaned-cover",
297
+ ref: coverId,
298
+ message: `orphaned: covers ${coverId}, which does not exist`
299
+ });
300
+ var unwantedCover = (coverId, itemId) => ({
301
+ kind: "unwanted-cover",
302
+ ref: coverId,
303
+ message: `unwanted: covers ${coverId}, but ${coverId} does not need ${itemId}`
304
+ });
305
+ var unwantedItem = (itemId) => ({
306
+ kind: "unwanted-item",
307
+ ref: itemId,
308
+ message: `unwanted: no item needs ${itemId}`
309
+ });
310
+ var duplicateId = (id, count) => ({
311
+ kind: "duplicate-id",
312
+ ref: id,
313
+ message: `duplicate: ID ${id} is defined ${count} times`
314
+ });
315
+ var duplicateForwarding = (from, count, { file, line, character }) => ({
316
+ kind: "duplicate-forwarding",
317
+ ref: from,
318
+ file,
319
+ line,
320
+ character,
321
+ message: `duplicate: forwarding for ${from} is declared ${count} times`
322
+ });
323
+ var cyclicForwarding = (target, chain, { file, line, character }) => ({
324
+ kind: "cyclic-forwarding",
325
+ ref: target,
326
+ file,
327
+ line,
328
+ character,
329
+ message: `cyclic: forwards to ${target}, closing the cycle ${chain}, so the forwarding has no effect`
330
+ });
331
+
332
+ // src/spec-items.mjs
333
+ var KEYWORDS = ["Needs", "Covers", "Tags"];
334
+ var isKeyword = (text) => KEYWORDS.includes(text);
335
+ var parseVerbatimKeyword = (raw) => raw;
336
+ var KEYWORD_HANDLERS = {
337
+ Needs: { target: "needs", parse: parseNeedEntry },
338
+ Covers: { target: "covers", parse: parseCoverEntry },
339
+ Tags: { target: "tags", parse: parseVerbatimKeyword }
340
+ };
341
+ function applyKeyword(item, keyword, entries, file, source) {
342
+ const handler = KEYWORD_HANDLERS[keyword];
343
+ if (!handler) throw new Error(`applyKeyword: no handling for keyword "${keyword}"`);
344
+ const { target, parse } = handler;
345
+ for (const entry of entries) {
346
+ const value = parse(entry.value, item.id);
347
+ if (value) item[target].push(value);
348
+ else
349
+ item.defects.push(
350
+ invalidReference(entry.value, source, { file, line: entry.line, character: entry.character })
351
+ );
352
+ }
353
+ }
354
+
323
355
  // src/parse-markdown.mjs
324
356
  var DEFINITION_RE = new RegExp(String.raw`^\s*\`${ID_SRC}\`\s*$`);
325
357
  var HEADING_RE = /^(#{1,6})\s+(\S(?:.*\S)?)\s*$/;
326
358
  var SETEXT_UNDERLINE_RE = /^ {0,3}(?:=+|-+)[ \t]*$/;
327
359
  var THEMATIC_BREAK_RE = /^ {0,3}-{3,}[ \t]*$/;
328
- var KEYWORD_RE = /^(Needs|Covers|Tags):\s*((?:\S.*)?)$/;
360
+ var KEYWORD_RE = new RegExp(String.raw`^(${KEYWORDS.join("|")}):\s*((?:\S.*)?)$`);
329
361
  var BULLET_RE = /^\s*[-*+]\s+(\S(?:.*\S)?)\s*$/;
330
362
  var DELIMITER_CELL_RE = /^:?-+:?$/;
331
363
  var FORWARD_LINE_RE = new RegExp(String.raw`^\s*(\`?)${FORWARD_SRC}\1\s*$`);
@@ -438,7 +470,6 @@ function tableStartsAt(lines, j) {
438
470
  }
439
471
  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));
440
472
  var rowCellsInTable = (line) => rowCells(line) ?? [line.trim()];
441
- var isKeywordCell = (cell) => cell === "Needs" || cell === "Covers" || cell === "Tags";
442
473
  function scanTables(lines, file, problems) {
443
474
  const inTable = new Array(lines.length).fill(false);
444
475
  let j = 0;
@@ -449,7 +480,7 @@ function scanTables(lines, file, problems) {
449
480
  }
450
481
  const keywordColumns = /* @__PURE__ */ new Set();
451
482
  rowCells(lines[j]).forEach((cell, col) => {
452
- if (isKeywordCell(cell)) keywordColumns.add(col);
483
+ if (isKeyword(cell)) keywordColumns.add(col);
453
484
  });
454
485
  const start = j;
455
486
  let end = j + 1;
@@ -473,11 +504,11 @@ function scanTables(lines, file, problems) {
473
504
  }
474
505
  return inTable;
475
506
  }
476
- function takeKeywordTable(lines, inTable, j, item, file, problems) {
507
+ function takeKeywordTable(lines, inTable, j, item, file) {
477
508
  if (!inTable[j] || j > 0 && inTable[j - 1]) return null;
478
509
  const columns = [];
479
510
  rowCells(lines[j]).forEach((cell, col) => {
480
- if (isKeywordCell(cell)) columns.push([col, cell]);
511
+ if (isKeyword(cell)) columns.push([col, cell]);
481
512
  });
482
513
  if (columns.length === 0) return null;
483
514
  j++;
@@ -492,33 +523,13 @@ function takeKeywordTable(lines, inTable, j, item, file, problems) {
492
523
  keyword,
493
524
  [{ value: cells[col], line: j + 1, character: cellColumns[col] }],
494
525
  file,
495
- problems,
496
526
  `the ${keyword} column of ${item.id}`
497
527
  );
498
528
  }
499
529
  }
500
530
  return j;
501
531
  }
502
- function applyKeyword(item, keyword, entries, file, problems, source) {
503
- if (keyword === "Tags") {
504
- for (const entry of entries) item.tags.push(entry.value);
505
- return;
506
- }
507
- const target = keyword === "Needs" ? "needs" : "covers";
508
- const parse = keyword === "Needs" ? parseNeedEntry : parseCoverEntry;
509
- for (const entry of entries) {
510
- const id = parse(entry.value, item.id);
511
- if (id) item[target].push(id);
512
- else
513
- problems.push({
514
- file,
515
- line: entry.line,
516
- character: entry.character,
517
- message: `invalid ID "${entry.value}" in ${source}`
518
- });
519
- }
520
- }
521
- function parseItemBody(lines, boundary, start, item, file, problems, forwards) {
532
+ function parseItemBody(lines, boundary, start, item, file, forwards) {
522
533
  const { inTable, opensHeading } = boundary;
523
534
  let j = start;
524
535
  let descriptionDone = false;
@@ -529,7 +540,7 @@ function parseItemBody(lines, boundary, start, item, file, problems, forwards) {
529
540
  continue;
530
541
  }
531
542
  const keywordMatch = line.match(KEYWORD_RE);
532
- const tableEnd = keywordMatch ? null : takeKeywordTable(lines, inTable, j, item, file, problems);
543
+ const tableEnd = keywordMatch ? null : takeKeywordTable(lines, inTable, j, item, file);
533
544
  if (keywordMatch) {
534
545
  descriptionDone = true;
535
546
  const collected = keywordEntries(lines, j, keywordMatch[2]);
@@ -538,8 +549,7 @@ function parseItemBody(lines, boundary, start, item, file, problems, forwards) {
538
549
  keywordMatch[1],
539
550
  collected.entries,
540
551
  file,
541
- problems,
542
- `${keywordMatch[1]}: list of ${item.id}`
552
+ `the ${keywordMatch[1]} list of ${item.id}`
543
553
  );
544
554
  j = collected.j;
545
555
  } else if (tableEnd !== null) {
@@ -584,12 +594,83 @@ function parseMarkdown(file, text, problems, forwards = []) {
584
594
  }
585
595
  const item = newItem(makeId(definition[1], definition[2], definition[3], definition[4]), "spec", file, i + 1, firstNonBlankColumn(lines[i]));
586
596
  item.title = titleAbove(lines, inTable, i);
587
- i = parseItemBody(lines, boundary, i + 1, item, file, problems, forwards);
597
+ i = parseItemBody(lines, boundary, i + 1, item, file, forwards);
588
598
  items.push(item);
589
599
  }
590
600
  return items;
591
601
  }
592
602
 
603
+ // src/parse-spec.mjs
604
+ var BY_EXT2 = {
605
+ ".md": parseMarkdown,
606
+ ".markdown": parseMarkdown
607
+ };
608
+ var SPEC_EXT = new Set(Object.keys(BY_EXT2));
609
+ var specParserFor = (ext) => BY_EXT2[ext] ?? null;
610
+
611
+ // src/files.mjs
612
+ var GIT_LOCATIONS = process.platform === "win32" ? [
613
+ String.raw`C:\Program Files\Git\cmd\git.exe`,
614
+ String.raw`C:\Program Files (x86)\Git\cmd\git.exe`
615
+ ] : ["/usr/bin/git", "/bin/git"];
616
+ var gitBin;
617
+ function findGit() {
618
+ if (gitBin === void 0) {
619
+ gitBin = GIT_LOCATIONS.find((p) => existsSync(p)) ?? null;
620
+ }
621
+ return gitBin;
622
+ }
623
+ function compareStrings(a, b) {
624
+ if (a < b) return -1;
625
+ if (a > b) return 1;
626
+ return 0;
627
+ }
628
+ async function walk(dir, out) {
629
+ let entries;
630
+ try {
631
+ entries = await fs.readdir(dir, { withFileTypes: true });
632
+ } catch {
633
+ return out;
634
+ }
635
+ for (const entry of entries) {
636
+ if (entry.name === ".git" || entry.name === "node_modules") continue;
637
+ const entryPath = path.join(dir, entry.name);
638
+ if (entry.isDirectory()) await walk(entryPath, out);
639
+ else if (entry.isFile()) out.push(entryPath);
640
+ }
641
+ return out;
642
+ }
643
+ async function collectFiles(dirs) {
644
+ const files = /* @__PURE__ */ new Set();
645
+ for (const dir of dirs) {
646
+ const abs = path.resolve(dir);
647
+ const stats = await fs.stat(abs).catch(() => null);
648
+ if (!stats) throw new UsageError(`input path does not exist: ${dir}`);
649
+ if (stats.isFile()) {
650
+ files.add(abs);
651
+ continue;
652
+ }
653
+ let list = null;
654
+ const git = findGit();
655
+ try {
656
+ if (!git) throw new Error("git not found");
657
+ const out = execFileSync(
658
+ git,
659
+ ["-C", abs, "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
660
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
661
+ );
662
+ list = out.split("\0").filter(Boolean).map((f) => path.join(abs, f));
663
+ } catch {
664
+ list = await walk(abs, []);
665
+ }
666
+ for (const file of list) files.add(file);
667
+ }
668
+ return [...files].filter((file) => {
669
+ const ext = path.extname(file).toLowerCase();
670
+ return SPEC_EXT.has(ext) || CODE_EXT.has(ext);
671
+ }).sort(compareStrings);
672
+ }
673
+
593
674
  // src/parse-code.mjs
594
675
  import path2 from "node:path";
595
676
  var TAG_RE = new RegExp(
@@ -735,7 +816,7 @@ function commentText(line, state, grammar) {
735
816
  }
736
817
  function attachNeed(m, file, line, character, state, problems) {
737
818
  const source = m[1] ? makeId(m[1], m[2], m[3], m[4]) : null;
738
- const anchor = source ? state.byId.get(source) : state.lastItem;
819
+ const anchor = source ? state.byId.get(canonicalId(source)) : state.lastItem;
739
820
  if (!anchor) {
740
821
  const written = m[5] + (m[6] ? `:${m[6]}` : "") + (m[7] ? `#${m[7]}` : "");
741
822
  problems.push({
@@ -754,7 +835,7 @@ function collectTags(comment, file, line, state, items, problems) {
754
835
  if (m[8]) {
755
836
  const item = newItem(makeId(m[8], m[9], m[10], m[11]), "code", file, line, character);
756
837
  state.lastItem = item;
757
- state.byId.set(item.id, item);
838
+ state.byId.set(item.canonicalId, item);
758
839
  items.push(item);
759
840
  } else {
760
841
  attachNeed(m, file, line, character, state, problems);
@@ -777,57 +858,11 @@ function parseCode(file, text, problems, forwards = []) {
777
858
  return items;
778
859
  }
779
860
 
780
- // src/defects.mjs
781
- var DEFECT_KINDS = Object.freeze([
782
- "uncovered-need",
783
- "uncovered-forward",
784
- "orphaned-cover",
785
- "unwanted-cover",
786
- "unwanted-item",
787
- "duplicate-id",
788
- "duplicate-forwarding"
789
- ]);
790
- var uncoveredNeed = (need) => ({
791
- kind: "uncovered-need",
792
- ref: need,
793
- message: `uncovered: needs ${need}, which does not exist`
794
- });
795
- var uncoveredForward = (target) => ({
796
- kind: "uncovered-forward",
797
- ref: target,
798
- message: `uncovered: forwards to ${target}, which does not exist`
799
- });
800
- var orphanedCover = (coverId) => ({
801
- kind: "orphaned-cover",
802
- ref: coverId,
803
- message: `orphaned: covers ${coverId}, which does not exist`
804
- });
805
- var unwantedCover = (coverId, itemId) => ({
806
- kind: "unwanted-cover",
807
- ref: coverId,
808
- message: `unwanted: covers ${coverId}, but ${coverId} does not need ${itemId}`
809
- });
810
- var unwantedItem = (itemId) => ({
811
- kind: "unwanted-item",
812
- ref: itemId,
813
- message: `unwanted: no item needs ${itemId}`
814
- });
815
- var duplicateId = (id, count) => ({
816
- kind: "duplicate-id",
817
- ref: id,
818
- message: `duplicate: ID ${id} is defined ${count} times`
819
- });
820
- var duplicateForwarding = (from, count) => ({
821
- kind: "duplicate-forwarding",
822
- ref: from,
823
- message: `duplicate: forwarding for ${from} is declared ${count} times`
824
- });
825
-
826
861
  // src/analyze.mjs
827
862
  function checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, forwardTargets) {
828
- const forwardTarget = forwardTargets.get(item.id);
863
+ const forwardTarget = forwardTargets.get(item.canonicalId);
829
864
  if (forwardTarget !== void 0) {
830
- if (!byId.has(forwardTarget))
865
+ if (!byId.has(canonicalId(forwardTarget)))
831
866
  item.defects.push(withRevisions(uncoveredForward(forwardTarget)));
832
867
  } else {
833
868
  for (const need of item.needs) {
@@ -836,18 +871,28 @@ function checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, for
836
871
  }
837
872
  }
838
873
  for (const coverId of item.covers) {
839
- const targets = byId.get(coverId);
874
+ const targets = byId.get(canonicalId(coverId));
840
875
  if (!targets) {
841
876
  item.defects.push(withRevisions(orphanedCover(coverId)));
842
877
  } else if (!targets.some((target) => target.needs.some((need) => idMatches(need, item.id)))) {
843
878
  item.defects.push(unwantedCover(coverId, item.id));
844
879
  }
845
880
  }
846
- if (item.origin === "code" && !isNeeded(item.id)) {
881
+ if (item.origin === "code" && !isNeeded(item.canonicalId)) {
847
882
  item.defects.push(unwantedItem(item.id));
848
883
  }
849
884
  }
850
- function dropCyclicForwards(forwardTargets, declarationBySource, problems) {
885
+ var displayedDuplicateId = (writtenIds, canonical) => writtenIds.every((id) => id === writtenIds[0]) ? writtenIds[0] : canonical;
886
+ function voidForwardingCycle(cycle, chain, forwardTargets, declarationBySource, byId) {
887
+ for (const id of cycle) {
888
+ const declaration = declarationBySource.get(id);
889
+ declaration.effective = false;
890
+ declaration.voidedBy = "cycle";
891
+ for (const item of byId.get(id)) item.defects.push(cyclicForwarding(declaration.to, chain, declaration));
892
+ forwardTargets.delete(id);
893
+ }
894
+ }
895
+ function dropCyclicForwards(forwardTargets, declarationBySource, byId) {
851
896
  const done = /* @__PURE__ */ new Set();
852
897
  for (const start of forwardTargets.keys()) {
853
898
  if (done.has(start)) continue;
@@ -857,23 +902,12 @@ function dropCyclicForwards(forwardTargets, declarationBySource, problems) {
857
902
  while (forwardTargets.has(current) && !done.has(current) && !seen.has(current)) {
858
903
  seen.set(current, path6.length);
859
904
  path6.push(current);
860
- current = forwardTargets.get(current);
905
+ current = canonicalId(forwardTargets.get(current));
861
906
  }
862
907
  if (seen.has(current)) {
863
908
  const cycle = path6.slice(seen.get(current));
864
- const chain = [...cycle, current].join(" --> ");
865
- for (const id of cycle) {
866
- const declaration = declarationBySource.get(id);
867
- declaration.effective = false;
868
- declaration.voidedBy = "cycle";
869
- problems.push({
870
- file: declaration.file,
871
- line: declaration.line,
872
- character: declaration.character,
873
- message: `cyclic forwarding: ${chain}`
874
- });
875
- forwardTargets.delete(id);
876
- }
909
+ const chain = [...cycle, current].map((id) => declarationBySource.get(id).from).join(" --> ");
910
+ voidForwardingCycle(cycle, chain, forwardTargets, declarationBySource, byId);
877
911
  }
878
912
  for (const id of path6) done.add(id);
879
913
  }
@@ -883,7 +917,8 @@ function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
883
917
  const declarationBySource = /* @__PURE__ */ new Map();
884
918
  const forwardsBySource = /* @__PURE__ */ new Map();
885
919
  for (const forward of forwards) {
886
- (forwardsBySource.get(forward.from) ?? forwardsBySource.set(forward.from, []).get(forward.from)).push(forward);
920
+ const from = canonicalId(forward.from);
921
+ (forwardsBySource.get(from) ?? forwardsBySource.set(from, []).get(from)).push(forward);
887
922
  }
888
923
  for (const [from, group] of forwardsBySource) {
889
924
  const sources = byId.get(from);
@@ -895,13 +930,15 @@ function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
895
930
  file: forward.file,
896
931
  line: forward.line,
897
932
  character: forward.character,
898
- message: `forwarding from ${from}, which does not exist${revHint(from)}`
933
+ message: `forwarding from ${forward.from}, which does not exist${revHint(forward.from)}`
899
934
  });
900
935
  }
901
936
  continue;
902
937
  }
903
- if (group.length > 1)
904
- for (const item of sources) item.defects.push(duplicateForwarding(from, group.length));
938
+ if (group.length > 1) {
939
+ const shown = displayedDuplicateId(group.map((forward) => forward.from), from);
940
+ for (const item of sources) item.defects.push(duplicateForwarding(shown, group.length, group[0]));
941
+ }
905
942
  group[0].effective = true;
906
943
  for (let i = 1; i < group.length; i++) {
907
944
  group[i].effective = false;
@@ -910,8 +947,8 @@ function buildForwardMap(forwards, byId, neededIds, revHint, problems) {
910
947
  forwardTargets.set(from, group[0].to);
911
948
  declarationBySource.set(from, group[0]);
912
949
  }
913
- dropCyclicForwards(forwardTargets, declarationBySource, problems);
914
- for (const to of forwardTargets.values()) neededIds.add(to);
950
+ dropCyclicForwards(forwardTargets, declarationBySource, byId);
951
+ for (const to of forwardTargets.values()) neededIds.add(canonicalId(to));
915
952
  return forwardTargets;
916
953
  }
917
954
  function markDeepCoverage(items, byId, matchesOf, forwardTargets) {
@@ -927,7 +964,7 @@ function markDeepCoverage(items, byId, matchesOf, forwardTargets) {
927
964
  const forwardTarget = forwardTargets.get(id);
928
965
  let ok = true;
929
966
  if (forwardTarget !== void 0) {
930
- ok = deep(forwardTarget);
967
+ ok = deep(canonicalId(forwardTarget));
931
968
  } else {
932
969
  for (const item of group) for (const need of item.needs) if (!needDeep(need)) ok = false;
933
970
  }
@@ -935,7 +972,7 @@ function markDeepCoverage(items, byId, matchesOf, forwardTargets) {
935
972
  return ok;
936
973
  };
937
974
  const needDeep = (need) => matchesOf(need).some((id) => deep(id));
938
- for (const item of items) item.deepCovered = deep(item.id);
975
+ for (const item of items) item.deepCovered = deep(item.canonicalId);
939
976
  }
940
977
  function groupIdsByKey(byId) {
941
978
  const idsByKey = /* @__PURE__ */ new Map();
@@ -954,7 +991,9 @@ function buildWantedBy(items, byId, matchesOf) {
954
991
  }
955
992
  function buildResolver(items) {
956
993
  const byId = /* @__PURE__ */ new Map();
957
- for (const item of items) (byId.get(item.id) ?? byId.set(item.id, []).get(item.id)).push(item);
994
+ for (const item of items) {
995
+ (byId.get(item.canonicalId) ?? byId.set(item.canonicalId, []).get(item.canonicalId)).push(item);
996
+ }
958
997
  const idsByKey = groupIdsByKey(byId);
959
998
  const matchesOf = (ref) => (idsByKey.get(keyOf(ref)) ?? []).filter((id) => idMatches(ref, id));
960
999
  return { byId, matchesOf, wantedBy: buildWantedBy(items, byId, matchesOf) };
@@ -986,7 +1025,7 @@ function splitNeeds(items) {
986
1025
  for (const item of items)
987
1026
  for (const need of item.needs) {
988
1027
  if (isWildcardRev(revOf(need))) wildcard.push(need);
989
- else exact.add(need);
1028
+ else exact.add(canonicalId(need));
990
1029
  }
991
1030
  return { exact, wildcard };
992
1031
  }
@@ -996,9 +1035,12 @@ function analyze(items, forwards = [], problems = []) {
996
1035
  for (const item of items)
997
1036
  (revsByKey.get(item.key) ?? revsByKey.set(item.key, /* @__PURE__ */ new Set()).get(item.key)).add(item.revision);
998
1037
  const { exact: exactNeeds, wildcard: wildcardNeeds } = splitNeeds(items);
999
- const isNeeded = (id) => exactNeeds.has(id) || wildcardNeeds.some((wildcard) => idMatches(wildcard, id));
1038
+ const isNeeded = (canonical) => exactNeeds.has(canonical) || wildcardNeeds.some((wildcard) => idMatches(wildcard, canonical));
1000
1039
  for (const [id, group] of byId) {
1001
- if (group.length > 1) for (const item of group) item.defects.push(duplicateId(id, group.length));
1040
+ if (group.length > 1) {
1041
+ const shown = displayedDuplicateId(group.map((item) => item.id), id);
1042
+ for (const item of group) item.defects.push(duplicateId(shown, group.length));
1043
+ }
1002
1044
  }
1003
1045
  const existingRevisionsOf = (id) => {
1004
1046
  const revs = revsByKey.get(keyOf(id));
@@ -1020,7 +1062,7 @@ function analyze(items, forwards = [], problems = []) {
1020
1062
  };
1021
1063
  const forwardTargets = buildForwardMap(forwards, byId, exactNeeds, revHint, problems);
1022
1064
  for (const item of items) {
1023
- item.forwardsTo = forwardTargets.get(item.id) ?? null;
1065
+ item.forwardsTo = forwardTargets.get(item.canonicalId) ?? null;
1024
1066
  checkItemReferences(item, byId, matchesOf, isNeeded, withRevisions, forwardTargets);
1025
1067
  }
1026
1068
  markDeepCoverage(items, byId, matchesOf, forwardTargets);
@@ -1056,7 +1098,7 @@ function byFileLine(a, b) {
1056
1098
  return a.line - b.line;
1057
1099
  }
1058
1100
  function forwardEdge(item, byId, style, dimLocation) {
1059
- const target = byId.get(item.forwardsTo)?.[0];
1101
+ const target = byId.get(canonicalId(item.forwardsTo))?.[0];
1060
1102
  if (!target) return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${style.red("\u2718 missing")}`;
1061
1103
  return ` ${style.cyan("\u2192")} ${item.forwardsTo} ${styledStatus(target, style).mark} ${dimLocation(target.file, target.line)}`;
1062
1104
  }
@@ -1071,8 +1113,8 @@ function needEdges(item, byId, matchesOf, style, dimLocation) {
1071
1113
  const wildcard = isWildcardRev(revOf(need));
1072
1114
  for (const id of ids) {
1073
1115
  const covering = byId.get(id)[0];
1074
- const arrow = style.dim(`(\u2192 ${id})`);
1075
- const ref = wildcard ? `${need} ${arrow}` : need;
1116
+ const arrow = style.dim(`(\u2192 ${covering.id})`);
1117
+ const ref = wildcard || covering.id !== need ? `${need} ${arrow}` : need;
1076
1118
  lines.push(` ${style.dim("needs")} ${ref} ${styledStatus(covering, style).mark} ${dimLocation(covering.file, covering.line)}`);
1077
1119
  }
1078
1120
  }
@@ -1081,12 +1123,18 @@ function needEdges(item, byId, matchesOf, style, dimLocation) {
1081
1123
  function coverEdges(item, byId, style, dimLocation) {
1082
1124
  const lines = [];
1083
1125
  for (const coverId of item.covers) {
1084
- const target = byId.get(coverId)?.[0];
1126
+ const target = byId.get(canonicalId(coverId))?.[0];
1085
1127
  if (!target) lines.push(` ${style.dim("covers")} ${coverId} ${style.red("\u2718 missing")}`);
1086
1128
  else lines.push(` ${style.dim("covers")} ${coverId} ${style.green("\u2714")} ${dimLocation(target.file, target.line)}`);
1087
1129
  }
1088
1130
  return lines;
1089
1131
  }
1132
+ function defectLines(item, style, dimLocation) {
1133
+ return item.defects.map((defect) => {
1134
+ const location = defect.file ? ` ${dimLocation(defect.file, defect.line)}` : "";
1135
+ return ` ${style.red("\u2022")} ${defect.message}${location}`;
1136
+ });
1137
+ }
1090
1138
  function edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation) {
1091
1139
  const lines = [];
1092
1140
  if (item.forwardsTo !== null) lines.push(forwardEdge(item, byId, style, dimLocation));
@@ -1107,9 +1155,9 @@ function renderVerbose(items, out, style, dimLocation) {
1107
1155
  const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
1108
1156
  out.push(
1109
1157
  `${mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)} ${tag}`,
1110
- ...edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation)
1158
+ ...edgeLines(item, byId, matchesOf, wantedBy, style, dimLocation),
1159
+ ...defectLines(item, style, dimLocation)
1111
1160
  );
1112
- for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect.message}`);
1113
1161
  }
1114
1162
  if (sorted.length) out.push("");
1115
1163
  }
@@ -1117,10 +1165,10 @@ function renderDefective(defective, out, style, dimLocation) {
1117
1165
  for (const item of defective) {
1118
1166
  const title = item.title ? " " + style.dim(`"${item.title}"`) : "";
1119
1167
  out.push(
1120
- `${styledStatus(item, style).mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)}`
1168
+ `${styledStatus(item, style).mark} ${style.bold(item.id)}${title} ${dimLocation(item.file, item.line)}`,
1169
+ ...defectLines(item, style, dimLocation),
1170
+ ""
1121
1171
  );
1122
- for (const defect of item.defects) out.push(` ${style.red("\u2022")} ${defect.message}`);
1123
- out.push("");
1124
1172
  }
1125
1173
  }
1126
1174
  function renderSummary(summary, out, style) {
@@ -1172,17 +1220,11 @@ function buildForwardedFrom(items, byId) {
1172
1220
  const forwardedFrom = /* @__PURE__ */ new Map();
1173
1221
  for (const item of items) {
1174
1222
  if (item.forwardsTo === null) continue;
1175
- for (const target of byId.get(item.forwardsTo) ?? [])
1223
+ for (const target of byId.get(canonicalId(item.forwardsTo)) ?? [])
1176
1224
  (forwardedFrom.get(target) ?? forwardedFrom.set(target, []).get(target)).push(item);
1177
1225
  }
1178
1226
  return forwardedFrom;
1179
1227
  }
1180
- function defectDocument(defect) {
1181
- const out = { kind: defect.kind, ref: defect.ref };
1182
- if (defect.existingRevisions) out.existingRevisions = defect.existingRevisions;
1183
- out.message = defect.message;
1184
- return out;
1185
- }
1186
1228
  function buildReportDocument(items, forwards, problems, cwd, opts = {}) {
1187
1229
  const { version } = opts;
1188
1230
  if (typeof version !== "string")
@@ -1196,8 +1238,19 @@ function buildReportDocument(items, forwards, problems, cwd, opts = {}) {
1196
1238
  };
1197
1239
  const { byId, matchesOf, wantedBy } = buildResolver(items);
1198
1240
  const forwardedFrom = buildForwardedFrom(items, byId);
1199
- const resolvedTo = (ref) => matchesOf(ref).sort((a, b) => compareRev(revOf(a), revOf(b)));
1241
+ const resolvedTo = (ref) => [
1242
+ ...new Set(
1243
+ matchesOf(ref).sort((a, b) => compareRev(revOf(a), revOf(b))).flatMap((id) => byId.get(id).map((item) => item.id))
1244
+ )
1245
+ ];
1200
1246
  const itemRefs = (related) => [...related].map((other) => ({ id: other.id, ...location(other) })).sort(byLocation);
1247
+ const defectDocument = (defect) => {
1248
+ const out = { kind: defect.kind, ref: defect.ref };
1249
+ if (defect.file) Object.assign(out, location(defect));
1250
+ if (defect.existingRevisions) out.existingRevisions = defect.existingRevisions;
1251
+ out.message = defect.message;
1252
+ return out;
1253
+ };
1201
1254
  const itemDocument = (item) => {
1202
1255
  const coverStatus = coverStatusOf(item);
1203
1256
  return {
@@ -1360,9 +1413,8 @@ async function main() {
1360
1413
  for (const file of files) {
1361
1414
  const text = await fs2.readFile(file, "utf8");
1362
1415
  const ext = path5.extname(file).toLowerCase();
1363
- items.push(
1364
- ...SPEC_EXT.has(ext) ? parseMarkdown(file, text, problems, forwards) : parseCode(file, text, problems, forwards)
1365
- );
1416
+ const parse = specParserFor(ext) ?? parseCode;
1417
+ items.push(...parse(file, text, problems, forwards));
1366
1418
  }
1367
1419
  if (opts.tags) {
1368
1420
  const wantUntagged = opts.tags.includes("_");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flashtrace",
3
- "version": "0.11.5",
3
+ "version": "0.12.1",
4
4
  "description": "Lightning-fast, reference-based requirement tracing that works anywhere.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -32,7 +32,9 @@
32
32
  "build": "esbuild src/main.mjs --bundle --format=esm --platform=node --outfile=dist/flashtrace.mjs",
33
33
  "prepack": "pnpm run build",
34
34
  "pretest": "pnpm run build",
35
- "test": "node --test"
35
+ "test": "node --test",
36
+ "pretest:coverage": "pnpm run build && node .github/scripts/prepare-coverage.mjs",
37
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-include=src/** --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-reporter=junit --test-reporter-destination=coverage/junit.xml"
36
38
  },
37
39
  "devDependencies": {
38
40
  "esbuild": "^0.28.1"