@blundergoat/gruff-ts 0.5.0 → 0.6.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 (77) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +49 -50
  4. package/SECURITY.md +18 -31
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -10
  8. package/docs/agent-hook.md +32 -35
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +160 -89
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -172
  15. package/docs/rules.md +126 -98
  16. package/package.json +10 -8
  17. package/src/analyser.ts +817 -323
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +62 -68
  22. package/src/blocks.ts +512 -336
  23. package/src/changed-regions.ts +380 -79
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +445 -436
  26. package/src/cli-program.ts +915 -172
  27. package/src/cli.ts +9 -3
  28. package/src/comment-rules.ts +236 -418
  29. package/src/comment-scanner.ts +339 -47
  30. package/src/complexity-metrics.ts +111 -35
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +751 -223
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +182 -54
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +493 -140
  40. package/src/doc-rules.ts +602 -126
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +134 -109
  43. package/src/findings.ts +47 -27
  44. package/src/fixture-purpose-rules.ts +194 -50
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +328 -121
  47. package/src/hook-contract.ts +681 -255
  48. package/src/init-config.ts +163 -118
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -468
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +32 -127
  54. package/src/parsed-script.ts +868 -314
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +86 -74
  57. package/src/project-config-rules.ts +324 -140
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +102 -38
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +821 -203
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +249 -55
  66. package/src/security-flow-rules.ts +791 -115
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +460 -387
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +378 -104
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +343 -253
  73. package/src/text-scans.ts +62 -11
  74. package/src/types.ts +220 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -163
  77. package/src/test-fixtures.ts +0 -671
@@ -0,0 +1,463 @@
1
+ // The one line-free identity a baseline stores for a finding, ratified for the family in
2
+ // `contracts/core/finding-identity.v1.json`.
3
+ //
4
+ // When a user runs `gruff-ts analyse --generate-baseline`, every ordinary finding is named by this identity and
5
+ // nothing positional. On the next `analyse --baseline` a finding that moved lines still matches, while a new
6
+ // sibling of the same rule never inherits the review.
7
+ //
8
+ // Three decisions live here:
9
+ // - a symbol-bearing finding is named by its symbol plus a declaration ordinal, so two same-named functions stay apart;
10
+ // - a finding naming no symbol falls back to its message with measured values normalised, so a grown file keeps its review;
11
+ // - a sensitive finding receives no identity at all, because a stored identity is what would let a review hide a secret.
12
+ import { createHash } from "node:crypto";
13
+ import type { Finding } from "./types.ts";
14
+
15
+ // Token gruff-ts contributes to every identity, so the same rule on the same path never collides with another port's finding.
16
+ export const TOOL_LANGUAGE = "ts";
17
+
18
+ // Joins a symbol to its declaration ordinal; a symbol carrying it could forge another symbol's ordinal, so it gets no identity.
19
+ const ORDINAL_SEPARATOR = "#";
20
+
21
+ // Every number a message can state: a length, a count, a percentage, or a version, including groups such as 1,234 or 12.5.
22
+ const MEASURED_VALUE_PATTERN = /[0-9]+(?:[.,][0-9]+)*/gu;
23
+
24
+ // What every measured value becomes in a subject, so a file that grew from 1010 to 1200 lines keeps its reviewed identity.
25
+ const MEASURED_VALUE_PLACEHOLDER = "#";
26
+
27
+ // The pillar that marks a secret; the rule-id prefix is checked alongside it so a mis-tagged rule still cannot be baselined.
28
+ const SENSITIVE_PILLAR = "sensitive-data";
29
+
30
+ /*
31
+ * One finding's durable name, plus the two facts matching needs alongside it.
32
+ *
33
+ * `declarationKey` is equal for two findings on one declaration; two different keys under one identity are a
34
+ * collision, which the run reports by name and never hides.
35
+ */
36
+ export interface FindingIdentity {
37
+ identity: string;
38
+ subject: string;
39
+ declarationKey: string;
40
+ }
41
+
42
+ // One parsed declaration and the lines (plus optional 1-based columns) it covers, used to rank same-named declarations in one file.
43
+ export interface DeclarationSpan {
44
+ name: string;
45
+ startLine: number;
46
+ endLine: number;
47
+ startColumn?: number;
48
+ endColumn?: number;
49
+ }
50
+
51
+ // Columns are stored as the fraction after the line number, capped so a long line never reaches the next line's position.
52
+ const COLUMN_POSITION_SCALE = 1_000_000;
53
+ const MAX_COLUMN_OFFSET = 999_999;
54
+
55
+ /*
56
+ * Maps a finding to the line its declaration starts on and, when the parse is available, lists the start line of
57
+ * every same-named declaration in its file.
58
+ *
59
+ * The list is what makes the ordinal count declarations rather than findings. Without it a clean earlier
60
+ * declaration takes no slot, so the day it first warns it takes the later declaration's ordinal and stored review.
61
+ * Stable contract: with the list present, a declaration's ordinal does not depend on which findings this run emitted.
62
+ */
63
+ export interface DeclarationPositionResolver {
64
+ (finding: Finding): number;
65
+ sameNamedPositions?: (finding: Finding) => readonly number[];
66
+ }
67
+
68
+ /** Raised when a finding cannot be given a durable name, so the run reports a baseline failure instead of guessing. */
69
+ export class BaselineIdentityError extends Error {}
70
+
71
+ /**
72
+ * Check baseline eligibility. Stable contract: sensitive findings receive no baseline identity, so a stored review cannot suppress them.
73
+ * A matching sensitiveExclusions entry with a written reason can remove a finding before baseline application.
74
+ *
75
+ * @param finding - finding whose pillar and rule ID are checked against sensitive-data
76
+ * @returns False for findings in the sensitive-data pillar or with a rule ID starting with sensitive-data followed by a dot; otherwise true.
77
+ */
78
+ export function isBaselineEligible(finding: Finding): boolean {
79
+ return finding.pillar !== SENSITIVE_PILLAR && !finding.ruleId.startsWith(`${SENSITIVE_PILLAR}.`);
80
+ }
81
+
82
+ /**
83
+ * Normalise numeric sequences in a finding message to keep a symbol-less finding's subject stable as measurements change.
84
+ * Changes to the surrounding text still affect the subject.
85
+ *
86
+ * @param message - finding message text whose numeric sequences are replaced
87
+ * @returns The message with numeric sequences, including digits joined by periods or commas, replaced by #.
88
+ */
89
+ export function normaliseMeasuredValues(message: string): string {
90
+ return message.replace(MEASURED_VALUE_PATTERN, MEASURED_VALUE_PLACEHOLDER);
91
+ }
92
+
93
+ /**
94
+ * Build a stable baseline subject. An ordinal distinguishes declarations with the same symbol so each can be reviewed independently.
95
+ *
96
+ * @param finding - supplies the symbol or, when there is no symbol, the message used for matching
97
+ * @param ordinal - one-based declaration rank used when the symbol can be named
98
+ * @returns The symbol with its ordinal or the normalised message. Undefined means a reserved separator or empty message prevents naming.
99
+ * @throws {BaselineIdentityError} - a symbol without the reserved separator was given an ordinal that is not a positive integer.
100
+ */
101
+ export function baselineSubject(finding: Finding, ordinal: number): string | undefined {
102
+ const symbol = finding.symbol && finding.symbol.length > 0 ? finding.symbol : undefined;
103
+ // Normalise measured values so changes to the measurement can preserve the file-level subject.
104
+ if (symbol === undefined) {
105
+ return finding.message.length === 0 ? undefined : normaliseMeasuredValues(finding.message);
106
+ }
107
+ // A symbol carrying the separator could pose as another symbol's ordinal, so it is left unnamed rather than hashed ambiguously.
108
+ if (symbol.includes(ORDINAL_SEPARATOR)) {
109
+ return undefined;
110
+ }
111
+ // Defaulting a missing ordinal to 1 would merge namesakes back together, the collision the ordinal exists to prevent.
112
+ if (!Number.isInteger(ordinal) || ordinal < 1) {
113
+ throw new BaselineIdentityError(`finding ${finding.ruleId} in ${finding.filePath} has symbol "${symbol}" without a declaration ordinal`);
114
+ }
115
+ return `${symbol}${ORDINAL_SEPARATOR}${ordinal}`;
116
+ }
117
+
118
+ /**
119
+ * Compute the stable 16-character baseline digest for a finding identity.
120
+ * The explicit language lets conformance tests compare the calculation with pinned identities for other ports.
121
+ *
122
+ * @param toolLanguage - writer language token included in the hash input
123
+ * @param ruleId - finding rule identifier included in the digest input
124
+ * @param path - finding file path included in the digest input
125
+ * @param subject - finding identity subject included in the digest input
126
+ * @returns The 16-character lowercase hex prefix of the SHA-256 digest over the null-joined inputs.
127
+ */
128
+ export function computeIdentityFor(toolLanguage: string, ruleId: string, path: string, subject: string): string {
129
+ return createHash("sha256").update([toolLanguage, ruleId, path, subject].join("\0")).digest("hex").slice(0, 16);
130
+ }
131
+
132
+ /**
133
+ * Assign stable baseline identities through the same path for generation and matching, preserving names already assigned to the full scan.
134
+ *
135
+ * @param findings - findings to rank together or whose stored identities and subjects to reuse
136
+ * @param declarationPosition - resolver for declaration ranking. Defaults to the finding's line position.
137
+ * @returns One identity record per input finding in order. Ineligible findings and findings with no usable subject receive undefined.
138
+ */
139
+ export function findingIdentities(findings: Finding[], declarationPosition: DeclarationPositionResolver = declarationPositionByLine): Array<FindingIdentity | undefined> {
140
+ const ordinals = symbolOrdinals(findings, declarationPosition);
141
+ return findings.map((finding, index) => {
142
+ // Findings classified as sensitive get no baseline identity, so a stored review cannot suppress them.
143
+ if (!isBaselineEligible(finding)) {
144
+ return undefined;
145
+ }
146
+ // Reuse a name assigned across the full scan so a filtered consumer preserves the declaration's original ordinal.
147
+ if (finding.baselineIdentity !== undefined && finding.baselineSubject !== undefined) {
148
+ return { identity: finding.baselineIdentity, subject: finding.baselineSubject, declarationKey: storedDeclarationKey(finding, finding.baselineSubject) };
149
+ }
150
+ const subject = baselineSubject(finding, ordinals[index] ?? 0);
151
+ // An unusable subject leaves the finding without a stable match key, so baseline matching cannot hide it.
152
+ if (subject === undefined) {
153
+ return undefined;
154
+ }
155
+ return {
156
+ identity: computeIdentityFor(TOOL_LANGUAGE, finding.ruleId, finding.filePath, subject),
157
+ subject,
158
+ declarationKey: declarationKey(finding, declarationPosition),
159
+ };
160
+ });
161
+ }
162
+
163
+ /**
164
+ * Rank same-named declarations within each file so stable baseline identities distinguish namesakes.
165
+ *
166
+ * @param findings - current findings whose file and symbol define each ranking group
167
+ * @param declarationPosition - resolves declaration positions and can supply additional same-name positions
168
+ * @returns One ordinal per finding in input order. Named declarations rank from one, and zero marks a finding with no eligible symbol.
169
+ */
170
+ function symbolOrdinals(findings: Finding[], declarationPosition: DeclarationPositionResolver): number[] {
171
+ const positionsBySymbol = new Map<string, Set<number>>();
172
+ for (const finding of findings) {
173
+ const symbol = namedSymbol(finding);
174
+ if (symbol !== undefined) {
175
+ const key = `${finding.filePath}\0${symbol}`;
176
+ const positions = positionsBySymbol.get(key) ?? new Set<number>();
177
+ positions.add(declarationPosition(finding));
178
+ // Include any extra positions supplied by the resolver so declarations without findings can still reserve their slots.
179
+ for (const position of declarationPosition.sameNamedPositions?.(finding) ?? []) {
180
+ positions.add(position);
181
+ }
182
+ positionsBySymbol.set(key, positions);
183
+ }
184
+ }
185
+
186
+ return findings.map((finding) => {
187
+ const symbol = namedSymbol(finding);
188
+ // With no eligible symbol, zero signals that there is no declaration rank to use.
189
+ if (symbol === undefined) {
190
+ return 0;
191
+ }
192
+ const positions = [...(positionsBySymbol.get(`${finding.filePath}\0${symbol}`) ?? new Set<number>())].sort((left, right) => left - right);
193
+ return positions.indexOf(declarationPosition(finding)) + 1;
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Build a stable collision key for the current finding, where distinct keys under the same baseline identity mark a collision.
199
+ * Findings without an eligible symbol share a file-level key so repeated measurements can be matched by count.
200
+ *
201
+ * @param finding - finding whose symbol eligibility and position determine the collision key
202
+ * @param declarationPosition - resolver returning the declaration position for a named finding
203
+ * @returns The file-level key for findings without an eligible symbol, or a declaration key using the resolved position.
204
+ */
205
+ function declarationKey(finding: Finding, declarationPosition: DeclarationPositionResolver): string {
206
+ return namedSymbol(finding) === undefined ? "declaration:file" : `declaration:${declarationPosition(finding)}`;
207
+ }
208
+
209
+ /**
210
+ * Build the stable collision key for a finding reusing its baseline identity to preserve grouping.
211
+ *
212
+ * @param finding - finding checked for an eligible symbol
213
+ * @param subject - stored baseline subject used in the key for a named finding
214
+ * @returns The file-level key when there is no eligible symbol, or a subject-scoped declaration key for a named finding.
215
+ */
216
+ function storedDeclarationKey(finding: Finding, subject: string): string {
217
+ return namedSymbol(finding) === undefined ? "declaration:file" : `declaration:subject:${subject}`;
218
+ }
219
+
220
+ /**
221
+ * Extract the symbol used for stable declaration grouping, excluding findings ineligible for baseline matching.
222
+ *
223
+ * @param finding - finding checked for baseline eligibility and a non-empty symbol
224
+ * @returns The non-empty symbol, or undefined when missing, empty, or ineligible (even when carrying a symbol) so it gets no rank.
225
+ */
226
+ function namedSymbol(finding: Finding): string | undefined {
227
+ if (!isBaselineEligible(finding)) {
228
+ return undefined;
229
+ }
230
+ return finding.symbol && finding.symbol.length > 0 ? finding.symbol : undefined;
231
+ }
232
+
233
+ // Rules whose finding line anchors on a leading comment or tag above the callable declaration rather than inside its body span.
234
+ const DOCBLOCK_COMMENT_ANCHORED_RULES = new Set([
235
+ "docs.missing-param-tag",
236
+ "docs.missing-return-tag",
237
+ "docs.stale-param-tag",
238
+ ]);
239
+
240
+ /**
241
+ * Build a stable position resolver so moving a finding within a matched declaration preserves its position for ranking.
242
+ * When spans carry column bounds, same-line same-named declarations receive distinct monotonic positions so each gets its own ordinal.
243
+ *
244
+ * @param spansByFile - parsed spans grouped by path for matching declarations and collecting same-name positions; empty map ranks by line alone
245
+ * @returns Resolver with same-name positions. Uses the matching span's position or the finding's line, defaulting to 1 when unlocated.
246
+ */
247
+ export function declarationPositionFromSpans(spansByFile: Map<string, DeclarationSpan[]>): DeclarationPositionResolver {
248
+ /**
249
+ * Resolve a stable declaration position for identity ranking, using the parsed span when it matches the finding.
250
+ *
251
+ * @param finding - occurrence whose path, line, optional column, and final symbol segment locate its declaration
252
+ * @returns The matching declaration's position, or the finding's line when no span encloses it. A missing finding line is treated as 1.
253
+ */
254
+ const resolver: DeclarationPositionResolver = (finding: Finding) => {
255
+ const line = finding.line ?? 1;
256
+ const symbol = namedSymbol(finding);
257
+ // Without an eligible symbol there is no declaration to rank, so use the finding's line position.
258
+ if (symbol === undefined) {
259
+ return line;
260
+ }
261
+ const wanted = symbol.split(".").at(-1) ?? symbol;
262
+ const fileSpans = spansByFile.get(finding.filePath) ?? [];
263
+ // Docblock findings anchor on the leading comment above the declaration, so map them to the nearest same-named span at or after that location.
264
+ if (DOCBLOCK_COMMENT_ANCHORED_RULES.has(finding.ruleId)) {
265
+ const following = nearestSpanAtOrAfter(fileSpans, wanted, line, finding.column);
266
+ if (following !== undefined) {
267
+ return spanPosition(following);
268
+ }
269
+ }
270
+ // Choose the innermost enclosing span so nested or same-line same-named declarations each keep their own position.
271
+ const enclosing = innermostEnclosingSpan(fileSpans, wanted, line, finding.endLine, finding.column);
272
+ // A finding outside every span ranks by line alone, so two rules reporting one symbol on one line share an ordinal.
273
+ return enclosing !== undefined ? spanPosition(enclosing) : line;
274
+ };
275
+ resolver.sameNamedPositions = (finding: Finding) => {
276
+ const symbol = namedSymbol(finding);
277
+ // With no eligible symbol there are no positions to add to ranking.
278
+ // Qualified names rank from their findings alone because span names lack the class qualifier and could merge distinct methods.
279
+ if (symbol === undefined || symbol.includes(".")) {
280
+ return [];
281
+ }
282
+ return (spansByFile.get(finding.filePath) ?? []).filter((span) => span.name === symbol).map(spanPosition);
283
+ };
284
+ return resolver;
285
+ }
286
+
287
+ /**
288
+ * Encodes a 1-based line and optional 1-based column into one monotonic numeric position for declaration ranking.
289
+ * Column 1 and absent columns produce the exact integer line number so single-column callers keep integer positions.
290
+ *
291
+ * @param line - one-based source line number
292
+ * @param column - optional one-based source column number; omitted or 1 keeps the exact integer line number
293
+ * @returns Monotonic numeric coordinate strictly less than `line + 1`.
294
+ */
295
+ function positionForLineColumn(line: number, column?: number): number {
296
+ return column !== undefined && column > 1
297
+ ? line + Math.min(column - 1, MAX_COLUMN_OFFSET) / COLUMN_POSITION_SCALE
298
+ : line;
299
+ }
300
+
301
+ /**
302
+ * Returns the monotonic ranking position of a parsed declaration span from its start line and optional start column.
303
+ *
304
+ * @param span - parsed declaration span to position
305
+ * @returns Monotonic numeric position preserving source order across lines and same-line columns.
306
+ */
307
+ function spanPosition(span: DeclarationSpan): number {
308
+ return positionForLineColumn(span.startLine, span.startColumn);
309
+ }
310
+
311
+ /**
312
+ * Checks whether `span` encloses a finding's `(line, endLine, column)`, applying end-line and column bounds when available.
313
+ *
314
+ * @param span - candidate declaration span to test
315
+ * @param line - one-based finding start line
316
+ * @param endLine - optional one-based finding end line that must not extend past `span.endLine`
317
+ * @param column - optional one-based finding column
318
+ * @returns True when the finding location falls within `span`; otherwise false.
319
+ */
320
+ function spanEnclosesLocation(span: DeclarationSpan, line: number, endLine: number | undefined, column: number | undefined): boolean {
321
+ // A finding outside the declaration's lines belongs to some other declaration.
322
+ if (span.startLine > line || line > span.endLine) {
323
+ return false;
324
+ }
325
+ // A finding that runs past the declaration's last line is not inside it.
326
+ if (endLine !== undefined && endLine > span.endLine) {
327
+ return false;
328
+ }
329
+ // Without a finding column, the line bounds alone decide.
330
+ if (column === undefined) {
331
+ return true;
332
+ }
333
+ // On the declaration's first line, a finding left of its start column belongs to an earlier declaration on that line.
334
+ if (span.startLine === line && span.startColumn !== undefined && column < span.startColumn) {
335
+ return false;
336
+ }
337
+ // On the declaration's last line, a finding right of its end column belongs to a later declaration on that line.
338
+ if (span.endLine === line && span.endColumn !== undefined && column > span.endColumn) {
339
+ return false;
340
+ }
341
+ return true;
342
+ }
343
+
344
+ /**
345
+ * Picks the tightest same-named declaration that contains the finding's line, end line and column.
346
+ * Nested functions and same-line functions with one name then keep separate baseline positions.
347
+ *
348
+ * @param spans - parsed declaration spans for the finding's file
349
+ * @param wantedName - unqualified declaration symbol name being matched
350
+ * @param line - one-based finding line that must lie within `[startLine, endLine]`
351
+ * @param endLine - optional one-based finding end line used to distinguish same-start-line declarations of different lengths
352
+ * @param column - optional one-based finding column used to disambiguate same-line declarations
353
+ * @returns The matching enclosing span with the smallest span (tie-broken by latest start position), or undefined if none encloses the location.
354
+ */
355
+ function innermostEnclosingSpan(spans: readonly DeclarationSpan[], wantedName: string, line: number, endLine?: number, column?: number): DeclarationSpan | undefined {
356
+ let best: DeclarationSpan | undefined;
357
+ const hasColumn = column !== undefined;
358
+ for (const span of spans) {
359
+ // Skip declarations with another name and those that do not contain the finding.
360
+ if (span.name !== wantedName || !spanEnclosesLocation(span, line, endLine, column)) {
361
+ continue;
362
+ }
363
+ // Keep the tightest match, so a nested same-named function wins over the one around it.
364
+ if (best === undefined || isTighterEnclosingSpan(span, best, hasColumn)) {
365
+ best = span;
366
+ }
367
+ }
368
+ return best;
369
+ }
370
+
371
+ /**
372
+ * Compares two enclosing spans by line length, optional same-line column width, and latest start position.
373
+ *
374
+ * @param candidate - newly considered enclosing span
375
+ * @param currentBest - tightest enclosing span selected so far
376
+ * @param hasColumn - true when the finding supplied a column so same-line width can disambiguate nested spans
377
+ * @returns True when `candidate` is strictly tighter than `currentBest` (or tied in size with a later start position).
378
+ */
379
+ function isTighterEnclosingSpan(candidate: DeclarationSpan, currentBest: DeclarationSpan, hasColumn: boolean): boolean {
380
+ const candidateLines = candidate.endLine - candidate.startLine;
381
+ const bestLines = currentBest.endLine - currentBest.startLine;
382
+ // Fewer lines means the more deeply nested declaration.
383
+ if (candidateLines !== bestLines) {
384
+ return candidateLines < bestLines;
385
+ }
386
+ const candidateWidth = singleLineSpanWidth(candidate, hasColumn);
387
+ const bestWidth = singleLineSpanWidth(currentBest, hasColumn);
388
+ // With equal line counts on one line, the narrower span is the inner declaration.
389
+ if (candidateWidth !== bestWidth) {
390
+ return candidateWidth < bestWidth;
391
+ }
392
+ return spanPosition(candidate) > spanPosition(currentBest);
393
+ }
394
+
395
+ /**
396
+ * Computes the column width of a single-line span when column disambiguation is active, or `Infinity` otherwise.
397
+ *
398
+ * @param span - declaration span to measure
399
+ * @param hasColumn - true when the finding carries a column coordinate
400
+ * @returns Column width for a column-bounded single-line span, or `Infinity` when width comparison does not apply.
401
+ */
402
+ function singleLineSpanWidth(span: DeclarationSpan, hasColumn: boolean): number {
403
+ // Width breaks ties only for one-line spans with both columns known; every other span compares as equal.
404
+ if (!hasColumn || span.startLine !== span.endLine || span.startColumn === undefined || span.endColumn === undefined) {
405
+ return Number.POSITIVE_INFINITY;
406
+ }
407
+ return span.endColumn - span.startColumn;
408
+ }
409
+
410
+ /**
411
+ * Checks whether a span starts before a doc comment's location; on a shared line only a real start column can put it earlier.
412
+ * A span whose leading JSDoc starts its first line has no column, so an indented `/**` on that line still belongs to it.
413
+ *
414
+ * @param span - candidate declaration span
415
+ * @param line - one-based line of the doc comment the finding points at
416
+ * @param column - optional one-based column of that doc comment; absent means only lines are compared
417
+ * @returns True when the span starts on an earlier line, or earlier on the same line by a known column
418
+ */
419
+ function startsBeforeLocation(span: DeclarationSpan, line: number, column: number | undefined): boolean {
420
+ // Different lines settle order immediately without needing column coordinates.
421
+ if (span.startLine !== line) {
422
+ return span.startLine < line;
423
+ }
424
+ // Columns compare only when both are known, which is the case for two same-named declarations on one line.
425
+ return column !== undefined && span.startColumn !== undefined && span.startColumn < column;
426
+ }
427
+
428
+ /**
429
+ * Finds the nearest same-named declaration span starting at or after a leading-comment finding location.
430
+ *
431
+ * @param spans - parsed declaration spans for the finding's file
432
+ * @param wantedName - unqualified declaration symbol name being matched
433
+ * @param line - one-based comment or tag line where the docblock finding is anchored
434
+ * @param column - optional one-based finding column used to disambiguate same-line declarations
435
+ * @returns The matching span with the smallest start position at or after `(line, column)`, or undefined when none follows.
436
+ */
437
+ function nearestSpanAtOrAfter(spans: readonly DeclarationSpan[], wantedName: string, line: number, column?: number): DeclarationSpan | undefined {
438
+ let nearest: DeclarationSpan | undefined;
439
+ let nearestPosition = Number.POSITIVE_INFINITY;
440
+ for (const span of spans) {
441
+ const candidatePosition = spanPosition(span);
442
+ // Skip other names and declarations that start before the doc comment the finding points at.
443
+ if (span.name !== wantedName || startsBeforeLocation(span, line, column)) {
444
+ continue;
445
+ }
446
+ // Keep the closest following declaration, which is the one the doc comment sits above.
447
+ if (nearest === undefined || candidatePosition < nearestPosition) {
448
+ nearest = span;
449
+ nearestPosition = candidatePosition;
450
+ }
451
+ }
452
+ return nearest;
453
+ }
454
+
455
+ /**
456
+ * Resolve a stable declaration position from the finding's own line when parsed declarations are unavailable.
457
+ *
458
+ * @param finding - finding whose line property supplies the fallback position
459
+ * @returns The finding's line number, or 1 for unlocated findings.
460
+ */
461
+ export function declarationPositionByLine(finding: Finding): number {
462
+ return finding.line ?? 1;
463
+ }