@blundergoat/gruff-ts 0.4.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 +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  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 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  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 +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  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 +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  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 +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -26,8 +26,12 @@ interface CommentScanState {
26
26
 
27
27
  type CommentScanHandler = (source: string, index: number, state: CommentScanState, records: CommentRecord[]) => number | undefined;
28
28
 
29
- // Source-text comment lexer. Produces the stable list of CommentRecords every documentation rule
30
- // consumes. Walks the file once via the prioritised handler chain (`COMMENT_SCAN_HANDLERS`).
29
+ /**
30
+ * Scans a file's source text and collects comment records in source order for checks that inspect comment text and locations.
31
+ *
32
+ * @param source - the whole file text to scan for line and block comments
33
+ * @returns comment records in source order, or an empty array when the lexer recognises no source comments
34
+ */
31
35
  export function commentRecords(source: string): CommentRecord[] {
32
36
  const records: CommentRecord[] = [];
33
37
  const state = initialCommentScanState();
@@ -48,7 +52,15 @@ const COMMENT_SCAN_HANDLERS: CommentScanHandler[] = [
48
52
  scanRegexStartStep,
49
53
  ];
50
54
 
51
- /** Runs the first lexer step that can consume the current source character. */
55
+ /**
56
+ * Runs the first lexer step that can consume the current source character.
57
+ *
58
+ * @param source - the whole file text being scanned
59
+ * @param index - position of the current character in `source`
60
+ * @param state - lexer state, updated by whichever step runs; an unconsumed non-whitespace character becomes `previousCode`
61
+ * @param records - comment records found so far; the comment step appends to it
62
+ * @returns index of the last consumed character, after which `commentRecords` resumes; `index` when no step consumed the character
63
+ */
52
64
  function advanceCommentRecordScan(source: string, index: number, state: CommentScanState, records: CommentRecord[]): number {
53
65
  for (const handler of COMMENT_SCAN_HANDLERS) {
54
66
  const nextIndex = handler(source, index, state, records);
@@ -60,7 +72,11 @@ function advanceCommentRecordScan(source: string, index: number, state: CommentS
60
72
  return index;
61
73
  }
62
74
 
63
- /** Creates a fresh comment lexer state for a single source file scan. */
75
+ /**
76
+ * Creates a fresh comment lexer state for a single source file scan.
77
+ *
78
+ * @returns state at line 1 with no open string, template or regex and no previous code character
79
+ */
64
80
  function initialCommentScanState(): CommentScanState {
65
81
  return {
66
82
  quote: undefined,
@@ -73,7 +89,14 @@ function initialCommentScanState(): CommentScanState {
73
89
  };
74
90
  }
75
91
 
76
- /** Consumes newlines and resets quote/regex state that cannot cross lines. */
92
+ /**
93
+ * Consumes newlines and resets quote/regex state that cannot cross lines.
94
+ *
95
+ * @param source - the whole file text being scanned
96
+ * @param index - position of the current character
97
+ * @param state - lexer state; on a newline its line count advances, a non-template quote closes and regex state clears
98
+ * @returns `index` when the character is a newline, or undefined to pass it to the next step
99
+ */
77
100
  function scanCommentLineBreak(source: string, index: number, state: CommentScanState): number | undefined {
78
101
  if ((source[index] ?? "") !== "\n") {
79
102
  return undefined;
@@ -82,7 +105,12 @@ function scanCommentLineBreak(source: string, index: number, state: CommentScanS
82
105
  return index;
83
106
  }
84
107
 
85
- /** Advances the lexer after a newline has been consumed. */
108
+ /**
109
+ * Advances the lexer after a newline has been consumed.
110
+ *
111
+ * @param state - lexer state to update: the line count goes up by one, any quote except a template backtick closes, and the regex flags clear
112
+ * @returns Nothing. Updates the lexer state in place for the next line.
113
+ */
86
114
  function advanceCommentScanLine(state: CommentScanState): void {
87
115
  state.line += 1;
88
116
  if (state.quote !== "`") {
@@ -93,12 +121,25 @@ function advanceCommentScanLine(state: CommentScanState): void {
93
121
  state.isRegexCharClass = false;
94
122
  }
95
123
 
96
- /** Keeps quoted text from being reported as a real source comment. */
124
+ /**
125
+ * Keeps quoted text from being reported as a real source comment.
126
+ *
127
+ * @param source - the whole file text being scanned
128
+ * @param index - position of the current character
129
+ * @param state - lexer state; inside a string or template, the character updates its quote and escape flags
130
+ * @returns `index` when the lexer is inside a string or template, so the character is neither code nor a comment; otherwise undefined
131
+ */
97
132
  function scanQuotedCommentStep(source: string, index: number, state: CommentScanState): number | undefined {
98
133
  return scanActiveQuotedCommentState(state, source[index] ?? "") ? index : undefined;
99
134
  }
100
135
 
101
- /** Updates quote escape/close state when the lexer is inside a string. */
136
+ /**
137
+ * Updates quote escape/close state when the lexer is inside a string.
138
+ *
139
+ * @param state - lexer state whose quote and escape flags change: a backslash escapes the next character, an unescaped closing quote ends the string
140
+ * @param character - the current source character
141
+ * @returns true when a quote was open, so the character belongs to the string; false when none was open
142
+ */
102
143
  function scanActiveQuotedCommentState(state: CommentScanState, character: string): boolean {
103
144
  if (!state.quote) {
104
145
  return false;
@@ -109,12 +150,25 @@ function scanActiveQuotedCommentState(state: CommentScanState, character: string
109
150
  return true;
110
151
  }
111
152
 
112
- /** Keeps regex literal bodies from being reported as real source comments. */
153
+ /**
154
+ * Keeps regex literal bodies from being reported as real source comments.
155
+ *
156
+ * @param source - the whole file text being scanned
157
+ * @param index - position of the current character
158
+ * @param state - lexer state; inside a regex literal, the character updates its escape, character-class and close flags
159
+ * @returns `index` when the lexer is inside a regex literal, otherwise undefined
160
+ */
113
161
  function scanRegexCommentStep(source: string, index: number, state: CommentScanState): number | undefined {
114
162
  return scanActiveRegexCommentState(state, source[index] ?? "") ? index : undefined;
115
163
  }
116
164
 
117
- /** Updates regex escape, character-class, and close state. */
165
+ /**
166
+ * Updates regex escape, character-class, and close state.
167
+ *
168
+ * @param state - lexer state whose regex flags change: an unescaped `/` outside a character class ends the literal
169
+ * @param character - the current source character
170
+ * @returns true when a regex literal was open, so the character belongs to it; false when none was open
171
+ */
118
172
  function scanActiveRegexCommentState(state: CommentScanState, character: string): boolean {
119
173
  if (!state.isRegex) {
120
174
  return false;
@@ -126,7 +180,15 @@ function scanActiveRegexCommentState(state: CommentScanState, character: string)
126
180
  return true;
127
181
  }
128
182
 
129
- /** Records a line or block comment and returns the consumed source index. */
183
+ /**
184
+ * Records a line or block comment and returns the consumed source index.
185
+ *
186
+ * @param source - the whole file text being scanned
187
+ * @param index - position of the current character, a possible `//` or `/*` start
188
+ * @param state - lexer state; its line moves to the comment's last line
189
+ * @param records - comment records found so far; a comment starting here is appended
190
+ * @returns index of the comment's last character, or undefined when none starts here; a line comment stops before its newline for the line count
191
+ */
130
192
  function scanCommentRecordStep(source: string, index: number, state: CommentScanState, records: CommentRecord[]): number | undefined {
131
193
  const record = commentRecordAt(source, index, state.line);
132
194
  if (!record) {
@@ -137,7 +199,14 @@ function scanCommentRecordStep(source: string, index: number, state: CommentScan
137
199
  return record.kind === "line" ? record.endIndex - 1 : record.endIndex;
138
200
  }
139
201
 
140
- /** Detects whether the current slash pair begins a source comment. */
202
+ /**
203
+ * Detects whether the current slash pair begins a source comment.
204
+ *
205
+ * @param source - the whole file text being scanned
206
+ * @param index - position of the possible `//` or `/*` start
207
+ * @param line - one-based line number of `index`, stored as the record's first line
208
+ * @returns a line or block comment record starting at `index`, or undefined when the two characters there are neither `//` nor `/*`
209
+ */
141
210
  function commentRecordAt(source: string, index: number, line: number): CommentRecord | undefined {
142
211
  const character = source[index] ?? "";
143
212
  const next = source[index + 1] ?? "";
@@ -150,12 +219,25 @@ function commentRecordAt(source: string, index: number, line: number): CommentRe
150
219
  return undefined;
151
220
  }
152
221
 
153
- /** Opens string/template quote state when the current character starts a literal. */
222
+ /**
223
+ * Opens string/template quote state when the current character starts a literal.
224
+ *
225
+ * @param source - the whole file text being scanned
226
+ * @param index - position of the current character
227
+ * @param state - lexer state that records an opener as both the open quote and previous code character and clears the escape flag
228
+ * @returns the current index when a quote opens, otherwise undefined with lexer state unchanged
229
+ */
154
230
  function scanQuoteStartStep(source: string, index: number, state: CommentScanState): number | undefined {
155
231
  return openCommentScanQuote(state, source[index] ?? "") ? index : undefined;
156
232
  }
157
233
 
158
- /** Mutates quote state after a quote-start character is found. */
234
+ /**
235
+ * Mutates quote state after a quote-start character is found.
236
+ *
237
+ * @param state - lexer state; a quote character becomes its open quote and `previousCode`, with the escape flag cleared
238
+ * @param character - the current source character
239
+ * @returns true when the character opened a string or template; false for any other character, leaving the state unchanged
240
+ */
159
241
  function openCommentScanQuote(state: CommentScanState, character: string): boolean {
160
242
  if (character !== "\"" && character !== "'" && character !== "`") {
161
243
  return false;
@@ -166,12 +248,27 @@ function openCommentScanQuote(state: CommentScanState, character: string): boole
166
248
  return true;
167
249
  }
168
250
 
169
- /** Opens regex state for slash tokens that follow expression-start syntax. */
251
+ /**
252
+ * Opens regex state for a slash that the lexer treats as the start of a literal, including when it has seen no code yet.
253
+ *
254
+ * @param source - file text supplying the current character and up to 40 preceding characters to check for return
255
+ * @param index - position of the current character
256
+ * @param state - lexer state to update on a match. Opens the regex, clears its escape and class flags and records the slash as previous code
257
+ * @returns index on a regex start, or undefined with lexer state unchanged when the character does not open a regex
258
+ */
170
259
  function scanRegexStartStep(source: string, index: number, state: CommentScanState): number | undefined {
171
260
  return openCommentScanRegex(state, source, index, source[index] ?? "") ? index : undefined;
172
261
  }
173
262
 
174
- /** Mutates regex state after a regex literal start is found. */
263
+ /**
264
+ * Mutates regex state after a regex literal start is found.
265
+ *
266
+ * @param state - lexer state; a regex start sets the regex flag, clears its escape and character-class flags and makes `/` the previous code
267
+ * @param source - the whole file text; up to 40 characters before `index` are checked for a preceding `return`
268
+ * @param index - position of the current character
269
+ * @param character - the current source character
270
+ * @returns true when the character is a `/` that `isCommentRegexStart` accepts as a regex start; false otherwise, leaving the state unchanged
271
+ */
175
272
  function openCommentScanRegex(state: CommentScanState, source: string, index: number, character: string): boolean {
176
273
  if (character !== "/" || !isCommentRegexStart(state.previousCode, source.slice(Math.max(0, index - 40), index))) {
177
274
  return false;
@@ -183,15 +280,27 @@ function openCommentScanRegex(state: CommentScanState, source: string, index: nu
183
280
  return true;
184
281
  }
185
282
 
186
- /** Remembers the last non-whitespace code token for regex/comment disambiguation. */
283
+ /**
284
+ * Remembers the last non-whitespace code character for regex/comment disambiguation.
285
+ *
286
+ * @param state - lexer state whose previousCode becomes character unless it is whitespace
287
+ * @param character - the source character no other lexer step consumed
288
+ * @returns Nothing. Records the character in the supplied lexer state when it contains non-whitespace.
289
+ */
187
290
  function updateCommentScanPreviousCode(state: CommentScanState, character: string): void {
188
291
  if (/\S/.test(character)) {
189
292
  state.previousCode = character;
190
293
  }
191
294
  }
192
295
 
193
- // Pure function returning the next quote state. Pure because callers thread the state explicitly,
194
- // which keeps the comment-lexer testable in isolation from the surrounding mutation.
296
+ /**
297
+ * Computes the next quote and escape flags for one character inside a string or template.
298
+ *
299
+ * @param character - current source character inside the quoted literal
300
+ * @param quote - opening delimiter of the active string or template literal
301
+ * @param isEscaped - whether the current character is escaped by a preceding backslash
302
+ * @returns updated quote and escape flags; an unescaped matching delimiter yields an undefined quote so scanning resumes outside the literal
303
+ */
195
304
  function scanQuotedCommentCharacter(character: string, quote: string, isEscaped: boolean): { quote: string | undefined; isEscaped: boolean } {
196
305
  if (isEscaped) {
197
306
  return { quote, isEscaped: false };
@@ -205,7 +314,14 @@ function scanQuotedCommentCharacter(character: string, quote: string, isEscaped:
205
314
  return { quote, isEscaped: false };
206
315
  }
207
316
 
208
- // Pure step that yields the next regex state. Same isolation pattern as `scanQuotedCommentCharacter`.
317
+ /**
318
+ * Computes the next regex state from one character inside a regex literal.
319
+ *
320
+ * @param character - current source character inside the regex literal
321
+ * @param isEscaped - whether the current character is escaped by a preceding backslash
322
+ * @param isCharClass - whether the scanner is currently inside a `[...]` character class
323
+ * @returns updated open, escape, and character-class flags; an unescaped slash outside a class closes the regex
324
+ */
209
325
  function scanRegexCommentCharacter(character: string, isEscaped: boolean, isCharClass: boolean): { isRegex: boolean; isEscaped: boolean; isCharClass: boolean } {
210
326
  if (isEscaped) {
211
327
  return { isRegex: true, isEscaped: false, isCharClass };
@@ -225,14 +341,25 @@ function scanRegexCommentCharacter(character: string, isEscaped: boolean, isChar
225
341
  return { isRegex: true, isEscaped: false, isCharClass };
226
342
  }
227
343
 
228
- // Same regex-vs-division heuristic as `source-text.ts:isRegexLiteralStart`. Duplicated here so the
229
- // comment lexer stays a leaf with no cross-module dependency on the masking pass.
344
+ /**
345
+ * Determines whether a slash opens a regex literal, mirroring the masking pass to keep the comment lexer independent.
346
+ *
347
+ * @param previousCode - last non-whitespace code character before the slash, or empty when none was seen yet
348
+ * @param beforeSlash - available source slice immediately preceding the slash, checked for a trailing `return` keyword
349
+ * @returns true when `previousCode` is empty or a regex-preceding token, or `beforeSlash` ends with `return`; false otherwise
350
+ */
230
351
  function isCommentRegexStart(previousCode: string, beforeSlash: string): boolean {
231
352
  return previousCode === "" || "([{=,:!&|?;".includes(previousCode) || /\breturn$/.test(beforeSlash.trimEnd());
232
353
  }
233
354
 
234
- // Line-comment record. `line === endLine` because line comments cannot span newlines. Text is
235
- // captured trimmed so leading/trailing whitespace doesn't enter rule comparisons.
355
+ /**
356
+ * Builds a record for a line comment at its opener offset and trims its body for rule comparisons.
357
+ *
358
+ * @param source - whole file text being scanned
359
+ * @param startIndex - zero-based offset of the `//` opener in `source`
360
+ * @param line - one-based line number used for both `line` and `endLine`
361
+ * @returns line comment record whose exclusive `endIndex` is the newline index, or `source.length` when no newline follows
362
+ */
236
363
  function lineCommentRecord(source: string, startIndex: number, line: number): CommentRecord {
237
364
  const newline = source.indexOf("\n", startIndex + 2);
238
365
  const endIndex = newline === -1 ? source.length : newline;
@@ -246,8 +373,14 @@ function lineCommentRecord(source: string, startIndex: number, line: number): Co
246
373
  };
247
374
  }
248
375
 
249
- // Block-comment record. `endLine > line` is normal for multi-line blocks. `text` is normalised
250
- // (leading-asterisk decoration stripped) so JSDoc-style and plain-block comments compare equally.
376
+ /**
377
+ * Builds a record for a block comment, dropping leading asterisks so prose compares equally in JSDoc and plain blocks.
378
+ *
379
+ * @param source - whole file text being scanned
380
+ * @param startIndex - zero-based offset of the block comment opener in `source`
381
+ * @param line - one-based line number of the opener
382
+ * @returns block comment record whose `endIndex` points to the closer's last character, or the final source character when unclosed
383
+ */
251
384
  function blockCommentRecord(source: string, startIndex: number, line: number): CommentRecord {
252
385
  let endIndex = source.length - 1;
253
386
  let endLine = line;
@@ -270,8 +403,12 @@ function blockCommentRecord(source: string, startIndex: number, line: number): C
270
403
  };
271
404
  }
272
405
 
273
- // Strips the `* ` JSDoc-style line decoration so `/** foo */`, `/* foo */`, and `// foo` all
274
- // produce the same `text` payload for rule comparison.
406
+ /**
407
+ * Extracts comparison text from a delimiter-free block comment body by removing leading asterisks and joining nonblank lines.
408
+ *
409
+ * @param text - block comment body with opening and closing delimiters already removed
410
+ * @returns normalized space-joined prose, or an empty string when the body contains only decoration and whitespace
411
+ */
275
412
  function normalizedBlockCommentText(text: string): string {
276
413
  return text
277
414
  .split(/\r?\n/)
@@ -281,15 +418,55 @@ function normalizedBlockCommentText(text: string): string {
281
418
  .trim();
282
419
  }
283
420
 
284
- // String-input wrapper around `hasLeadingCommentBeforeLines`. Keeps call sites that already hold
285
- // a split line array from re-splitting on every lookup.
421
+ /**
422
+ * Reads consecutive line comments as one maintainer comment while keeping the final record's source position.
423
+ *
424
+ * @param comments - comment records in source order so context on earlier lines of the header still counts
425
+ * @param finalComment - trailing comment record whose contiguous preceding line comments should be merged
426
+ * @returns merged comment record anchored at `finalComment`, or `finalComment` unchanged if it is a block comment or absent from `comments`
427
+ */
428
+ export function combinedContextLineComment(comments: CommentRecord[], finalComment: CommentRecord): CommentRecord {
429
+ if (finalComment.kind !== "line") {
430
+ return finalComment;
431
+ }
432
+ const finalIndex = comments.indexOf(finalComment);
433
+ if (finalIndex < 0) {
434
+ return finalComment;
435
+ }
436
+ let firstIndex = finalIndex;
437
+ while (firstIndex > 0) {
438
+ const previous = comments[firstIndex - 1];
439
+ const current = comments[firstIndex];
440
+ if (!previous || !current || previous.kind !== "line" || previous.endLine + 1 !== current.line) {
441
+ break;
442
+ }
443
+ firstIndex -= 1;
444
+ }
445
+ const text = comments
446
+ .slice(firstIndex, finalIndex + 1)
447
+ .map((comment) => comment.text)
448
+ .join(" ");
449
+ return { ...finalComment, text };
450
+ }
451
+
452
+ /**
453
+ * Splits file text into lines and checks whether usable leading comment text precedes a declaration line.
454
+ *
455
+ * @param source - whole file text to split on line breaks
456
+ * @param line - one-based line number of the declaration
457
+ * @returns true when a nonblank comment with usable text precedes `line`, otherwise false
458
+ */
286
459
  export function hasLeadingCommentBeforeLine(source: string, line: number): boolean {
287
460
  return hasLeadingCommentBeforeLines(source.split(/\r?\n/), line);
288
461
  }
289
462
 
290
- // Skips blank padding above the declaration and asks whether the immediately preceding non-blank
291
- // line is any comment shape (`//`, `/*`, or `*/`). Underlies the missing-comment rules across
292
- // functions, interfaces, and exported declarations.
463
+ /**
464
+ * Checks source lines above a declaration line, skipping blank padding, for a usable leading comment.
465
+ *
466
+ * @param lines - source file split into zero-based lines
467
+ * @param line - one-based line number of the declaration
468
+ * @returns true if the nearest preceding nonblank line yields comment text, and false if there is no usable text
469
+ */
293
470
  export function hasLeadingCommentBeforeLines(lines: string[], line: number): boolean {
294
471
  let index = line - 2;
295
472
  while (index >= 0 && (lines[index] ?? "").trim() === "") {
@@ -298,9 +475,137 @@ export function hasLeadingCommentBeforeLines(lines: string[], line: number): boo
298
475
  return index >= 0 && commentTextAtLine(lines, index) !== undefined;
299
476
  }
300
477
 
301
- // Three comment shapes resolved here: `//` line comments, `/* … */` opener lines, and lines that
302
- // only contain the `*/` closer (call delegates upward to find the opener). Returns undefined for
303
- // non-comment lines and for empty comments, so callers can use truthiness as the "has text" gate.
478
+ /**
479
+ * Checks source lines above a function declaration for leading text that counts as its own documentation.
480
+ *
481
+ * @param lines - source file split into zero-based lines
482
+ * @param line - one-based line number of the function declaration
483
+ * @returns false when blank-skipped preceding text is missing or is a section divider or file overview, otherwise true
484
+ */
485
+ export function hasFunctionLeadingCommentBeforeLines(lines: string[], line: number): boolean {
486
+ let endIndex = line - 2;
487
+ while (endIndex >= 0 && (lines[endIndex] ?? "").trim() === "") {
488
+ endIndex -= 1;
489
+ }
490
+ if (endIndex < 0 || commentTextAtLine(lines, endIndex) === undefined) {
491
+ return false;
492
+ }
493
+ return !isOverviewOrDividerCommentAt(lines, commentStartIndex(lines, endIndex), endIndex, line - 1);
494
+ }
495
+
496
+ /**
497
+ * Finds the opener line of the comment ending on `endIndex` (the first contiguous `//` line for line comments, else the nearest `/*` above).
498
+ *
499
+ * @param lines - source file split into zero-based lines
500
+ * @param endIndex - zero-based line index where the comment ends
501
+ * @returns zero-based line index of the comment opener, or `endIndex` if no opener line is found above
502
+ */
503
+ function commentStartIndex(lines: string[], endIndex: number): number {
504
+ // Walk upward across contiguous `//` lines so tags like `@fileoverview` on line 1 of a multi-line header stay included.
505
+ if ((lines[endIndex] ?? "").trim().startsWith("//")) {
506
+ let start = endIndex;
507
+ while (start > 0 && (lines[start - 1] ?? "").trim().startsWith("//")) {
508
+ start -= 1;
509
+ }
510
+ return start;
511
+ }
512
+ for (let index = endIndex; index >= 0; index -= 1) {
513
+ const trimmedLine = (lines[index] ?? "").trim();
514
+ if (trimmedLine.startsWith("/*")) {
515
+ return index;
516
+ }
517
+ }
518
+ return endIndex;
519
+ }
520
+
521
+ /**
522
+ * Checks whether a comment is a section divider or a file-opening overview rather than declaration documentation.
523
+ *
524
+ * @param lines - source file lines from the beginning so earlier code can rule out a file overview
525
+ * @param startIndex - zero-based inclusive start line index of the comment
526
+ * @param endIndex - zero-based inclusive end line index of the comment
527
+ * @param declarationIndex - zero-based line index of the following declaration, bounding the gap lines
528
+ * @returns true for a section divider or a file-opening comment with a file-level tag or a blank gap before the declaration
529
+ */
530
+ export function isOverviewOrDividerCommentAt(lines: string[], startIndex: number, endIndex: number, declarationIndex: number): boolean {
531
+ const commentText = lines.slice(startIndex, endIndex + 1).join("\n");
532
+ return isDividerComment(commentText) || (isFileOverviewComment(commentText, lines.slice(endIndex + 1, declarationIndex)) && isFileOpeningLine(lines, startIndex));
533
+ }
534
+
535
+ /**
536
+ * Detects one-line section-divider comments (such as `// ---- helpers` or a `====` block comment) that do not describe the function below.
537
+ *
538
+ * @param commentText - raw comment text across one or more source lines
539
+ * @returns true when `commentText` is a single line opening with three or more `-`, `=`, `*`, `_`, `#`, `~`, `+`, or `/` characters
540
+ */
541
+ export function isDividerComment(commentText: string): boolean {
542
+ if (commentText.includes("\n")) {
543
+ return false;
544
+ }
545
+ const text = commentText.trim().replace(/^\/\/|^\/\*\*?/, "").replace(/\*\/$/, "").trim();
546
+ return /^[-=*_#~+/]{3,}/.test(text);
547
+ }
548
+
549
+ /**
550
+ * Determines whether a comment looks like a file overview (the caller separately checks that it sits at the file opening).
551
+ *
552
+ * @param commentText - raw comment text checked for file-level JSDoc tags
553
+ * @param gapLines - source lines between the end of the comment and the next declaration
554
+ * @returns true when `commentText` has a file-level tag or `gapLines` contains a blank separator line
555
+ */
556
+ export function isFileOverviewComment(commentText: string, gapLines: string[]): boolean {
557
+ return gapLines.some((gapLine) => gapLine.trim() === "") || /@(?:file|fileoverview|overview|packageDocumentation|module|license)\b/.test(commentText);
558
+ }
559
+
560
+ /**
561
+ * Checks whether a comment at `startIndex` opens the file, stopping as soon as any preceding code token appears.
562
+ * Handles inline block comments followed by code on the same line (such as `/* policy *\/ export const seed = 1;`).
563
+ *
564
+ * @param lines - source file split into zero-based lines
565
+ * @param startIndex - zero-based start line index of the comment being tested
566
+ * @returns True when only a shebang, blank lines, and earlier comments precede `startIndex`; false if code appears first.
567
+ */
568
+ function isFileOpeningLine(lines: string[], startIndex: number): boolean {
569
+ let isInBlockComment = false;
570
+ for (let index = 0; index < startIndex; index += 1) {
571
+ let rest = (lines[index] ?? "").trim();
572
+ if (index === 0 && !isInBlockComment && rest.startsWith("#!")) {
573
+ continue;
574
+ }
575
+ // Consume any sequence of block comments and trailing line comments on this line; any leftover token is code.
576
+ while (rest !== "") {
577
+ if (isInBlockComment) {
578
+ const closeIndex = rest.indexOf("*/");
579
+ if (closeIndex === -1) {
580
+ rest = "";
581
+ break;
582
+ }
583
+ isInBlockComment = false;
584
+ rest = rest.slice(closeIndex + 2).trim();
585
+ continue;
586
+ }
587
+ if (rest.startsWith("//")) {
588
+ rest = "";
589
+ break;
590
+ }
591
+ if (rest.startsWith("/*")) {
592
+ isInBlockComment = true;
593
+ rest = rest.slice(2);
594
+ continue;
595
+ }
596
+ return false;
597
+ }
598
+ }
599
+ return !isInBlockComment;
600
+ }
601
+
602
+ /**
603
+ * Extracts comment prose at a source line from a line comment, block opener, or trailing block closer, dropping block tag lines.
604
+ *
605
+ * @param lines - source file split into zero-based lines
606
+ * @param index - zero-based line index to inspect
607
+ * @returns extracted comment text, or undefined when no text remains, an opener lacks a closer, or the line has no comment
608
+ */
304
609
  export function commentTextAtLine(lines: string[], index: number): string | undefined {
305
610
  const trimmedLine = (lines[index] ?? "").trim();
306
611
  if (trimmedLine.startsWith("//")) {
@@ -316,9 +621,13 @@ export function commentTextAtLine(lines: string[], index: number): string | unde
316
621
  return undefined;
317
622
  }
318
623
 
319
- // Walks upward from a `*/` closer to its matching `/*` opener, then delegates to
320
- // `blockCommentText` to extract the joined body. Used when a declaration's leading comment is a
321
- // block comment whose closer sits on the line above the declaration.
624
+ /**
625
+ * Walks upward from a block closer to its matching opener and extracts the joined body for a leading declaration comment.
626
+ *
627
+ * @param lines - source file split into zero-based lines
628
+ * @param endIndex - zero-based line index ending with the block comment closer
629
+ * @returns extracted block comment text from `blockCommentText`, or undefined if no matching opener line is found
630
+ */
322
631
  function blockCommentTextEndingAt(lines: string[], endIndex: number): string | undefined {
323
632
  for (let index = endIndex; index >= 0; index -= 1) {
324
633
  if ((lines[index] ?? "").trim().startsWith("/*")) {
@@ -328,9 +637,14 @@ function blockCommentTextEndingAt(lines: string[], endIndex: number): string | u
328
637
  return undefined;
329
638
  }
330
639
 
331
- // Joins a block comment's lines into one normalised text run: strips `/*` / `*/` / leading `*`,
332
- // drops `@tag` lines, and collapses whitespace. The `knownEndIndex` parameter lets
333
- // `blockCommentTextEndingAt` skip the scan when the closer line is already known.
640
+ /**
641
+ * Extracts space-joined prose from a block comment starting at `startIndex`, stripping delimiters, leading asterisks, and tag lines.
642
+ *
643
+ * @param lines - source file split into zero-based lines
644
+ * @param startIndex - zero-based line index of the block opener
645
+ * @param knownEndIndex - optional zero-based closer line index that skips searching for the end of the block
646
+ * @returns trimmed, space-joined comment text, or undefined when no closer is found or no prose remains
647
+ */
334
648
  function blockCommentText(lines: string[], startIndex: number, knownEndIndex?: number): string | undefined {
335
649
  const endIndex = knownEndIndex ?? blockCommentEndIndex(lines, startIndex);
336
650
  if (endIndex === undefined) {
@@ -345,8 +659,13 @@ function blockCommentText(lines: string[], startIndex: number, knownEndIndex?: n
345
659
  return text === "" ? undefined : text;
346
660
  }
347
661
 
348
- // Forward scan for the next line containing `*/`. Returns undefined for unterminated comments,
349
- // which the caller treats as "no useful text" rather than throwing - partial-scan robustness.
662
+ /**
663
+ * Finds the first source line index containing a block closer at or after the block opener.
664
+ *
665
+ * @param lines - source file split into zero-based lines
666
+ * @param startIndex - zero-based line index of the block comment opener
667
+ * @returns zero-based line index of the closing line, or undefined when no closer is found
668
+ */
350
669
  function blockCommentEndIndex(lines: string[], startIndex: number): number | undefined {
351
670
  for (let index = startIndex; index < lines.length; index += 1) {
352
671
  if ((lines[index] ?? "").includes("*/")) {