@kongyo2/ts-comment-scanner 1.20.0 → 1.22.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 (78) hide show
  1. package/README.md +240 -52
  2. package/dist/args.d.ts.map +1 -1
  3. package/dist/args.js +23 -19
  4. package/dist/args.js.map +1 -1
  5. package/dist/astgrep.d.ts +5 -3
  6. package/dist/astgrep.d.ts.map +1 -1
  7. package/dist/astgrep.js +10 -12
  8. package/dist/astgrep.js.map +1 -1
  9. package/dist/containers.d.ts +48 -0
  10. package/dist/containers.d.ts.map +1 -0
  11. package/dist/containers.js +82 -0
  12. package/dist/containers.js.map +1 -0
  13. package/dist/coverage.d.ts +45 -0
  14. package/dist/coverage.d.ts.map +1 -0
  15. package/dist/coverage.js +92 -0
  16. package/dist/coverage.js.map +1 -0
  17. package/dist/directives.d.ts +21 -3
  18. package/dist/directives.d.ts.map +1 -1
  19. package/dist/directives.js +31 -23
  20. package/dist/directives.js.map +1 -1
  21. package/dist/files.d.ts +7 -3
  22. package/dist/files.d.ts.map +1 -1
  23. package/dist/files.js +129 -82
  24. package/dist/files.js.map +1 -1
  25. package/dist/imports.d.ts.map +1 -1
  26. package/dist/imports.js +14 -8
  27. package/dist/imports.js.map +1 -1
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/jsx.d.ts.map +1 -1
  33. package/dist/jsx.js +5 -6
  34. package/dist/jsx.js.map +1 -1
  35. package/dist/lines.d.ts +24 -5
  36. package/dist/lines.d.ts.map +1 -1
  37. package/dist/lines.js +50 -16
  38. package/dist/lines.js.map +1 -1
  39. package/dist/ranges.d.ts +8 -0
  40. package/dist/ranges.d.ts.map +1 -1
  41. package/dist/ranges.js +12 -0
  42. package/dist/ranges.js.map +1 -1
  43. package/dist/remove.d.ts +18 -14
  44. package/dist/remove.d.ts.map +1 -1
  45. package/dist/remove.js +69 -630
  46. package/dist/remove.js.map +1 -1
  47. package/dist/run.d.ts.map +1 -1
  48. package/dist/run.js +21 -28
  49. package/dist/run.js.map +1 -1
  50. package/dist/scanner.d.ts +34 -0
  51. package/dist/scanner.d.ts.map +1 -1
  52. package/dist/scanner.js +137 -31
  53. package/dist/scanner.js.map +1 -1
  54. package/dist/shields.d.ts +72 -0
  55. package/dist/shields.d.ts.map +1 -0
  56. package/dist/shields.js +624 -0
  57. package/dist/shields.js.map +1 -0
  58. package/dist/splice.d.ts +42 -11
  59. package/dist/splice.d.ts.map +1 -1
  60. package/dist/splice.js +189 -56
  61. package/dist/splice.js.map +1 -1
  62. package/package.json +2 -1
  63. package/src/args.ts +21 -21
  64. package/src/astgrep.ts +11 -13
  65. package/src/containers.ts +128 -0
  66. package/src/coverage.ts +110 -0
  67. package/src/directives.ts +38 -20
  68. package/src/files.ts +169 -91
  69. package/src/imports.ts +15 -8
  70. package/src/index.ts +1 -0
  71. package/src/jsx.ts +5 -6
  72. package/src/lines.ts +55 -14
  73. package/src/ranges.ts +17 -0
  74. package/src/remove.ts +82 -730
  75. package/src/run.ts +22 -34
  76. package/src/scanner.ts +180 -32
  77. package/src/shields.ts +701 -0
  78. package/src/splice.ts +224 -60
package/dist/remove.js CHANGED
@@ -1,9 +1,11 @@
1
- import { astGrepReach, isFileWidePosition, rowStartOffsets } from "./astgrep.js";
2
- import { activePositionalDirectives, bunMarkerOffset, carriesAstGrepSuppression, isLegalComment, } from "./directives.js";
3
- import { LINE_TERMINATOR, isBlank, lineStartOffsets } from "./lines.js";
4
- import { firstIndexAtOrAfter } from "./ranges.js";
1
+ import { isFileWidePosition } from "./astgrep.js";
2
+ import { attachContainers, emptiedBy, mergeContainers } from "./containers.js";
3
+ import { activePositionalDirectives, bunMarkerOffset, isLegalComment } from "./directives.js";
4
+ import { LINE_TERMINATOR, isBlank } from "./lines.js";
5
+ import { byStart } from "./ranges.js";
5
6
  import { analyzeSource } from "./scanner.js";
6
- import { applyEdits, blankLineEdits } from "./splice.js";
7
+ import { shieldDirectives } from "./shields.js";
8
+ import { applyEdits, blankLineEdits, heldLines } from "./splice.js";
7
9
  /**
8
10
  * Removes comments from TypeScript source without touching code.
9
11
  *
@@ -11,11 +13,16 @@ import { applyEdits, blankLineEdits } from "./splice.js";
11
13
  * - AST-based ranges: strings, template literals and regexes are never affected.
12
14
  * - Directives (`@ts-expect-error`, `eslint-disable`, ...) and license headers are
13
15
  * kept by default, since deleting them changes build/lint behaviour.
14
- * - Surviving comments keep their directive semantics: when deleting a leading
15
- * comment would newly activate a position-dependent directive in a kept
16
- * comment (prettier's `@format` docblock pragma counts only as the file's
17
- * first comment, Bun's `// @bun` only at the very start or right after a
18
- * shebang line), the leading comment is kept instead.
16
+ * - Surviving comments keep their directive semantics. The lines a directive
17
+ * covers stay lines of their own: where deleting the comments on one would
18
+ * empty it, an empty line stays in its place, so that the code below moves
19
+ * up under no next-line directive or counted coverage hint, and where it
20
+ * would join one to another line, the comment's own line breaks stay. A
21
+ * comment stays only where a tool reads the directive with it: one between
22
+ * a directive and the code it would otherwise apply to, or one whose
23
+ * removal would newly activate a position-dependent directive (prettier's
24
+ * `@format` docblock pragma counts only as the file's first comment, Bun's
25
+ * `// @bun` only at the very start or right after a shebang line).
19
26
  * - A space is inserted where removing a block comment would merge two tokens,
20
27
  * and a line break is kept where the comment acted as one (ASI stays intact).
21
28
  * - A JSX comment goes with its braces (`{/* note *​/}`), unless that would
@@ -42,8 +49,8 @@ import { applyEdits, blankLineEdits } from "./splice.js";
42
49
  * set, an error is thrown instead of returning corrupted output.
43
50
  */
44
51
  export function removeComments(source, options = {}) {
45
- const jsx = options.jsx === true;
46
- const analysis = analyzeSource(source, { jsx });
52
+ const scan = { jsx: options.jsx === true, javascript: options.javascript === true };
53
+ const analysis = analyzeSource(source, scan);
47
54
  const comments = analysis.comments;
48
55
  let removed = [];
49
56
  const kept = [];
@@ -66,9 +73,13 @@ export function removeComments(source, options = {}) {
66
73
  containerOf.set(comment, container);
67
74
  }
68
75
  const context = {
76
+ comments,
69
77
  containerOf,
70
78
  skippable: skippableRanges(comments, containerOf, new Set(removed)),
71
79
  preceding: analysis.preceding,
80
+ directives: analysis.directives,
81
+ shadows: analysis.shadows,
82
+ casts: analysis.casts,
72
83
  };
73
84
  const search = containerSearch(containers);
74
85
  // Collapsing blank lines can only move a surviving comment to the very
@@ -81,18 +92,22 @@ export function removeComments(source, options = {}) {
81
92
  // below them (see gapHolders).
82
93
  const holders = new Set();
83
94
  for (;;) {
84
- const shielding = shieldNextLineDirectives(source, removed, kept, skipped, context);
95
+ const shielding = shieldDirectives(source, removed, kept, skipped, context);
85
96
  removed = shielding.removed;
86
97
  if (removed.length === 0) {
87
98
  return { code: source, removed, kept, skipped, changed: false };
88
99
  }
89
100
  const removing = new Set(removed);
90
- search.track(new Set(containers.filter((container) => container.comments.every((c) => removing.has(c)))));
101
+ search.track(new Set(containers.filter((container) => emptiedBy(container, removing))));
91
102
  const edits = removalEdits(removed, containerOf, search.droppable, holders);
92
103
  const deletions = edits.filter((edit) => edit.replacement === undefined);
93
- const blankEdits = tidyBlankLines ? blankLineEdits(source, deletions, comments, shielding.lines, analysis.jsx) : [];
94
- const code = editKeepingBom(source, [...edits, ...blankEdits].sort(byStart));
95
- const output = analyzeSource(code, { jsx });
104
+ const lines = {
105
+ shielded: shielding.lines,
106
+ held: heldLines(source, deletions, comments, shielding.lines),
107
+ };
108
+ const blankEdits = tidyBlankLines ? blankLineEdits(source, deletions, comments, lines, analysis.jsx) : [];
109
+ const code = editKeepingBom(source, [...edits, ...blankEdits].sort(byStart), lines);
110
+ const output = analyzeSource(code, scan);
96
111
  if (search.adjust(changedSegments(analysis.jsx.segments, output.jsx.segments)))
97
112
  continue;
98
113
  // Where the output joins two groups of imports or exports that a sorter
@@ -105,7 +120,7 @@ export function removeComments(source, options = {}) {
105
120
  holders.add(holder);
106
121
  continue;
107
122
  }
108
- const survivor = firstChangedSurvivor(source, code, output.comments, kept, skipped);
123
+ const survivor = firstChangedSurvivor(source, analysis, code, output, kept, skipped);
109
124
  if (survivor === undefined) {
110
125
  return { code, removed, kept, skipped, changed: true };
111
126
  }
@@ -115,7 +130,9 @@ export function removeComments(source, options = {}) {
115
130
  }
116
131
  // A surviving comment changed meaning: with everything before it deleted
117
132
  // it became the file's first comment (or its very first bytes), turning a
118
- // previously inert positional directive live. Re-protect the removal
133
+ // previously inert positional directive live — or, in JavaScript, a
134
+ // multi-line comment in front of it went for a line break, after which
135
+ // tsc reads it as the JSDoc of the code behind it. Re-protect the removal
119
136
  // candidate closest before it and try again: that comment then keeps
120
137
  // holding the survivor away from the activating position, exactly as the
121
138
  // input did. (Looping, because the re-protected comment can itself be a
@@ -133,32 +150,35 @@ export function removeComments(source, options = {}) {
133
150
  function unexpectedResult() {
134
151
  return new Error("comment removal produced an unexpected result; refusing to continue");
135
152
  }
136
- /** Sort comparator for document order: ranges are ordered by where they start. */
137
- function byStart(a, b) {
138
- return a.start - b.start;
153
+ /**
154
+ * The items of the source's list and of the output's that correspond, in
155
+ * pairs; throws when the lists differ in length, since removing comments
156
+ * never adds or drops what they list.
157
+ */
158
+ function corresponding(before, after) {
159
+ if (before.length !== after.length)
160
+ throw unexpectedResult();
161
+ return before.map((item, index) => [item, after[index]]);
139
162
  }
140
163
  /**
141
164
  * Compares the spliced output's comments against the comments meant to
142
165
  * survive, in document order (removal never reorders them). Throws when the
143
166
  * texts themselves differ (the output would be corrupted) and returns the
144
167
  * first surviving comment whose directive semantics changed, or undefined
145
- * when the output is exactly as expected. Besides the canonical directive
146
- * name, the position-dependent pragmas are compared on their own: a comment
168
+ * when the output is exactly as expected. Every directive a comment carries
169
+ * is compared, and what tsc reads from it as JSDoc in JavaScript. The
170
+ * position-dependent pragmas are compared on their own besides: a comment
147
171
  * can carry an inert `@format` underneath the directive an earlier rule
148
- * already named (an eslint config block, say), and that pragma going live
149
- * must not hide behind the unchanged name.
172
+ * already named (an eslint config block, say), and where an ast-grep
173
+ * suppression covers the file does not show in its name.
150
174
  */
151
- function firstChangedSurvivor(source, code, actual, kept, skipped) {
152
- const expected = [...kept, ...skipped].sort(byStart);
153
- if (actual.length !== expected.length) {
154
- throw unexpectedResult();
155
- }
156
- for (const [index, comment] of expected.entries()) {
157
- const survivor = actual[index];
175
+ function firstChangedSurvivor(source, analysis, code, output, kept, skipped) {
176
+ const carried = (of, comment) => JSON.stringify([of.directives.get(comment) ?? [], of.typed.get(comment) ?? []]);
177
+ for (const [comment, survivor] of corresponding([...kept, ...skipped].sort(byStart), output.comments)) {
158
178
  if (survivor.text !== comment.text) {
159
179
  throw unexpectedResult();
160
180
  }
161
- if (survivor.directive !== comment.directive)
181
+ if (carried(output, survivor) !== carried(analysis, comment))
162
182
  return comment;
163
183
  const before = activePositionalDirectives(comment.kind, comment.text, positionalPlacement(source, comment));
164
184
  const after = activePositionalDirectives(survivor.kind, survivor.text, positionalPlacement(code, survivor));
@@ -210,11 +230,8 @@ function closestRemovalBefore(removals, comment) {
210
230
  * group are sorted, and so can an empty line only the output has.
211
231
  */
212
232
  function gapHolders(source, before, after, removals, holders) {
213
- if (before.length !== after.length)
214
- throw unexpectedResult();
215
233
  const found = [];
216
- for (const [index, gap] of before.entries()) {
217
- const { splits, spaced } = after[index];
234
+ for (const [gap, { splits, spaced }] of corresponding(before, after)) {
218
235
  const intact = gap.splits.every((sorter) => splits.includes(sorter)) && gap.spaced.every((linter) => spaced.includes(linter));
219
236
  if (intact)
220
237
  continue;
@@ -235,15 +252,15 @@ function gapHolders(source, before, after, removals, holders) {
235
252
  * comment-only first line took it along: the mark is an encoding artifact,
236
253
  * not line content.
237
254
  */
238
- function editKeepingBom(source, edits) {
255
+ function editKeepingBom(source, edits, lines) {
239
256
  if (!source.startsWith(""))
240
- return applyEdits(source, edits);
257
+ return applyEdits(source, edits, lines);
241
258
  // The editing itself works on the BOM-less body (with ranges shifted to
242
259
  // match) so its line handling never sees the mark, then the mark is
243
260
  // re-attached; this keeps `// gone\n...` from losing the mark with
244
261
  // the dropped line.
245
262
  const shifted = edits.map((edit) => ({ ...edit, start: edit.start - 1, end: edit.end - 1 }));
246
- return `${applyEdits(source.slice(1), shifted)}`;
263
+ return `${applyEdits(source.slice(1), shifted, lines)}`;
247
264
  }
248
265
  function isProtected(comment, options) {
249
266
  if (options.keep?.(comment) === true)
@@ -254,57 +271,6 @@ function isProtected(comment, options) {
254
271
  return true;
255
272
  return false;
256
273
  }
257
- function attachContainers(source, layouts, comments) {
258
- const containers = new Map();
259
- for (const layout of layouts) {
260
- const inside = [];
261
- let index = firstIndexAtOrAfter(comments, layout.start, (comment) => comment.start);
262
- for (let comment = comments[index]; comment !== undefined && comment.end < layout.end; comment = comments[index]) {
263
- inside.push(comment);
264
- index += 1;
265
- }
266
- containers.set(layout, {
267
- start: layout.start,
268
- end: layout.end,
269
- segment: layout.segment,
270
- suspect: layout.suspect,
271
- next: undefined,
272
- comments: inside,
273
- mode: "drop",
274
- spaceRange: spaceRange(source, layout),
275
- });
276
- }
277
- for (const [layout, container] of containers) {
278
- if (layout.next !== undefined)
279
- container.next = containers.get(layout.next);
280
- }
281
- return [...containers.values()];
282
- }
283
- const isHorizontalSpace = (char) => char === " " || char === "\t";
284
- /**
285
- * The range `{" "}` would take the place of: a one-line container and the
286
- * spaces before it when code precedes it on its line (`<b /> {/* x *​/}`), or
287
- * the spaces after it when it opens its line and code follows. Undefined when
288
- * no spaces hold it off anything on its line.
289
- */
290
- function spaceRange(source, container) {
291
- if (LINE_TERMINATOR.test(source.slice(container.start, container.end)))
292
- return undefined;
293
- let lineStart = container.start;
294
- while (lineStart > 0 && !LINE_TERMINATOR.test(source[lineStart - 1]))
295
- lineStart -= 1;
296
- let before = container.start;
297
- while (isHorizontalSpace(source[before - 1]))
298
- before -= 1;
299
- let after = container.end;
300
- while (isHorizontalSpace(source[after]))
301
- after += 1;
302
- if (!isBlank(source.slice(lineStart, container.start))) {
303
- return before < container.start ? { start: before, end: container.end } : undefined;
304
- }
305
- const codeAfter = after < source.length && !LINE_TERMINATOR.test(source[after]);
306
- return codeAfter && after > container.end ? { start: container.start, end: after } : undefined;
307
- }
308
274
  /**
309
275
  * Comments, and the comment-only containers that may go along with theirs,
310
276
  * as sorted ranges: what the search for the code after a directive skips.
@@ -313,17 +279,7 @@ function spaceRange(source, container) {
313
279
  * the found code further down, which shields more, not less.
314
280
  */
315
281
  function skippableRanges(comments, containerOf, candidates) {
316
- const ranges = [];
317
- for (const comment of comments) {
318
- const container = containerOf.get(comment);
319
- if (container === undefined || !container.comments.every((inside) => candidates.has(inside))) {
320
- ranges.push(comment);
321
- }
322
- else if (ranges[ranges.length - 1] !== container) {
323
- ranges.push(container);
324
- }
325
- }
326
- return ranges;
282
+ return mergeContainers(comments, containerOf, (container) => emptiedBy(container, candidates));
327
283
  }
328
284
  /**
329
285
  * The edits that remove the comments: one per comment, or one per container
@@ -331,27 +287,20 @@ function skippableRanges(comments, containerOf, candidates) {
331
287
  * gapHolders) leaves an empty line in its place.
332
288
  */
333
289
  function removalEdits(removed, containerOf, droppable, holders) {
334
- const edits = [];
335
- for (const comment of removed) {
336
- const container = containerOf.get(comment);
337
- if (container === undefined || !droppable.has(container) || container.mode === "keep") {
338
- edits.push({ start: comment.start, end: comment.end, blankLine: holders.has(comment) });
339
- }
340
- else if (comment === container.comments[0]) {
341
- edits.push(container.mode === "drop"
342
- ? { start: container.start, end: container.end, jsx: true }
343
- : { ...container.spaceRange, replacement: '{" "}' });
344
- }
345
- }
346
- return edits;
290
+ const units = mergeContainers(removed, containerOf, (container) => droppable.has(container) && container.mode !== "keep");
291
+ return units.map((unit) => {
292
+ if (!("comments" in unit))
293
+ return { start: unit.start, end: unit.end, blankLine: holders.has(unit) };
294
+ return unit.mode === "drop"
295
+ ? { start: unit.start, end: unit.end, jsx: true }
296
+ : { ...unit.spaceRange, replacement: '{" "}' };
297
+ });
347
298
  }
348
299
  /** Indexes of the JSX stretches whose rendering differs; throws when the structure itself does. */
349
300
  function changedSegments(before, after) {
350
- if (before.length !== after.length)
351
- throw unexpectedResult();
352
301
  const changed = new Set();
353
- for (const [index, rendering] of before.entries()) {
354
- if (rendering !== after[index])
302
+ for (const [index, [rendering, now]] of corresponding(before, after).entries()) {
303
+ if (rendering !== now)
355
304
  changed.add(index);
356
305
  }
357
306
  return changed;
@@ -435,514 +384,4 @@ function containerSearch(containers) {
435
384
  },
436
385
  };
437
386
  }
438
- /**
439
- * Re-protects comments whose removal would delete a physical line sitting
440
- * under a surviving next-line directive (`@ts-expect-error`,
441
- * `eslint-disable-next-line`, ...). Dropping such a line would shift the
442
- * following code up, silently changing which line the directive applies to —
443
- * and with it the compiler or linter behaviour. Nor may a removal join
444
- * another line to one a directive covers, the line a line directive
445
- * (`eslint-disable-line`, ...) stands on included. Directives whose tools
446
- * reach further get more: below a tsc suppression the first line each
447
- * compiler cannot step over stays, oxlint's line-feed rows add the lines they
448
- * run over, between a directive that only counts as the last comment before
449
- * its target (`@deno-types`, ...) or a coverage hint that ast-v8-to-istanbul
450
- * only applies to the node right after it and that target every comment
451
- * stays, and a JSX comment container right after a directive in a container
452
- * (`{/* prettier-ignore *​/}`, which applies to the next sibling) stays too.
453
- *
454
- * The line checks work on whole lines, not single comments: a line holding
455
- * several removable comments (`/* one *​/ /* two *​/`) vanishes just the same,
456
- * so every comment on it has to stay — and a comment-only JSX container takes
457
- * its braces along. Runs to a fixpoint because a re-protected comment can
458
- * itself be a next-line directive shielding further lines (when directives
459
- * are being removed selectively).
460
- */
461
- function shieldNextLineDirectives(source, removed, kept, skipped, context) {
462
- const lineOffsets = lineStartOffsets(source);
463
- const totalLines = lineOffsets.length;
464
- const shieldedLines = new Set();
465
- const blockingLines = new Set();
466
- const shieldedGaps = [];
467
- const siblingTargets = new Set();
468
- const astGrepReaches = [];
469
- const processed = new Set();
470
- let stillRemoved = removed;
471
- let units;
472
- const currentUnits = () => (units ??= removalUnits(stillRemoved, context.containerOf));
473
- let rows;
474
- /** The (1-based) line holding the offset. */
475
- const lineOf = (offset) => firstIndexAtOrAfter(lineOffsets, offset + 1, (start) => start);
476
- const collectShields = () => {
477
- let added = false;
478
- const shieldLines = (from, to) => {
479
- for (let line = from; line <= Math.min(to, totalLines); line += 1) {
480
- if (shieldedLines.has(line))
481
- continue;
482
- shieldedLines.add(line);
483
- added = true;
484
- }
485
- };
486
- for (const comment of [...kept, ...skipped]) {
487
- if (processed.has(comment))
488
- continue;
489
- processed.add(comment);
490
- const directive = comment.directive;
491
- if (directive === undefined)
492
- continue;
493
- if (carriesAstGrepSuppression(comment.text)) {
494
- const reach = astGrepReach(source, (rows ??= rowStartOffsets(source)), comment, context.preceding.get(comment));
495
- astGrepReaches.push(reach);
496
- if (reach.nextRow !== undefined && reach.nextRow.end > reach.nextRow.start) {
497
- for (let line = lineOf(reach.nextRow.start); line <= lineOf(reach.nextRow.end - 1); line += 1) {
498
- shieldedLines.add(line);
499
- }
500
- }
501
- added = true;
502
- }
503
- const lastComment = LAST_COMMENT_DIRECTIVES.has(directive);
504
- if (lastComment || NEXT_TOKEN_DIRECTIVES.has(directive)) {
505
- const codeStart = codeStartAfter(source, comment.end, context.skippable);
506
- if (codeStart > comment.end && codeStart < source.length) {
507
- shieldedGaps.push([comment.end, codeStart]);
508
- added = true;
509
- }
510
- if (lastComment)
511
- continue;
512
- }
513
- if (TSC_SUPPRESSIONS.has(directive)) {
514
- for (const line of firstBlockingLines(source, comment, lineOffsets, context.skippable)) {
515
- if (blockingLines.has(line))
516
- continue;
517
- blockingLines.add(line);
518
- added = true;
519
- }
520
- }
521
- // oxlint reaches its rows' lines past the ones counted below.
522
- if (OXLINT_ROW_DIRECTIVES.has(directive)) {
523
- const reach = oxlintReachLines(source, (rows ??= rowStartOffsets(source)), lineOf, comment, directive);
524
- if (reach !== undefined)
525
- shieldLines(reach.from, reach.to);
526
- }
527
- // A line directive covers the line it stands on, which no removal may
528
- // join to another (see joiningLineGroup).
529
- if (isOwnLineDirective(directive))
530
- shieldLines(comment.line, comment.line);
531
- if (!isNextLineDirective(directive))
532
- continue;
533
- // In JSX, such a directive in braces applies to the sibling after it,
534
- // whatever line that is on (prettier leaves the element after
535
- // `{/* prettier-ignore */}` as is): a comment-only container standing
536
- // between them has to stay. Range and file pragmas target no sibling.
537
- const holder = context.containerOf.get(comment);
538
- if (holder?.next !== undefined && !siblingTargets.has(holder.next)) {
539
- siblingTargets.add(holder.next);
540
- added = true;
541
- }
542
- // A trailing formatter or scanner suppression (`a = [1]; // oxfmt-ignore`,
543
- // `secret(); // nosemgrep`) targets its own line, so it shields nothing
544
- // below it. In JSX, the container holding the comment is what has to
545
- // stand on lines of its own.
546
- if (TRAILING_TARGETS_OWN_LINE.has(directive) && !occupiesWholeLines(source, holder ?? comment))
547
- continue;
548
- // Counted pragmas like `c8 ignore next 3` cover several lines.
549
- shieldLines(comment.endLine + 1, comment.endLine + shieldedLineCount(comment));
550
- }
551
- return added;
552
- };
553
- const protect = (group) => {
554
- const grouped = new Set(group);
555
- stillRemoved = stillRemoved.filter((comment) => !grouped.has(comment));
556
- kept.push(...group);
557
- units = undefined;
558
- };
559
- const protectShields = () => {
560
- let changed = false;
561
- for (const line of shieldedLines) {
562
- const group = vanishingLineGroup(source, line, lineOffsets, currentUnits()) ??
563
- joiningLineGroup(source, line, lineOffsets, currentUnits());
564
- if (group === undefined)
565
- continue;
566
- protect(group);
567
- changed = true;
568
- }
569
- for (const line of blockingLines) {
570
- const group = lineOpeningGroup(source, line, lineOffsets, currentUnits());
571
- if (group === undefined)
572
- continue;
573
- protect(group);
574
- changed = true;
575
- }
576
- for (const [from, to] of shieldedGaps) {
577
- const group = stillRemoved.filter((comment) => comment.start >= from && comment.start < to);
578
- if (group.length === 0)
579
- continue;
580
- protect(group);
581
- changed = true;
582
- }
583
- for (const target of siblingTargets) {
584
- const group = stillRemoved.filter((comment) => target.comments.includes(comment));
585
- if (group.length === 0)
586
- continue;
587
- protect(group);
588
- changed = true;
589
- }
590
- for (const reach of astGrepReaches) {
591
- const group = currentUnits().filter((unit) => reach.holds(unit));
592
- if (group.length === 0)
593
- continue;
594
- protect(group.flatMap((unit) => unit.comments));
595
- changed = true;
596
- }
597
- return changed;
598
- };
599
- collectShields();
600
- while (protectShields()) {
601
- if (!collectShields())
602
- break;
603
- }
604
- if (stillRemoved.length !== removed.length) {
605
- kept.sort(byStart);
606
- }
607
- return { removed: stillRemoved, lines: shieldedLines };
608
- }
609
- /**
610
- * The removals as the edits delete them: a comment-only container whose
611
- * comments all go — and that is to go braces and all — is one unit spanning
612
- * its braces, every other comment a unit of its own. Sorted, as the comments.
613
- */
614
- function removalUnits(removals, containerOf) {
615
- const removing = new Set(removals);
616
- const units = [];
617
- for (const comment of removals) {
618
- const container = containerOf.get(comment);
619
- if (container === undefined ||
620
- container.mode !== "drop" ||
621
- !container.comments.every((inside) => removing.has(inside))) {
622
- units.push({ start: comment.start, end: comment.end, comments: [comment] });
623
- }
624
- else if (units[units.length - 1]?.container !== container) {
625
- units.push({ start: container.start, end: container.end, comments: container.comments, container });
626
- }
627
- }
628
- return units;
629
- }
630
- /**
631
- * Offset of the first character at or after `from` that is neither
632
- * whitespace nor inside one of the (sorted, non-overlapping) ranges, or the
633
- * source length when only ranges follow. `from` lies past the start of at
634
- * least one range (the directive the search is for); when the closest of
635
- * them runs past `from` — a block comment opened on the directive's line —
636
- * the search resumes at its end.
637
- */
638
- function codeStartAfter(source, from, ranges) {
639
- let next = firstIndexAtOrAfter(ranges, from, (range) => range.start);
640
- let index = Math.max(from, ranges[next - 1].end);
641
- while (index < source.length) {
642
- const range = ranges[next];
643
- if (range !== undefined && range.start === index) {
644
- index = range.end;
645
- next += 1;
646
- }
647
- else if (isBlank(source[index])) {
648
- index += 1;
649
- }
650
- else {
651
- return index;
652
- }
653
- }
654
- return source.length;
655
- }
656
- /**
657
- * For each TypeScript compiler, the first line between a tsc suppression and
658
- * the code on the lines below it that the compiler does not step over, if
659
- * any. Looking for the line a suppression applies to, a compiler skips the
660
- * lines it reads as blank or as a `//` comment (see TSC_PASSABLE_LINES); any
661
- * other line — one opening with a block comment, say — ends the search,
662
- * leaving the suppression without a target for that compiler. Deleting that
663
- * line would let the suppression reach the code instead, so it has to stay.
664
- * The two compilers can stop at different lines: a line holding only a
665
- * vertical tab stops tsc 7, while tsc 6 searches on to the next line it
666
- * cannot pass.
667
- */
668
- function firstBlockingLines(source, comment, lineOffsets, ranges) {
669
- // A suppression applies from the line below it on, so code sharing its line
670
- // (`/* @ts-ignore */ foo();`) does not end the search.
671
- const codeStart = codeStartAfter(source, lineOffsets[comment.endLine] ?? source.length, ranges);
672
- if (codeStart >= source.length)
673
- return [];
674
- const codeLine = firstIndexAtOrAfter(lineOffsets, codeStart + 1, (offset) => offset);
675
- const found = [];
676
- for (const passable of TSC_PASSABLE_LINES) {
677
- for (let line = comment.endLine + 1; line < codeLine; line += 1) {
678
- if (!passable.test(source.slice(lineOffsets[line - 1], lineOffsets[line]))) {
679
- found.push(line);
680
- break;
681
- }
682
- }
683
- }
684
- return found;
685
- }
686
- /**
687
- * The removals on the given line when one of them opens it (holds its first
688
- * non-whitespace character), so that deleting them would change how the
689
- * line starts. Returns undefined when something that survives opens the line
690
- * instead, or nothing on it is to be removed.
691
- */
692
- function lineOpeningGroup(source, line, lineOffsets, units) {
693
- // A blocking line always lies above the code line, so the next offset exists.
694
- const lineStart = lineOffsets[line - 1];
695
- const lineEnd = lineOffsets[line];
696
- const group = units.filter((unit) => unit.start < lineEnd && unit.end > lineStart);
697
- let first = lineStart;
698
- while (first < lineEnd && isBlank(source[first]))
699
- first += 1;
700
- return group.some((unit) => unit.start <= first && first < unit.end)
701
- ? group.flatMap((unit) => unit.comments)
702
- : undefined;
703
- }
704
- /**
705
- * The removals that would make the given line disappear: every
706
- * non-whitespace character of the line lies inside one of them, so deleting
707
- * them deletes the physical line. Returns undefined when the line survives
708
- * (it holds code, a kept comment, or nothing to remove at all).
709
- */
710
- function vanishingLineGroup(source, line, lineOffsets, units) {
711
- // collectShields never shields a line beyond the last one, so the offset exists.
712
- const lineStart = lineOffsets[line - 1];
713
- const lineEnd = lineOffsets[line] ?? source.length;
714
- const group = units.filter((unit) => unit.start < lineEnd && unit.end > lineStart);
715
- if (group.length === 0)
716
- return undefined;
717
- for (let index = lineStart; index < lineEnd; index += 1) {
718
- if (isBlank(source[index]))
719
- continue;
720
- if (!group.some((unit) => unit.start <= index && index < unit.end))
721
- return undefined;
722
- }
723
- return group.flatMap((unit) => unit.comments);
724
- }
725
- /**
726
- * The removals that would join the given line to another: they reach past
727
- * one of its ends, with something other than whitespace beyond them on the
728
- * line they run into. Deleting such a comment takes its line breaks along —
729
- * with nothing in their place right after an opening bracket or before
730
- * closing punctuation (see applyEdits) — so what stands beyond it can land on
731
- * the line, or what stands on the line move off it, and a directive covering
732
- * the line would cover other code. (With only whitespace beyond, the lines
733
- * the comment held vanish, which vanishingLineGroup weighs.)
734
- */
735
- function joiningLineGroup(source, line, lineOffsets, units) {
736
- const lineStart = lineOffsets[line - 1];
737
- const nextLineStart = lineOffsets[line];
738
- const lineEnd = nextLineStart ?? source.length;
739
- const group = units.filter((unit) => unit.start < lineEnd &&
740
- unit.end > lineStart &&
741
- ((nextLineStart !== undefined && unit.end > nextLineStart && !closesItsLine(source, unit)) ||
742
- (unit.start < lineStart && !opensItsLine(source, unit))));
743
- return group.length === 0 ? undefined : group.flatMap((unit) => unit.comments);
744
- }
745
- // The directives oxlint reads on rows of its own (see oxlintReachLines).
746
- const OXLINT_ROW_DIRECTIVES = new Set([
747
- "eslint-disable-next-line",
748
- "oxlint-disable-next-line",
749
- "eslint-disable-line",
750
- "oxlint-disable-line",
751
- ]);
752
- /**
753
- * The lines (1-based, inclusive) that oxlint applies an `eslint-` or
754
- * `oxlint-` line or next-line comment to, past the ones the line-based
755
- * shields take in. oxlint finds the stretch on rows that only a line feed
756
- * ends (`split_inclusive('\n')` and `lines()` in its `disable_directives.rs`):
757
- * a next-line comment covers the rest of the row its text ends on and the
758
- * row after it, a line comment its own row up to the comment. A lone CR,
759
- * U+2028 or U+2029 — a line break to tsc and ESLint — ends no row there, so
760
- * a row can run over several of the lines counted here. Undefined when a
761
- * next-line comment stands on the file's last row: oxlint then covers the
762
- * rest of the file, which no removal changes.
763
- */
764
- function oxlintReachLines(source, rows, lineOf, comment, directive) {
765
- const rowOf = (offset) => firstIndexAtOrAfter(rows, offset + 1, (start) => start) - 1;
766
- if (!directive.endsWith("-next-line")) {
767
- return { from: lineOf(rows[rowOf(comment.start)]), to: comment.line };
768
- }
769
- // The comment's text ends in front of a block comment's `*/`.
770
- const row = rowOf(comment.kind === "block" ? comment.end - 2 : comment.end);
771
- if (rows[row + 1] === undefined)
772
- return undefined;
773
- return { from: comment.endLine + 1, to: lineOf((rows[row + 2] ?? source.length) - 1) };
774
- }
775
- /**
776
- * Whether the directive covers the line it stands on: the `-line` forms of
777
- * the suppressions (`eslint-disable-line`, `tslint:disable-line`, ...).
778
- */
779
- function isOwnLineDirective(name) {
780
- return name.endsWith("-line") && !name.endsWith("-next-line");
781
- }
782
- // These suppressions only apply to the following node/line when they stand on
783
- // their own line — trailing after code they target (at most) their own line.
784
- // Other next-line directives (`@ts-ignore`, `no-dd-sa`, ...) target the next
785
- // line even when they trail code.
786
- const TRAILING_TARGETS_OWN_LINE = new Set([
787
- "prettier-ignore",
788
- "oxfmt-ignore",
789
- "dprint-ignore",
790
- "lgtm",
791
- "codeql",
792
- "skipcq",
793
- "nosemgrep",
794
- ]);
795
- // The suppressions tsc looks past blank and `//` lines for (see
796
- // firstBlockingLines). They stay next-line directives as well: Flow, which
797
- // honours them in TypeScript files, applies them to the very next line.
798
- const TSC_SUPPRESSIONS = new Set(["@ts-ignore", "@ts-expect-error"]);
799
- // The lines each compiler steps over on its way up from a diagnostic to a
800
- // suppression, matched against the whole line, line break included. tsc 6
801
- // trims the line and accepts nothing or a `//` comment; tsc 7 accepts only
802
- // spaces and tabs before the line break or the `//`.
803
- const TSC_PASSABLE_LINES = [/^\s*(?:\/\/|$)/, /^[ \t]*(?:[\r\n]|\/\/)/];
804
- // Directives that only count while no other comment sits between them and
805
- // their target: deno_graph reads `@deno-types`/`@ts-types` from the last
806
- // comment before an import, ts-prune and graphql-tag-pluck from the closest
807
- // leading comment, and ESLint's no-fallthrough and default-case from the last
808
- // comment before the next case or the closing brace. Deleting the comments in
809
- // that gap would newly activate such a directive, so the whole gap is
810
- // shielded — trailing comments in front of the code included. With no code
811
- // left there is nothing to target, and the switch-clause comments are only
812
- // detected in front of the `case`, `default` or `}` their rules read them
813
- // before.
814
- const LAST_COMMENT_DIRECTIVES = new Set([
815
- "@deno-types",
816
- "@ts-types",
817
- "ts-prune-ignore-next",
818
- "GraphQL",
819
- "fallthrough",
820
- "no-default",
821
- ]);
822
- // The coverage hints ast-v8-to-istanbul, Vitest's v8 provider, applies to the
823
- // node that starts at the very token after them: with another comment in
824
- // between, the hint has no target, and deleting that comment would bring it
825
- // into effect. The gap up to the code is shielded like the one above, on top
826
- // of the lines below the hint, which c8, Node and monocart count.
827
- const NEXT_TOKEN_DIRECTIVES = new Set([
828
- "istanbul-ignore-next",
829
- "istanbul-ignore-if",
830
- "istanbul-ignore-else",
831
- "c8-ignore-next",
832
- "c8-ignore-if",
833
- "c8-ignore-else",
834
- "v8-ignore-next",
835
- "v8-ignore-if",
836
- "v8-ignore-else",
837
- "node:coverage-ignore",
838
- "node:coverage-ignore-if",
839
- "node:coverage-ignore-else",
840
- ]);
841
- // Directives that target the line or node directly below them. File- and
842
- // range-scoped pragmas (`istanbul-ignore-file`, `c8-ignore-start`, ...) are
843
- // absent: they do not target the following line, so they never shield it.
844
- // They go by their names here: Vitest's v8 provider reads a range hint
845
- // spelled out on any line of this file, and would drop the rest of the file
846
- // from this project's coverage.
847
- const NEXT_LINE_DIRECTIVES = new Set([
848
- "@ts-ignore",
849
- "@ts-expect-error",
850
- "biome-ignore",
851
- "deno-lint-ignore",
852
- "deno-fmt-ignore",
853
- "deno-coverage-ignore",
854
- "prettier-ignore",
855
- "oxfmt-ignore",
856
- "dprint-ignore",
857
- "rome-ignore",
858
- "istanbul-ignore-next",
859
- "istanbul-ignore-if",
860
- "istanbul-ignore-else",
861
- "c8-ignore-next",
862
- "c8-ignore-if",
863
- "c8-ignore-else",
864
- "v8-ignore-next",
865
- "v8-ignore-if",
866
- "v8-ignore-else",
867
- "node:coverage-ignore",
868
- "node:coverage-ignore-if",
869
- "node:coverage-ignore-else",
870
- // Directives that hang off the node or line directly below them: a
871
- // whole-line comment between them and their target would change what
872
- // they apply to, so the line below stays shielded.
873
- "million-ignore",
874
- "@million-skip",
875
- "@million-jsx-skip",
876
- "deepcode-ignore",
877
- "skipcq",
878
- "lgtm",
879
- "codeql",
880
- "nosemgrep",
881
- "no-dd-sa",
882
- "datadog-disable",
883
- "noinspection",
884
- "language-injection",
885
- "@next-codemod-error",
886
- "@next-codemod-ignore",
887
- "$FlowFixMe",
888
- "$FlowExpectedError",
889
- "$FlowIssue",
890
- "$FlowIgnore",
891
- "pragma-allowlist-nextline-secret",
892
- "cspell:disable-next",
893
- "HTML",
894
- ]);
895
- function isNextLineDirective(name) {
896
- return name.endsWith("-next-line") || NEXT_LINE_DIRECTIVES.has(name);
897
- }
898
- // The coverage pragmas a line count after `ignore next` applies to: c8
899
- // (v8-to-istanbul), Node's test-runner coverage and monocart-coverage-reports
900
- // count lines. istanbul and ast-v8-to-istanbul, Vitest's providers, apply the
901
- // hint to the next node whatever count follows, so `istanbul ignore next 3`
902
- // covers one line. Everything else — `@ts-expect-error`,
903
- // `eslint-disable-next-line` and friends — covers exactly one line too, no
904
- // matter what prose like "we ignore next 3 legacy calls" appears in the
905
- // reason text.
906
- const COUNTED_NEXT_LINE = new Set(["c8-ignore-next", "v8-ignore-next", "node:coverage-ignore"]);
907
- /**
908
- * Number of following lines a next-line pragma covers (`c8 ignore next 3` →
909
- * 3). monocart reads the count past any whitespace or none, and c8 and
910
- * monocart stop at the last digit, so `next3` and `next 3x` count 3 as well.
911
- */
912
- function shieldedLineCount(comment) {
913
- if (comment.directive === undefined || !COUNTED_NEXT_LINE.has(comment.directive))
914
- return 1;
915
- const match = /\bignore\s*next\s*(\d+)/.exec(comment.text);
916
- return match ? Math.max(1, Number(match[1])) : 1;
917
- }
918
- /**
919
- * True when nothing but whitespace shares the range's first and last lines.
920
- * Lines are delimited by any ECMAScript line terminator, matching how the
921
- * scanner numbers them (a lone `\r`, U+2028 and U+2029 count too).
922
- */
923
- function occupiesWholeLines(source, range) {
924
- return opensItsLine(source, range) && closesItsLine(source, range);
925
- }
926
- /** True when nothing but whitespace follows the range on its last line. */
927
- function closesItsLine(source, range) {
928
- for (let index = range.end; index < source.length; index += 1) {
929
- const char = source[index];
930
- if (LINE_TERMINATOR.test(char))
931
- break;
932
- if (!isBlank(char))
933
- return false;
934
- }
935
- return true;
936
- }
937
- /** True when nothing but whitespace precedes the range on its first line. */
938
- function opensItsLine(source, range) {
939
- for (let index = range.start - 1; index >= 0; index -= 1) {
940
- const char = source[index];
941
- if (LINE_TERMINATOR.test(char))
942
- break;
943
- if (!isBlank(char))
944
- return false;
945
- }
946
- return true;
947
- }
948
387
  //# sourceMappingURL=remove.js.map