@kongyo2/ts-comment-scanner 1.21.0 → 1.23.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 (66) hide show
  1. package/README.md +240 -52
  2. package/dist/astgrep.d.ts +4 -2
  3. package/dist/astgrep.d.ts.map +1 -1
  4. package/dist/astgrep.js +7 -4
  5. package/dist/astgrep.js.map +1 -1
  6. package/dist/containers.d.ts +48 -0
  7. package/dist/containers.d.ts.map +1 -0
  8. package/dist/containers.js +82 -0
  9. package/dist/containers.js.map +1 -0
  10. package/dist/coverage.d.ts +45 -0
  11. package/dist/coverage.d.ts.map +1 -0
  12. package/dist/coverage.js +92 -0
  13. package/dist/coverage.js.map +1 -0
  14. package/dist/directives.d.ts +13 -3
  15. package/dist/directives.d.ts.map +1 -1
  16. package/dist/directives.js +31 -11
  17. package/dist/directives.js.map +1 -1
  18. package/dist/files.d.ts +5 -0
  19. package/dist/files.d.ts.map +1 -1
  20. package/dist/files.js +103 -41
  21. package/dist/files.js.map +1 -1
  22. package/dist/imports.d.ts +12 -5
  23. package/dist/imports.d.ts.map +1 -1
  24. package/dist/imports.js +33 -10
  25. package/dist/imports.js.map +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/lines.d.ts +11 -0
  31. package/dist/lines.d.ts.map +1 -1
  32. package/dist/lines.js +30 -0
  33. package/dist/lines.js.map +1 -1
  34. package/dist/remove.d.ts +16 -12
  35. package/dist/remove.d.ts.map +1 -1
  36. package/dist/remove.js +51 -638
  37. package/dist/remove.js.map +1 -1
  38. package/dist/run.d.ts.map +1 -1
  39. package/dist/run.js +11 -10
  40. package/dist/run.js.map +1 -1
  41. package/dist/scanner.d.ts +29 -0
  42. package/dist/scanner.d.ts.map +1 -1
  43. package/dist/scanner.js +122 -5
  44. package/dist/scanner.js.map +1 -1
  45. package/dist/shields.d.ts +77 -0
  46. package/dist/shields.d.ts.map +1 -0
  47. package/dist/shields.js +758 -0
  48. package/dist/shields.js.map +1 -0
  49. package/dist/splice.d.ts +40 -15
  50. package/dist/splice.d.ts.map +1 -1
  51. package/dist/splice.js +185 -69
  52. package/dist/splice.js.map +1 -1
  53. package/package.json +6 -5
  54. package/src/astgrep.ts +7 -5
  55. package/src/containers.ts +128 -0
  56. package/src/coverage.ts +110 -0
  57. package/src/directives.ts +45 -11
  58. package/src/files.ts +147 -53
  59. package/src/imports.ts +42 -17
  60. package/src/index.ts +1 -0
  61. package/src/lines.ts +33 -1
  62. package/src/remove.ts +58 -748
  63. package/src/run.ts +11 -10
  64. package/src/scanner.ts +160 -5
  65. package/src/shields.ts +852 -0
  66. package/src/splice.ts +216 -75
@@ -0,0 +1,758 @@
1
+ import { astGrepReach, rowStartOffsets } from "./astgrep.js";
2
+ import { commentsOf, removalUnits } from "./containers.js";
3
+ import { hintsNextNode, monocartLines, opensRow, textHints } from "./coverage.js";
4
+ import { carriesAstGrepSuppression } from "./directives.js";
5
+ import { LINE_TERMINATOR, closesItsLine, isBlank, lineIndexAt, lineStartOffsets, occupiesWholeLines, opensItsLine, } from "./lines.js";
6
+ import { byStart, firstIndexAtOrAfter, rangeAt } from "./ranges.js";
7
+ /**
8
+ * Finds what the directives that stay need the removal to leave in place,
9
+ * so that each applies to the same code afterwards, and keeps the comments
10
+ * among it.
11
+ *
12
+ * Most directives reach lines: the line below a next-line directive
13
+ * (`@ts-expect-error`, `eslint-disable-next-line`, ...), the lines a line
14
+ * directive (`eslint-disable-line`, `nosemgrep` after code, ...) stands on,
15
+ * the lines a coverage hint counts. Those lines are shielded: emptied, one
16
+ * stays as an empty line, and none is joined to another — the removal edits
17
+ * see to both (see ShieldedLines), so the comments on them go all the same.
18
+ * Only a comment-only JSX container that would join such a line keeps its
19
+ * comments, as a line break in its place would change what the element
20
+ * renders. To the tools that only a line feed ends a line for (oxlint,
21
+ * Semgrep, ast-grep, c8, Node's test runner), a directive reaches rows that
22
+ * can run over several of those lines, and their lines are shielded as well.
23
+ *
24
+ * Other directives are read with the comments around them, and there a
25
+ * comment has to stay:
26
+ *
27
+ * - below a tsc suppression, the first line each compiler cannot step over
28
+ * in front of the code (see tscReach);
29
+ * - between a directive that only counts as the last comment before its
30
+ * target (`@deno-types`, a fall-through comment, ...), or a coverage hint
31
+ * that ast-v8-to-istanbul only applies to the node right after it, and
32
+ * that target, one comment (see Gap);
33
+ * - in front of a directive that reaches the lines below only where it
34
+ * opens its row, one comment that keeps it from opening it, where those
35
+ * lines hold code (see Front);
36
+ * - next to a suppression a formatter applies by where it stands on its
37
+ * line, a comment whose removal would change that: one spanning lines that
38
+ * would leave a line break next to it (see PLACED_BY_LINE), or one right
39
+ * beside it that keeps it from an end of its line (see
40
+ * PLACED_BY_NEIGHBOURS);
41
+ * - a JSX comment container right after a directive in a container
42
+ * (`{/* prettier-ignore *​/}`, which applies to the next sibling);
43
+ * - the last JSDoc comment of a node in JavaScript, where an earlier one
44
+ * that stays holds tags it keeps off the node;
45
+ * - what an ast-grep suppression is keyed to (see astGrepReach).
46
+ *
47
+ * Each directive a comment carries shields what it reaches, whichever one
48
+ * names the comment. Runs to a fixpoint because a comment kept here can
49
+ * itself be a directive (when directives are being removed selectively).
50
+ */
51
+ export function shieldDirectives(source, removed, kept, skipped, context) {
52
+ const lineOffsets = lineStartOffsets(source);
53
+ const totalLines = lineOffsets.length;
54
+ const shieldedLines = new Set();
55
+ const blockingLines = new Set();
56
+ const gaps = [];
57
+ const fronts = [];
58
+ const siblingTargets = new Set();
59
+ /** The suppressions that stay which a formatter places by their line (see PLACED_BY_LINE). */
60
+ const placed = new Set();
61
+ /** Those of them one places by what stands right next to them (see PLACED_BY_NEIGHBOURS). */
62
+ const placedByNeighbours = new Set();
63
+ const rowTails = [];
64
+ const shadows = new Set();
65
+ const astGrepReaches = [];
66
+ const processed = new Set();
67
+ // The hints c8 and Node find in the text, until the comment holding one is known to stay.
68
+ let pendingHints = source.includes("ignore next") ? textHints(source) : [];
69
+ // Where a comment tsc reads a suppression from ends: tsc stops there on its
70
+ // way up from a diagnostic, as it does at a line it cannot step over.
71
+ const suppressions = new Map();
72
+ for (const [comment, names] of context.directives) {
73
+ if (names.some((name) => TSC_SUPPRESSIONS.has(name))) {
74
+ suppressions.set(comment.endLine, [...(suppressions.get(comment.endLine) ?? []), comment]);
75
+ }
76
+ }
77
+ let stillRemoved = removed;
78
+ const removing = new Set(removed);
79
+ let units;
80
+ const currentUnits = () => (units ??= removalUnits(stillRemoved, context.containerOf));
81
+ let rows;
82
+ const rowOffsets = () => (rows ??= rowStartOffsets(source));
83
+ /** The (1-based) line holding the offset. */
84
+ const lineOf = (offset) => lineIndexAt(lineOffsets, offset) + 1;
85
+ /** Where the comment stands among the source's. */
86
+ const indexOf = (comment) => firstIndexAtOrAfter(context.comments, comment.start, (other) => other.start);
87
+ /** The comment holding the offset, where it is still to be removed. */
88
+ const removalAt = (offset) => {
89
+ const holder = rangeAt(context.comments, offset);
90
+ return holder !== undefined && removing.has(holder) ? holder : undefined;
91
+ };
92
+ /** The given (1-based) line, which the shields only name when the source has it, and the units on it. */
93
+ const unitsOnLine = (line) => {
94
+ const start = lineOffsets[line - 1];
95
+ const end = lineOffsets[line] ?? source.length;
96
+ return { start, end, units: currentUnits().filter((unit) => unit.start < end && unit.end > start) };
97
+ };
98
+ /** Whether the lines (1-based, inclusive, each one the source has) hold nothing but whitespace and comments. */
99
+ const holdNoCode = (from, to) => {
100
+ const end = lineOffsets[to] ?? source.length;
101
+ for (let index = lineOffsets[from - 1]; index < end; index += 1) {
102
+ const comment = rangeAt(context.comments, index);
103
+ if (comment !== undefined)
104
+ index = comment.end - 1;
105
+ else if (!isBlank(source[index]))
106
+ return false;
107
+ }
108
+ return true;
109
+ };
110
+ let added = false;
111
+ const shieldLines = (from, to) => {
112
+ for (let line = from; line <= Math.min(to, totalLines); line += 1) {
113
+ if (shieldedLines.has(line))
114
+ continue;
115
+ shieldedLines.add(line);
116
+ added = true;
117
+ }
118
+ };
119
+ /** Shields the lines of the rows (0-based, inclusive) that only a line feed ends. */
120
+ const shieldRows = (from, to) => {
121
+ const offsets = rowOffsets();
122
+ const start = offsets[from];
123
+ if (start !== undefined)
124
+ shieldLines(lineOf(start), lineOf((offsets[to + 1] ?? source.length) - 1));
125
+ };
126
+ /** Collects what one of the directives the comment carries reaches. */
127
+ const shieldReach = (comment, directive) => {
128
+ if (PLACED_BY_LINE.has(directive)) {
129
+ placed.add(comment);
130
+ added = true;
131
+ }
132
+ if (PLACED_BY_NEIGHBOURS.has(directive)) {
133
+ placedByNeighbours.add(comment);
134
+ // oxfmt takes the last comment in front of the `;` that ends a statement
135
+ // for the statement's suppression: the comments from this one up to
136
+ // such a `;` keep it from being that one, and the last of them stays.
137
+ const codeStart = codeStartAfter(source, comment.end, context.skippable);
138
+ if (codeStart > comment.end && source[codeStart] === ";") {
139
+ gaps.push({ start: comment.end, end: codeStart, stays: "last", line: comment.endLine });
140
+ added = true;
141
+ }
142
+ }
143
+ const lastComment = isLastCommentDirective(comment, directive);
144
+ const cast = CAST_DIRECTIVES.has(directive) && context.casts.has(comment);
145
+ if (lastComment || cast || (NEXT_TOKEN_DIRECTIVES.has(directive) && hintsNextNode(comment.text))) {
146
+ const codeStart = codeStartAfter(source, comment.end, context.skippable);
147
+ if (codeStart > comment.end && codeStart < source.length) {
148
+ gaps.push({
149
+ start: comment.end,
150
+ end: codeStart,
151
+ stays: lastComment || cast ? "last" : "first",
152
+ line: comment.endLine,
153
+ });
154
+ added = true;
155
+ }
156
+ if (lastComment)
157
+ return;
158
+ }
159
+ if (TSC_SUPPRESSIONS.has(directive)) {
160
+ const reach = tscReach(source, comment, lineOffsets, context.skippable, (line) => suppressions.get(line)?.map((suppression) => removing.has(suppression)));
161
+ for (const line of reach.blocking) {
162
+ if (blockingLines.has(line))
163
+ continue;
164
+ blockingLines.add(line);
165
+ added = true;
166
+ }
167
+ if (reach.target !== undefined)
168
+ shieldLines(reach.target, reach.target);
169
+ }
170
+ // The row the comment ends on, for the tools that only a line feed ends
171
+ // a line for (oxlint, Semgrep, tree-sitter, c8): a lone CR, U+2028 or
172
+ // U+2029 — a line break to tsc and ESLint — ends no row, so a row can run
173
+ // over several of the lines counted here.
174
+ const endRow = lineIndexAt(rowOffsets(), comment.end - 1);
175
+ // A line directive covers the lines it stands on, which no removal may
176
+ // join to another (see joiningUnits): its rows, to those tools.
177
+ if (coversOwnLine(directive))
178
+ shieldRows(lineIndexAt(rowOffsets(), comment.start), endRow);
179
+ if (!isNextLineDirective(directive))
180
+ return;
181
+ // In JSX, such a directive in braces applies to the sibling after it,
182
+ // whatever line that is on (prettier leaves the element after
183
+ // `{/* prettier-ignore */}` as is): a comment-only container standing
184
+ // between them has to stay. Range and file pragmas target no sibling.
185
+ const holder = context.containerOf.get(comment);
186
+ if (holder?.next !== undefined && !siblingTargets.has(holder.next)) {
187
+ siblingTargets.add(holder.next);
188
+ added = true;
189
+ }
190
+ // A trailing formatter or scanner suppression (`a = [1]; // oxfmt-ignore`,
191
+ // `secret(); // skipcq`) targets what it trails, not the line below it.
192
+ // In JSX, the container holding the comment is what has to stand on
193
+ // lines of its own.
194
+ if (TRAILING_TARGETS_OWN_LINE.has(directive) && !occupiesWholeLines(source, holder ?? comment))
195
+ return;
196
+ const below = rowOffsets()[endRow + 1];
197
+ if (directive === "nosemgrep") {
198
+ // Semgrep reads the rule ids of a `nosemgrep:` off the rest of the row,
199
+ // which runs on where a lone CR or U+2028 ends the comment's line: what
200
+ // stands there is part of the ids it reads.
201
+ const nextLine = lineOffsets[comment.endLine] ?? source.length;
202
+ if (nextLine < (below ?? source.length) && SEMGREP_RULE_IDS.test(comment.text)) {
203
+ rowTails.push({ start: nextLine, end: below ?? source.length });
204
+ added = true;
205
+ }
206
+ // Its reach is a matter of what precedes the marker on its row.
207
+ if (below !== undefined) {
208
+ const rowStart = rowOffsets()[endRow];
209
+ const ownRow = comment.text.slice(comment.text.lastIndexOf("\n") + 1);
210
+ fronts.push({
211
+ rowStart,
212
+ at: Math.max(rowStart, comment.start),
213
+ reaches: (prefix) => SEMGREP_PREVIOUS_LINE.test(prefix + ownRow),
214
+ from: lineOf(below),
215
+ to: lineOf((rowOffsets()[endRow + 2] ?? source.length) - 1),
216
+ });
217
+ added = true;
218
+ }
219
+ return;
220
+ }
221
+ // The line below the directive, and the row below it. oxlint covers the
222
+ // rest of the row a next-line comment ends on as well, up to the end of
223
+ // the row after it (`split_inclusive('\n')` and `lines()` in its
224
+ // `disable_directives.rs`); on the file's last row it covers the rest of
225
+ // the file, which no removal changes.
226
+ shieldLines(comment.endLine + 1, comment.endLine + 1);
227
+ if (below !== undefined) {
228
+ shieldLines(OXLINT_NEXT_LINE.has(directive) ? comment.endLine + 1 : lineOf(below), lineOf((rowOffsets()[endRow + 2] ?? source.length) - 1));
229
+ }
230
+ if (COUNTED_NEXT_LINE.has(directive)) {
231
+ // monocart counts the lines below the comment's last (see monocartLines).
232
+ const trailing = source.slice(comment.end, lineOffsets[comment.endLine] ?? source.length);
233
+ const counted = monocartLines(comment.kind, comment.text, trailing);
234
+ if (counted !== undefined)
235
+ shieldLines(comment.endLine + 1, comment.endLine + counted);
236
+ }
237
+ };
238
+ const collectShields = () => {
239
+ added = false;
240
+ for (const comment of [...kept, ...skipped]) {
241
+ if (processed.has(comment))
242
+ continue;
243
+ processed.add(comment);
244
+ const shadow = context.shadows.get(comment);
245
+ if (shadow !== undefined)
246
+ shadows.add(shadow);
247
+ if (comment.directive === undefined)
248
+ continue;
249
+ if (carriesAstGrepSuppression(comment.text)) {
250
+ const reach = astGrepReach(source, rowOffsets(), comment, context.preceding.get(comment));
251
+ astGrepReaches.push(reach);
252
+ if (reach.nextRow !== undefined && reach.nextRow.end > reach.nextRow.start) {
253
+ shieldLines(lineOf(reach.nextRow.start), lineOf(reach.nextRow.end - 1));
254
+ }
255
+ added = true;
256
+ }
257
+ for (const directive of context.directives.get(comment))
258
+ shieldReach(comment, directive);
259
+ }
260
+ // c8 ignores the row holding a hint, wherever on it, and from a hint that
261
+ // opens its row the rows below it that the hint counts; Node's test
262
+ // runner ignores the rows below it wherever it stands. A hint in a
263
+ // comment that goes, goes with it.
264
+ pendingHints = pendingHints.filter((hint) => {
265
+ if (removalAt(hint.offset) !== undefined)
266
+ return true;
267
+ const offsets = rowOffsets();
268
+ const row = lineIndexAt(offsets, hint.offset);
269
+ shieldRows(row, row);
270
+ if (hint.nodeRows > 0)
271
+ shieldRows(row + 1, row + hint.nodeRows);
272
+ const below = offsets[row + 1];
273
+ if (below !== undefined) {
274
+ fronts.push({
275
+ rowStart: offsets[row],
276
+ at: hint.offset,
277
+ reaches: opensRow,
278
+ from: lineOf(below),
279
+ to: lineOf((offsets[row + hint.rows + 1] ?? source.length) - 1),
280
+ });
281
+ added = true;
282
+ }
283
+ return false;
284
+ });
285
+ return added;
286
+ };
287
+ /** Takes those of the comments that are still being removed out of the removal and keeps them. */
288
+ const protect = (group) => {
289
+ const staying = group.filter((comment) => removing.has(comment));
290
+ if (staying.length === 0)
291
+ return;
292
+ for (const comment of staying)
293
+ removing.delete(comment);
294
+ stillRemoved = stillRemoved.filter((comment) => removing.has(comment));
295
+ kept.push(...staying);
296
+ units = undefined;
297
+ };
298
+ /**
299
+ * Shields what a directive reaches below its row where it opens the row,
300
+ * and sees to it that the removal does not make it open one: with the
301
+ * comments in front of it gone, the directive would newly reach those
302
+ * lines. Where they hold no code, that changes nothing as long as they
303
+ * stay lines, so they are shielded as well; where they do, the comment in
304
+ * front that keeps the directive from opening its row stays.
305
+ */
306
+ const settleFront = (front) => {
307
+ const prefix = source.slice(front.rowStart, front.at);
308
+ if (!front.reaches(prefix)) {
309
+ const inFront = currentUnits().filter((unit) => unit.start < front.at && unit.end > front.rowStart);
310
+ /** The prefix once the units are deleted, all but `staying`. */
311
+ const without = (staying) => {
312
+ let text = "";
313
+ let cursor = front.rowStart;
314
+ for (const unit of inFront) {
315
+ if (unit === staying)
316
+ continue;
317
+ text += source.slice(cursor, Math.max(cursor, unit.start));
318
+ cursor = Math.min(front.at, unit.end);
319
+ }
320
+ return text + source.slice(cursor, front.at);
321
+ };
322
+ if (!front.reaches(without()))
323
+ return;
324
+ if (!holdNoCode(front.from, front.to)) {
325
+ protect(inFront.findLast((unit) => !front.reaches(without(unit))).comments);
326
+ return;
327
+ }
328
+ }
329
+ shieldLines(front.from, front.to);
330
+ };
331
+ /** Keeps the comment a gap needs, unless one that stays already serves. */
332
+ const settleGap = (gap) => {
333
+ const within = [];
334
+ for (let index = firstIndexAtOrAfter(context.comments, gap.start, (comment) => comment.start); (context.comments[index]?.start ?? gap.end) < gap.end; index += 1) {
335
+ within.push(context.comments[index]);
336
+ }
337
+ const first = within[0];
338
+ if (gap.stays === "last" || first === undefined) {
339
+ protect(within.slice(-1));
340
+ }
341
+ else {
342
+ // Any comment keeps ast-v8-to-istanbul's hint without a target. One on
343
+ // the hint's own line also keeps monocart from counting a line below
344
+ // the hint (see monocartLines), so where the first stands there, only a
345
+ // comment of that line serves.
346
+ const serving = first.line === gap.line ? within.filter((comment) => comment.line === gap.line) : within;
347
+ if (serving.every((comment) => removing.has(comment)))
348
+ protect([first]);
349
+ }
350
+ };
351
+ /**
352
+ * Whether something that stays shares a line with the comment, in front of
353
+ * it where `step` is -1 and behind it where it is 1. A removal on the way
354
+ * leaves nothing: what stands past a single-line one moves up to the
355
+ * comment, and one that spans lines, or runs to the end of its line, cuts
356
+ * the line off there.
357
+ */
358
+ const sharesLineWithWhatStays = (comment, step) => {
359
+ for (let index = step === 1 ? comment.end : comment.start - 1; index >= 0 && index < source.length && !LINE_TERMINATOR.test(source[index]); index += step) {
360
+ const holder = removalAt(index);
361
+ if (holder !== undefined) {
362
+ if (holder.kind === "line" || LINE_TERMINATOR.test(holder.text))
363
+ return false;
364
+ index = step === 1 ? holder.end - 1 : holder.start;
365
+ }
366
+ else if (!isBlank(source[index])) {
367
+ return true;
368
+ }
369
+ }
370
+ return false;
371
+ };
372
+ /**
373
+ * The removals in the run of comments around the given one (see
374
+ * PLACED_BY_LINE) that would leave a line break in their place: those
375
+ * spanning lines, with something that stays in front of them on their
376
+ * first line and something behind them on their last.
377
+ */
378
+ const lineBreakLeavers = (comment) => {
379
+ const glued = (index) => SAME_LINE_GAP.test(source.slice(context.comments[index].end, context.comments[index + 1].start));
380
+ const at = indexOf(comment);
381
+ let first = at;
382
+ while (first > 0 && glued(first - 1))
383
+ first -= 1;
384
+ let last = at;
385
+ while (last + 1 < context.comments.length && glued(last))
386
+ last += 1;
387
+ return context.comments
388
+ .slice(first, last + 1)
389
+ .filter((other) => removing.has(other) &&
390
+ LINE_TERMINATOR.test(other.text) &&
391
+ !closesItsLine(source, other) &&
392
+ sharesLineWithWhatStays(other, -1));
393
+ };
394
+ /**
395
+ * The removals right next to the given comment on its line (see
396
+ * PLACED_BY_NEIGHBOURS) that would leave it the first thing on that line,
397
+ * or the last, where it is not.
398
+ */
399
+ const edgeMakers = (comment) => {
400
+ const at = indexOf(comment);
401
+ return [-1, 1].flatMap((step) => {
402
+ const neighbour = context.comments[at + step];
403
+ if (neighbour === undefined || !removing.has(neighbour))
404
+ return [];
405
+ const gap = step === 1 ? source.slice(comment.end, neighbour.start) : source.slice(neighbour.end, comment.start);
406
+ const onItsLine = isBlank(gap) && !LINE_TERMINATOR.test(gap);
407
+ return onItsLine && !sharesLineWithWhatStays(comment, step) ? [neighbour] : [];
408
+ });
409
+ };
410
+ /** Protects what the shields collected so far hold in place; true when that kept anything. */
411
+ const protectShields = () => {
412
+ const removingBefore = stillRemoved.length;
413
+ for (const front of fronts)
414
+ settleFront(front);
415
+ // A comment that would join a shielded line to another leaves its line
416
+ // breaks behind; a container's braces have none to leave without
417
+ // changing what the element renders, so they stay.
418
+ for (const line of currentUnits().some((unit) => unit.braces) ? shieldedLines : []) {
419
+ for (const unit of joiningUnits(source, unitsOnLine(line))) {
420
+ if (unit.braces)
421
+ protect(unit.comments);
422
+ }
423
+ }
424
+ for (const line of blockingLines)
425
+ protect(lineOpeningGroup(source, unitsOnLine(line)));
426
+ for (const gap of gaps)
427
+ settleGap(gap);
428
+ protect([...shadows]);
429
+ for (const target of siblingTargets)
430
+ protect(target.comments);
431
+ for (const tail of rowTails) {
432
+ protect(commentsOf(currentUnits().filter((unit) => unit.start >= tail.start && unit.start < tail.end)));
433
+ }
434
+ for (const reach of astGrepReaches)
435
+ protect(commentsOf(currentUnits().filter((unit) => reach.holds(unit))));
436
+ // Last, and until nothing more stays: what a removal would leave next to
437
+ // a suppression depends on what else stays on its line.
438
+ let settling;
439
+ do {
440
+ settling = stillRemoved.length;
441
+ for (const comment of placed) {
442
+ protect(lineBreakLeavers(comment));
443
+ if (placedByNeighbours.has(comment))
444
+ protect(edgeMakers(comment));
445
+ }
446
+ } while (stillRemoved.length < settling);
447
+ return stillRemoved.length < removingBefore;
448
+ };
449
+ collectShields();
450
+ while (protectShields()) {
451
+ if (!collectShields())
452
+ break;
453
+ }
454
+ if (stillRemoved.length !== removed.length) {
455
+ kept.sort(byStart);
456
+ }
457
+ return { removed: stillRemoved, lines: shieldedLines };
458
+ }
459
+ /**
460
+ * Offset of the first character at or after `from` that is neither
461
+ * whitespace nor inside one of the (sorted, non-overlapping) ranges, or the
462
+ * source length when only ranges follow. `from` lies past the start of at
463
+ * least one range (the directive the search is for); when the closest of
464
+ * them runs past `from` — a block comment opened on the directive's line —
465
+ * the search resumes at its end.
466
+ */
467
+ function codeStartAfter(source, from, ranges) {
468
+ let next = firstIndexAtOrAfter(ranges, from, (range) => range.start);
469
+ let index = Math.max(from, ranges[next - 1].end);
470
+ while (index < source.length) {
471
+ const range = ranges[next];
472
+ if (range !== undefined && range.start === index) {
473
+ index = range.end;
474
+ next += 1;
475
+ }
476
+ else if (isBlank(source[index])) {
477
+ index += 1;
478
+ }
479
+ else {
480
+ return index;
481
+ }
482
+ }
483
+ return source.length;
484
+ }
485
+ /**
486
+ * What a tsc suppression needs left in place below it. Looking for the
487
+ * suppression a diagnostic falls under, a compiler goes up from the
488
+ * diagnostic's line over the lines it reads as blank or as a `//` comment
489
+ * (see TSC_PASSABLE_LINES) and takes the first suppression it meets. So a
490
+ * suppression applies to the first line below it that the compiler cannot
491
+ * step over:
492
+ *
493
+ * - where that is the line the code below starts on, the line is the
494
+ * suppression's `target`, which no removal may pull more code onto;
495
+ * - where a line in between stops the compiler first — one opening with a
496
+ * block comment, say — the suppression has no target for that compiler,
497
+ * and the line is `blocking`: deleting it would let the suppression reach
498
+ * the code instead;
499
+ * - where another suppression ends on a line in between, that one takes the
500
+ * diagnostics from below, and this one reaches nothing past it. The line
501
+ * is blocking while that suppression is being removed (`suppressions`
502
+ * tells, for a line, whether each suppression ending on it is).
503
+ *
504
+ * The two compilers can stop at different lines: a line holding only a
505
+ * vertical tab stops tsc 7, while tsc 6 searches on to the next line it
506
+ * cannot pass.
507
+ */
508
+ function tscReach(source, comment, lineOffsets, ranges, suppressions) {
509
+ // A suppression applies from the line below it on, so code sharing its line
510
+ // (`/* @ts-ignore */ foo();`) does not end the search.
511
+ const codeStart = codeStartAfter(source, lineOffsets[comment.endLine] ?? source.length, ranges);
512
+ if (codeStart >= source.length)
513
+ return { blocking: [], target: undefined };
514
+ const codeLine = lineIndexAt(lineOffsets, codeStart) + 1;
515
+ const blocking = [];
516
+ let target;
517
+ for (const passable of TSC_PASSABLE_LINES) {
518
+ let line = comment.endLine + 1;
519
+ for (; line < codeLine; line += 1) {
520
+ const removing = suppressions(line);
521
+ if (removing === undefined && passable.test(source.slice(lineOffsets[line - 1], lineOffsets[line])))
522
+ continue;
523
+ // A suppression that stays stops the compiler whatever is removed.
524
+ if (removing?.includes(false) !== true)
525
+ blocking.push(line);
526
+ break;
527
+ }
528
+ if (line === codeLine)
529
+ target = codeLine;
530
+ }
531
+ return { blocking, target };
532
+ }
533
+ /**
534
+ * The removals on the given line when one of them opens it (holds its first
535
+ * non-whitespace character), so that deleting them would change how the
536
+ * line starts. None when something that survives opens the line instead, or
537
+ * nothing on it is to be removed.
538
+ */
539
+ function lineOpeningGroup(source, line) {
540
+ let first = line.start;
541
+ while (first < line.end && isBlank(source[first]))
542
+ first += 1;
543
+ return line.units.some((unit) => unit.start <= first && first < unit.end) ? commentsOf(line.units) : [];
544
+ }
545
+ /**
546
+ * The removal units that would join the given line to another: they reach
547
+ * past one of its ends, with something other than whitespace beyond them on
548
+ * the line they run into. Deleting such a comment takes its line breaks
549
+ * along, so what stands beyond it can land on the line, or what stands on
550
+ * the line move off it, and a directive covering the line would cover other
551
+ * code — unless line breaks of its own take its place (see applyEdits).
552
+ */
553
+ function joiningUnits(source, line) {
554
+ return line.units.filter((unit) => (unit.end > line.end && !closesItsLine(source, unit)) || (unit.start < line.start && !opensItsLine(source, unit)));
555
+ }
556
+ // The next-line directives oxlint reads.
557
+ const OXLINT_NEXT_LINE = new Set(["eslint-disable-next-line", "oxlint-disable-next-line"]);
558
+ /**
559
+ * Whether the directive covers the lines it stands on: the `-line` forms of
560
+ * the suppressions (`eslint-disable-line`, `tslint:disable-line`, ...), the
561
+ * ones that cover the line holding them (see OWN_LINE_DIRECTIVES), and the
562
+ * `ignore next` hints c8 and monocart count lines for (see
563
+ * COUNTED_NEXT_LINE): they ignore the line holding one, from the hint on for
564
+ * monocart, along with the lines below it.
565
+ */
566
+ function coversOwnLine(name) {
567
+ return ((name.endsWith("-line") && !name.endsWith("-next-line")) ||
568
+ OWN_LINE_DIRECTIVES.has(name) ||
569
+ COUNTED_NEXT_LINE.has(name));
570
+ }
571
+ // Suppressions that apply to the line holding them: Semgrep's to findings
572
+ // that start on it, CodeQL's `lgtm` to its alerts up to the comment,
573
+ // DeepSource's, SonarQube's, gitleaks', TruffleHog's and detect-secrets' to
574
+ // the line, and codespell's to its words.
575
+ const OWN_LINE_DIRECTIVES = new Set([
576
+ "nosemgrep",
577
+ "lgtm",
578
+ "skipcq",
579
+ "NOSONAR",
580
+ "gitleaks:allow",
581
+ "trufflehog:ignore",
582
+ "pragma-allowlist-secret",
583
+ "codespell:ignore",
584
+ ]);
585
+ // Semgrep applies a `nosemgrep` to the line below where nothing but
586
+ // non-alphanumerics precede it on its line (`nosem_previous_line_re` in its
587
+ // Nosemgrep.ml): `// nosemgrep: rule-id` and `}); // nosemgrep` cover the next
588
+ // line, `// TODO nosemgrep` and `foo(); // nosemgrep` only their own.
589
+ const SEMGREP_PREVIOUS_LINE = /^[^a-zA-Z0-9]* *nosem(?:grep)?/i;
590
+ // A `nosemgrep` that names the rules it is for.
591
+ const SEMGREP_RULE_IDS = /nosem(?:grep)?[:=]/i;
592
+ // These suppressions only apply to the following node/line when they stand on
593
+ // their own line — trailing after code they target (at most) their own line.
594
+ // Other next-line directives (`@ts-ignore`, `no-dd-sa`, ...) target the next
595
+ // line even when they trail code.
596
+ const TRAILING_TARGETS_OWN_LINE = new Set([
597
+ "prettier-ignore",
598
+ "oxfmt-ignore",
599
+ "dprint-ignore",
600
+ "lgtm",
601
+ "codeql",
602
+ "skipcq",
603
+ ]);
604
+ // The suppressions a formatter applies by where the comment stands on its
605
+ // line. Prettier attaches a comment that ends its line to the code in front
606
+ // of it, where some stands on that line, and one that opens its line to the
607
+ // code after it (`isOwnLineComment` and `isEndOfLineComment` in its
608
+ // comments/attach.js), and a `prettier-ignore` attached that way keeps the
609
+ // statement it trails, or the node it leads, as written; oxfmt and Biome
610
+ // place their suppressions the same way. All three take the comments that
611
+ // only blanks hold apart as one run, and look for the line break in front of
612
+ // the run and behind it, so a line break inside a comment of the run counts
613
+ // for nothing: in `a( 1,2 ); /* note\n*/ // prettier-ignore` the
614
+ // suppression trails the call. Deleting the note for a line break would put
615
+ // the suppression on a line of its own, where it applies to the statement
616
+ // below instead, so a comment of the run that would leave a line break
617
+ // stays. dprint goes by the comments in front of a node wherever they stand,
618
+ // and is not among them. Checked against Prettier 3.8.4 and 3.10.1, oxfmt
619
+ // 0.79.0 and Biome 2.6.8; Rome placed its suppressions as Biome does.
620
+ const PLACED_BY_LINE = new Set(["prettier-ignore", "oxfmt-ignore", "biome-ignore", "rome-ignore"]);
621
+ // What holds two comments of one run apart: blanks, and no line feed.
622
+ const SAME_LINE_GAP = /^[^\S\n]*$/;
623
+ // oxfmt, which honours `prettier-ignore` as well, goes by what stands right
624
+ // next to the comment instead: oxc's parser notes for every comment whether a
625
+ // line break precedes it and whether one follows it, another comment on its
626
+ // line in between included. So a suppression has to stay the first thing on
627
+ // its line, or the last, exactly where it is one, and a comment next to it
628
+ // whose removal would make it one stays: after `break` on the line above,
629
+ // `/* note */ /* oxfmt-ignore */ ;` ignores nothing, and `/* oxfmt-ignore */ ;`
630
+ // alone on that line the statement below it. oxfmt also suppresses a
631
+ // statement whose last comment in front of its `;` is a suppression trailing
632
+ // the code (`is_node_suppressed` in its formatter/comments.rs, for the `;`
633
+ // that semicolon-less code opens the next line with), so the last comment
634
+ // between a suppression and such a `;` stays as well: below
635
+ // `import { a,b } from "m" // oxfmt-ignore`, a comment in front of the `;`
636
+ // on the next line keeps the import formatted.
637
+ const PLACED_BY_NEIGHBOURS = new Set(["prettier-ignore", "oxfmt-ignore"]);
638
+ // The suppressions tsc looks past blank and `//` lines for (see tscReach).
639
+ // They stay next-line directives as well: Flow, which honours them in
640
+ // TypeScript files, applies them to the very next line.
641
+ const TSC_SUPPRESSIONS = new Set(["@ts-ignore", "@ts-expect-error"]);
642
+ // The lines each compiler steps over on its way up from a diagnostic to a
643
+ // suppression, matched against the whole line, line break included. tsc 6
644
+ // trims the line and accepts nothing or a `//` comment; tsc 7 accepts only
645
+ // spaces and tabs before the line break or the `//`.
646
+ const TSC_PASSABLE_LINES = [/^\s*(?:\/\/|$)/, /^[ \t]*(?:[\r\n]|\/\/)/];
647
+ // Directives that only count while no other comment sits between them and
648
+ // their target: deno_graph reads `@deno-types`/`@ts-types` from the last
649
+ // comment before an import, ts-prune and graphql-tag-pluck from the closest
650
+ // leading comment, and ESLint's no-fallthrough and default-case from the last
651
+ // comment before the next case or the closing brace. JetBrains IDEs take a
652
+ // `noinspection` suppression from the comment right in front of a statement,
653
+ // past whitespace alone (`getStatementToolSuppressedIn` in the platform's
654
+ // SuppressionUtil), and a `language=` injection from the comment in front of
655
+ // the literal. Deleting every comment in that gap would newly activate such a
656
+ // directive, so the last one of them stays, trailing comments in front of
657
+ // the code included. With no code left there is nothing to target, and the
658
+ // switch-clause comments are only detected in front of the `case`, `default`
659
+ // or `}` their rules read them before.
660
+ const LAST_COMMENT_DIRECTIVES = new Set([
661
+ "@deno-types",
662
+ "@ts-types",
663
+ "ts-prune-ignore-next",
664
+ "GraphQL",
665
+ "fallthrough",
666
+ "no-default",
667
+ "noinspection",
668
+ "language-injection",
669
+ ]);
670
+ function isLastCommentDirective(comment, directive) {
671
+ // `//file:noinspection` suppresses for the whole file, wherever the code is.
672
+ return LAST_COMMENT_DIRECTIVES.has(directive) && !(directive === "noinspection" && /^\/\/file:/.test(comment.text));
673
+ }
674
+ // The JSDoc type casts prettier keeps the parentheses of (see the rule in
675
+ // directives.ts): it does while nothing but whitespace stands between the
676
+ // comment and the parenthesis (`text.slice(previousCommentEnd, start).trim()`
677
+ // in its parse/postprocess), under its Babel, acorn and meriyah parsers. A
678
+ // comment in between leaves the cast out of effect, and prettier drops
679
+ // redundant parentheses there, so the last comment of that gap stays.
680
+ const CAST_DIRECTIVES = new Set(["@type", "@satisfies"]);
681
+ // The coverage hints ast-v8-to-istanbul, Vitest's v8 provider, applies to the
682
+ // node that starts at the very token after them, where it reads them (see
683
+ // hintsNextNode): with another comment in between, the hint has no target,
684
+ // and deleting every comment there would bring it into effect. One comment of
685
+ // the gap up to the code stays, on top of the lines below the hint, which c8,
686
+ // Node and monocart count.
687
+ const NEXT_TOKEN_DIRECTIVES = new Set([
688
+ "istanbul-ignore-next",
689
+ "istanbul-ignore-if",
690
+ "istanbul-ignore-else",
691
+ "c8-ignore-next",
692
+ "c8-ignore-if",
693
+ "c8-ignore-else",
694
+ "v8-ignore-next",
695
+ "v8-ignore-if",
696
+ "v8-ignore-else",
697
+ "node:coverage-ignore",
698
+ "node:coverage-ignore-if",
699
+ "node:coverage-ignore-else",
700
+ ]);
701
+ // Directives that target the line or node directly below them. File- and
702
+ // range-scoped pragmas (`istanbul-ignore-file`, `c8-ignore-start`, ...) are
703
+ // absent: they do not target the following line, so they never shield it.
704
+ // They go by their names here: Vitest's v8 provider reads a range hint
705
+ // spelled out on any line of this file, and would drop the rest of the file
706
+ // from this project's coverage. So are the coverage hints no tool counts
707
+ // lines for — the `istanbul` ones and the `if` and `else` forms, which
708
+ // istanbul and ast-v8-to-istanbul alone read, and apply to a node wherever
709
+ // its line is (see NEXT_TOKEN_DIRECTIVES).
710
+ const NEXT_LINE_DIRECTIVES = new Set([
711
+ "@ts-ignore",
712
+ "@ts-expect-error",
713
+ "biome-ignore",
714
+ "deno-lint-ignore",
715
+ "deno-fmt-ignore",
716
+ "deno-coverage-ignore",
717
+ "prettier-ignore",
718
+ "oxfmt-ignore",
719
+ "dprint-ignore",
720
+ "rome-ignore",
721
+ "c8-ignore-next",
722
+ "v8-ignore-next",
723
+ "node:coverage-ignore",
724
+ // Directives that hang off the node or line directly below them: the line
725
+ // below stays a line, so that no code moves up under them.
726
+ "million-ignore",
727
+ "@million-skip",
728
+ "@million-jsx-skip",
729
+ "deepcode-ignore",
730
+ "skipcq",
731
+ "lgtm",
732
+ "codeql",
733
+ "nosemgrep",
734
+ "no-dd-sa",
735
+ "datadog-disable",
736
+ "@next-codemod-error",
737
+ "@next-codemod-ignore",
738
+ "$FlowFixMe",
739
+ "$FlowExpectedError",
740
+ "$FlowIssue",
741
+ "$FlowIgnore",
742
+ "pragma-allowlist-nextline-secret",
743
+ "cspell:disable-next",
744
+ "HTML",
745
+ ]);
746
+ function isNextLineDirective(name) {
747
+ return name.endsWith("-next-line") || NEXT_LINE_DIRECTIVES.has(name);
748
+ }
749
+ // The coverage pragmas a line count after `ignore next` applies to: c8
750
+ // (v8-to-istanbul), Node's test-runner coverage and monocart-coverage-reports
751
+ // count lines, each in its own way (see coverage.ts). istanbul and
752
+ // ast-v8-to-istanbul, Vitest's providers, apply the hint to the next node
753
+ // whatever count follows, so `istanbul ignore next 3` covers one line.
754
+ // Everything else — `@ts-expect-error`, `eslint-disable-next-line` and
755
+ // friends — covers exactly one line too, no matter what prose like "we
756
+ // ignore next 3 legacy calls" appears in the reason text.
757
+ const COUNTED_NEXT_LINE = new Set(["c8-ignore-next", "v8-ignore-next", "node:coverage-ignore"]);
758
+ //# sourceMappingURL=shields.js.map