@widgetic/dev-tools 0.3.8 → 0.3.9

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.
@@ -0,0 +1,1104 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Does the console-log commenter comment out only what it can, keep the rest, and say why?
4
+ *
5
+ * `comment-console-logs` turns `console.log` / `info` / `debug` / `trace` statements into comments and keeps every one
6
+ * of them in the code. A tool that edits other people's source is only as good as its worst edit, so each rule is driven
7
+ * here with the code it would be wrong about: a statement that is the body of a braceless `if` (commenting it hands the
8
+ * next statement to the `if`), a call that is a value (`() => console.log(x)` has nothing left to return), a call
9
+ * inside a string, a comment or a template literal (not a call at all), a statement that shares its line with a `*` and
10
+ * a `/` (it cannot go between `/*` and `*\/`), a call inside the arguments of a call that is itself commented out
11
+ * (two edits on the same text), files with CRLF endings, and Svelte markup, where a tag inside an attribute cannot
12
+ * become an HTML comment. Every result is also read again by the parser: no parse error, and every call that was
13
+ * meant to stay is still there.
14
+ *
15
+ * `typescript` and `svelte` are not dependencies of this package, so the suite loads them the way the tool does, from a
16
+ * checkout that has them installed: `COMMENT_CONSOLE_LOGS_RESOLVE_FROM`, the current directory, or any sibling checkout
17
+ * of this one. When none has both, the suite fails and says so (a skipped suite would prove nothing). It then runs the
18
+ * same fixtures against every TypeScript and Svelte pair the checkouts have installed, because the tool is meant to
19
+ * read the code with the parsers the code is built with.
20
+ *
21
+ * Runs on the built-in test runner — no framework, no dependencies:
22
+ *
23
+ * npm run test:comment-logs (in this repo)
24
+ */
25
+
26
+ import assert from 'node:assert/strict';
27
+ import { spawnSync } from 'node:child_process';
28
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
29
+ import { createRequire } from 'node:module';
30
+ import { tmpdir } from 'node:os';
31
+ import { dirname, join, resolve } from 'node:path';
32
+ import { after, describe, it } from 'node:test';
33
+ import { fileURLToPath, pathToFileURL } from 'node:url';
34
+
35
+ import {
36
+ applyEdits,
37
+ checkCommentedText,
38
+ collectSourceFiles,
39
+ commentOutConsoleLogs,
40
+ findConsoleCalls,
41
+ isSourceFile,
42
+ KEPT_REASONS,
43
+ loadParsers,
44
+ parsersNeededFor,
45
+ planEdit
46
+ } from '../lib/comment-console-logs.mjs';
47
+
48
+ const BIN = fileURLToPath(new URL('../bin/comment-console-logs.mjs', import.meta.url));
49
+ const FRONTEND_ROOT = fileURLToPath(new URL('../..', import.meta.url));
50
+
51
+ // ---- Finding parsers to read the fixtures with --------------------------------------------------------------------
52
+
53
+ /** The version of a package as the checkout `directory` would load it, or null when it has none. */
54
+ function installedVersion(directory, packageName) {
55
+ try {
56
+ const requireFromDirectory = createRequire(pathToFileURL(join(directory, 'package.json')));
57
+ return JSON.parse(readFileSync(requireFromDirectory.resolve(`${packageName}/package.json`), 'utf8')).version;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Every checkout that has both parsers installed, one per distinct pair of versions, the first of each pair wins:
65
+ * the environment variable, then the current directory, then the sibling checkouts in name order.
66
+ */
67
+ function findParserHosts() {
68
+ const candidates = [process.env.COMMENT_CONSOLE_LOGS_RESOLVE_FROM, process.cwd()].filter(Boolean);
69
+ if (existsSync(FRONTEND_ROOT)) {
70
+ for (const name of readdirSync(FRONTEND_ROOT).sort()) {
71
+ const siblingDirectory = join(FRONTEND_ROOT, name);
72
+ if (statSync(siblingDirectory).isDirectory()) candidates.push(siblingDirectory);
73
+ }
74
+ }
75
+ const hosts = [];
76
+ const seenPairs = new Set();
77
+ for (const directory of candidates) {
78
+ const typescriptVersion = installedVersion(directory, 'typescript');
79
+ const svelteVersion = installedVersion(directory, 'svelte');
80
+ if (!typescriptVersion || !svelteVersion) continue;
81
+ const pair = `typescript ${typescriptVersion} + svelte ${svelteVersion}`;
82
+ if (seenPairs.has(pair)) continue;
83
+ seenPairs.add(pair);
84
+ hosts.push({ directory: resolve(directory), pair });
85
+ }
86
+ return hosts;
87
+ }
88
+
89
+ const parserHosts = findParserHosts();
90
+ if (parserHosts.length === 0) {
91
+ throw new Error(
92
+ 'No checkout with both typescript and svelte installed was found (looked at COMMENT_CONSOLE_LOGS_RESOLVE_FROM, the current directory and the siblings of dev-tools). ' +
93
+ 'Install them in one, or set COMMENT_CONSOLE_LOGS_RESOLVE_FROM to it.'
94
+ );
95
+ }
96
+ const parsers = loadParsers(parserHosts[0].directory);
97
+ console.log(`[comment-console-logs test] reading the fixtures with ${parserHosts[0].pair} (from ${parserHosts[0].directory}); ${parserHosts.length} pair(s) installed in the checkouts`);
98
+
99
+ /** Every directory a test created, so a failure cannot leave one behind. */
100
+ const createdDirectories = [];
101
+ after(() => {
102
+ for (const directory of createdDirectories) rmSync(directory, { recursive: true, force: true });
103
+ });
104
+
105
+ function makeTemporaryDirectory(label) {
106
+ const directory = mkdtempSync(join(tmpdir(), `comment-console-logs-${label}-`));
107
+ createdDirectories.push(directory);
108
+ return directory;
109
+ }
110
+
111
+ // ---- Helpers for the fixtures -------------------------------------------------------------------------------------
112
+
113
+ /** The text as a pattern that matches only itself. */
114
+ function escapeRegExp(text) {
115
+ return text.replace(/[.*+?^$\{\}()|[\]\\]/g, '\\$&');
116
+ }
117
+
118
+ /** A fixture from its lines, so the indentation of each one is plain to see. Ends with a newline. */
119
+ function lines(...fixtureLines) {
120
+ return `${fixtureLines.join('\n')}\n`;
121
+ }
122
+
123
+ /** What the tool makes of a text, read with the given parsers. */
124
+ function commentOut(sourceText, fileName = 'fixture.ts', withParsers = parsers) {
125
+ return commentOutConsoleLogs(sourceText, fileName, withParsers);
126
+ }
127
+
128
+ /** The text after the tool ran, which must have changed it. */
129
+ function commentedText(sourceText, fileName = 'fixture.ts') {
130
+ const result = commentOut(sourceText, fileName);
131
+ assert.equal(result.status, 'commented', `expected a change, got ${result.status}${result.reason ? ` (${result.reason})` : ''}`);
132
+ return result.updatedText;
133
+ }
134
+
135
+ /** The reasons the tool gave for what it kept, in order. */
136
+ function keptReasons(result) {
137
+ return result.kept.map((finding) => finding.reason);
138
+ }
139
+
140
+ /** Asserts the tool left the text alone because every call in it has to stay, for the given reasons. */
141
+ function assertKept(sourceText, expectedReasons, fileName = 'fixture.ts') {
142
+ const result = commentOut(sourceText, fileName);
143
+ assert.equal(result.status, 'unchanged', `expected no change, got ${result.status}`);
144
+ assert.equal(result.updatedText, sourceText);
145
+ assert.deepEqual(keptReasons(result), expectedReasons);
146
+ }
147
+
148
+ // The fixtures that are also run against every installed pair of parsers.
149
+ const CROSS_VERSION_CASES = [
150
+ {
151
+ name: 'a script with statements, switch cases and a debug switch',
152
+ fileName: 'script.ts',
153
+ input: lines(
154
+ 'const DEBUG_X = false;',
155
+ 'export function sample(items: string[]) {',
156
+ "\tconsole.log('plain', items);",
157
+ "\tconsole.warn('warn');",
158
+ '\tconst mapped = items.map((item) => console.log(item));',
159
+ "\tif (items.length) console.log('braceless');",
160
+ "\tif (DEBUG_X) { console.info('gated'); }",
161
+ '\tswitch (items.length) {',
162
+ '\t\tcase 1:',
163
+ "\t\t\tconsole.trace('in case');",
164
+ '\t\t\tbreak;',
165
+ '\t\tdefault:',
166
+ "\t\t\tconsole.debug('in default');",
167
+ '\t}',
168
+ '\treturn mapped;',
169
+ '}'
170
+ ),
171
+ expected: lines(
172
+ 'const DEBUG_X = false;',
173
+ 'export function sample(items: string[]) {',
174
+ "\t// console.log('plain', items);",
175
+ "\tconsole.warn('warn');",
176
+ '\tconst mapped = items.map((item) => console.log(item));',
177
+ "\tif (items.length) console.log('braceless');",
178
+ "\tif (DEBUG_X) { console.info('gated'); }",
179
+ '\tswitch (items.length) {',
180
+ '\t\tcase 1:',
181
+ "\t\t\t// console.trace('in case');",
182
+ '\t\t\tbreak;',
183
+ '\t\tdefault:',
184
+ "\t\t\t// console.debug('in default');",
185
+ '\t}',
186
+ '\treturn mapped;',
187
+ '}'
188
+ ),
189
+ keptCount: 3
190
+ },
191
+ {
192
+ name: 'a Svelte file with a script, a handler and tags in the markup',
193
+ fileName: 'component.svelte',
194
+ input: lines(
195
+ '<script lang="ts">',
196
+ '\tlet count = $state(0);',
197
+ '\tfunction bump(): void {',
198
+ "\t\tconsole.log('bump', count);",
199
+ '\t\tcount += 1;',
200
+ '\t}',
201
+ '</script>',
202
+ '',
203
+ "<button onclick={() => console.log('click')}>go</button>",
204
+ "{console.log('tag', count)}",
205
+ '{#each [1, 2] as item}',
206
+ "\t{console.debug('item', item)}",
207
+ '\t<p>{item}</p>',
208
+ '{/each}'
209
+ ),
210
+ expected: lines(
211
+ '<script lang="ts">',
212
+ '\tlet count = $state(0);',
213
+ '\tfunction bump(): void {',
214
+ "\t\t// console.log('bump', count);",
215
+ '\t\tcount += 1;',
216
+ '\t}',
217
+ '</script>',
218
+ '',
219
+ "<button onclick={() => console.log('click')}>go</button>",
220
+ "<!-- {console.log('tag', count)} -->",
221
+ '{#each [1, 2] as item}',
222
+ "\t<!-- {console.debug('item', item)} -->",
223
+ '\t<p>{item}</p>',
224
+ '{/each}'
225
+ ),
226
+ keptCount: 1
227
+ }
228
+ ];
229
+
230
+ // ---- The rules, on scripts ----------------------------------------------------------------------------------------
231
+
232
+ describe('what is commented out in a script', () => {
233
+ it('comments out a statement of its own and keeps its indentation', () => {
234
+ const input = lines('function run() {', "\tconsole.log('a');", '\treturn 1;', '}');
235
+ assert.equal(commentedText(input), lines('function run() {', "\t// console.log('a');", '\treturn 1;', '}'));
236
+ });
237
+
238
+ it('comments out log, info, debug and trace, and says which lines', () => {
239
+ const input = lines('function run() {', '\tconsole.log(1);', '\tconsole.info(2);', '\tconsole.debug(3);', '\tconsole.trace(4);', '}');
240
+ const result = commentOut(input);
241
+ assert.equal(result.updatedText, lines('function run() {', '\t// console.log(1);', '\t// console.info(2);', '\t// console.debug(3);', '\t// console.trace(4);', '}'));
242
+ assert.deepEqual(
243
+ result.commented.map((finding) => [finding.line, finding.text]),
244
+ [
245
+ [2, 'console.log(1);'],
246
+ [3, 'console.info(2);'],
247
+ [4, 'console.debug(3);'],
248
+ [5, 'console.trace(4);']
249
+ ]
250
+ );
251
+ });
252
+
253
+ it('comments out a call that spans several lines, line by line, with the indentation inside it kept', () => {
254
+ const input = lines('function run(items) {', '\tconsole.log(', "\t\t'a',", '\t\titems', '\t);', '}');
255
+ assert.equal(commentedText(input), lines('function run(items) {', '\t// console.log(', "\t// \t'a',", '\t// \titems', '\t// );', '}'));
256
+ });
257
+
258
+ it('gives a blank line inside the statement `//` only, and a line that starts further left its own `// `', () => {
259
+ const input = lines('function run() {', '\tconsole.log(`one', '', 'two`);', '}');
260
+ assert.equal(commentedText(input), lines('function run() {', '\t// console.log(`one', '//', '// two`);', '}'));
261
+ });
262
+
263
+ it('gives a line of blanks `//` after its indentation, and keeps the blanks after it', () => {
264
+ const input = lines('function run() {', '\tconsole.log(`one', '\t\t', 'two`);', '}');
265
+ assert.equal(commentedText(input), lines('function run() {', '\t// console.log(`one', '\t//\t', '// two`);', '}'));
266
+ });
267
+
268
+ it('taking the `// ` away gives the original back', () => {
269
+ const input = lines(
270
+ 'function run(items) {',
271
+ '\tconsole.log(',
272
+ "\t\t'a',",
273
+ '',
274
+ '\t\titems',
275
+ '\t);',
276
+ '\tconsole.log(`one',
277
+ '',
278
+ 'two`);',
279
+ "\tconsole.log('b'); // why",
280
+ '\treturn items;',
281
+ '}'
282
+ );
283
+ const restored = commentedText(input)
284
+ .split('\n')
285
+ .map((line) => line.replace(/^(\s*)\/\/ ?/, '$1'))
286
+ .join('\n');
287
+ assert.equal(restored, input);
288
+ });
289
+
290
+ it('keeps the note after the statement', () => {
291
+ const input = lines('function run() {', "\tconsole.log('a'); // why", '}');
292
+ assert.equal(commentedText(input), lines('function run() {', "\t// console.log('a'); // why", '}'));
293
+ });
294
+
295
+ it('comments out a statement in a case and in a default clause, and one at the top of the file', () => {
296
+ const input = lines('switch (kind) {', '\tcase 1:', "\t\tconsole.log('one');", '\t\tbreak;', '\tdefault:', "\t\tconsole.log('other');", '}', "console.log('top');");
297
+ assert.equal(commentedText(input), lines('switch (kind) {', '\tcase 1:', "\t\t// console.log('one');", '\t\tbreak;', '\tdefault:', "\t\t// console.log('other');", '}', "// console.log('top');"));
298
+ });
299
+
300
+ it('comments out a statement in a TypeScript namespace', () => {
301
+ const input = lines('namespace Probe {', "\tconsole.log('in a namespace');", '}');
302
+ assert.equal(commentedText(input), lines('namespace Probe {', "\t// console.log('in a namespace');", '}'));
303
+ });
304
+
305
+ it('comments out an optional call', () => {
306
+ const input = lines('function run() {', '\tconsole?.log(1);', '}');
307
+ assert.equal(commentedText(input), lines('function run() {', '\t// console?.log(1);', '}'));
308
+ });
309
+
310
+ it('puts a statement that shares its line with other code between /* and */', () => {
311
+ const input = lines("if (ok) { console.log('a'); }", "first(); console.log('b'); last();");
312
+ assert.equal(commentedText(input), lines("if (ok) { /* console.log('a'); */ }", "first(); /* console.log('b'); */ last();"));
313
+ });
314
+
315
+ it('comments out a statement that holds `*/` when it stands alone on its lines, because a `//` comment is not ended by it', () => {
316
+ const input = lines('function run() {', "\tconsole.log('x' /* why */);", '}');
317
+ assert.equal(commentedText(input), lines('function run() {', "\t// console.log('x' /* why */);", '}'));
318
+ });
319
+
320
+ it('puts a statement between /* and */ when an empty statement follows it, even at the very end of the file', () => {
321
+ assert.equal(commentedText("console.log('x');;"), "/* console.log('x'); */;");
322
+ });
323
+
324
+ it('comments out a statement in a class static block', () => {
325
+ assert.equal(commentedText(lines('class Probe {', '\tstatic {', "\t\tconsole.log('init');", '\t}', '}')), lines('class Probe {', '\tstatic {', "\t\t// console.log('init');", '\t}', '}'));
326
+ });
327
+
328
+ it('keeps a statement that shares its line with other code and holds `*/`, and says so', () => {
329
+ assertKept("first(); console.log('x' /* why */); last();\n", [KEPT_REASONS.holdsCommentEnd]);
330
+ });
331
+
332
+ it('keeps a statement that holds a line separator character, which would end a `//` comment early', () => {
333
+ const input = `function run() {\n\tconsole.log('a\u2028b');\n}\n`;
334
+ assertKept(input, [KEPT_REASONS.holdsLineSeparator]);
335
+ });
336
+
337
+ it('leaves CRLF endings as they are, in a statement and in a note after it', () => {
338
+ const input = ['function run() {', '\tconsole.log(1); // note', '\tconsole.log(', '\t\t2', '\t);', '\treturn 1;', '}', ''].join('\r\n');
339
+ const expected = ['function run() {', '\t// console.log(1); // note', '\t// console.log(', '\t// \t2', '\t// );', '\treturn 1;', '}', ''].join('\r\n');
340
+ assert.equal(commentedText(input), expected);
341
+ });
342
+
343
+ it('never leaves a bare line feed in a CRLF file, blank lines inside a statement included', () => {
344
+ const input = ['function run() {', '\tconsole.log(`one', '', 'two`);', '}', ''].join('\r\n');
345
+ const updatedText = commentedText(input);
346
+ assert.equal(updatedText.replace(/\r\n/g, '').includes('\n'), false);
347
+ assert.equal(updatedText.replace(/\r\n/g, '').includes('\r'), false);
348
+ // The blank line is `//` and nothing else before its line ending, as it is with line feeds.
349
+ assert.equal(updatedText, ['function run() {', '\t// console.log(`one', '//', '// two`);', '}', ''].join('\r\n'));
350
+ });
351
+
352
+ it('reads .js, .mjs, .cjs, .jsx, .tsx and .svelte.ts files as the kind of code they are', () => {
353
+ const statement = lines('function run() {', "\tconsole.log('a');", '}');
354
+ const commented = lines('function run() {', "\t// console.log('a');", '}');
355
+ for (const fileName of ['a.js', 'a.mjs', 'a.cjs', 'a.mts', 'a.cts', 'store.svelte.ts']) {
356
+ assert.equal(commentedText(statement, fileName), commented, fileName);
357
+ }
358
+ assert.equal(commentedText(lines('const view = <div />;', "console.log('jsx');"), 'a.jsx'), lines('const view = <div />;', "// console.log('jsx');"));
359
+ assert.equal(commentedText(lines('const pick = <T,>(value: T) => value;', "console.log('tsx');"), 'a.tsx'), lines('const pick = <T,>(value: T) => value;', "// console.log('tsx');"));
360
+ });
361
+
362
+ it('reads a .tsx file with the TypeScript that is only valid there, which a plain script reading would call broken', () => {
363
+ // `useCallback<() => void>(...)` is a type argument in .ts and .tsx, and three parse errors in a .js or .jsx reading.
364
+ // (.js and .jsx are read alike by the TypeScript parser, both with JSX, so no input tells them apart.)
365
+ const input = lines('const onClick = useCallback<() => void>(() => {', "\tconsole.log('tsx');", '}, []);');
366
+ const result = commentOut(input, 'a.tsx');
367
+ assert.equal(result.status, 'commented');
368
+ assert.equal(result.updatedText, lines('const onClick = useCallback<() => void>(() => {', "\t// console.log('tsx');", '}, []);'));
369
+ assert.equal(commentOut(input, 'a.ts').status, 'commented');
370
+ assert.equal(commentOut(input, 'a.js').status, 'left alone');
371
+ });
372
+ });
373
+
374
+ describe('what stays in a script, and why', () => {
375
+ it('never touches warn, error or the other console methods', () => {
376
+ const input = lines('function run() {', "\tconsole.warn('w');", "\tconsole.error('e');", '\tconsole.table([1]);', "\tconsole.group('g');", "\tconsole.time('t');", '}');
377
+ const result = commentOut(input);
378
+ assert.equal(result.status, 'unchanged');
379
+ assert.equal(result.kept.length, 0);
380
+ assert.equal(result.commented.length, 0);
381
+ });
382
+
383
+ it('does not mistake a string, a template literal or a comment for a call', () => {
384
+ const input = lines('const a = "console.log(\'x\')";', "const b = `console.log('y') ${1}`;", "// console.log('z');", "/* console.log('w'); */", "const c = 'console.info(1)';");
385
+ assert.deepEqual(findConsoleCalls(input, 'fixture.ts', parsers).findings, []);
386
+ assert.equal(commentOut(input).status, 'unchanged');
387
+ });
388
+
389
+ it('does not read console[method] as a call it knows: the method is a name only at run time', () => {
390
+ const input = lines("const method = 'log';", "console[method]('x');", "console['log']('y');");
391
+ assert.deepEqual(findConsoleCalls(input, 'fixture.ts', parsers).findings, []);
392
+ assert.equal(commentOut(input).status, 'unchanged');
393
+ });
394
+
395
+ it('keeps the body of a braceless if, else, for, while, do and label, so no statement changes hands', () => {
396
+ const input = lines(
397
+ "if (a) console.log('if');",
398
+ "if (a) { run(); } else console.log('else');",
399
+ "for (const item of items) console.log('for', item);",
400
+ "while (a) console.log('while');",
401
+ "do console.log('do'); while (a);",
402
+ "label: console.log('label');"
403
+ );
404
+ assertKept(input, Array(6).fill(KEPT_REASONS.bracelessBody));
405
+ });
406
+
407
+ it('keeps a call that is a value, or handed over as a function', () => {
408
+ const input = lines(
409
+ 'function run(ok, promise) {',
410
+ '\tok && console.log(1);',
411
+ '\tconst log = () => console.log(2);',
412
+ '\tpromise.catch(console.log);',
413
+ '\tconst handedOver = console.info;',
414
+ '\tvoid console.debug(3);',
415
+ '\treturn console.trace(4);',
416
+ '}'
417
+ );
418
+ assertKept(input, [
419
+ KEPT_REASONS.usedAsValue,
420
+ KEPT_REASONS.usedAsValue,
421
+ KEPT_REASONS.handedOver,
422
+ KEPT_REASONS.handedOver,
423
+ KEPT_REASONS.usedAsValue,
424
+ KEPT_REASONS.usedAsValue
425
+ ]);
426
+ });
427
+
428
+ it('keeps a statement behind a debug switch, braceless or not, nested or not, whatever the switch is called', () => {
429
+ const input = lines(
430
+ 'function run(items) {',
431
+ "\tif (DEBUG_PANEL) { console.log('block'); }",
432
+ "\tif (debugMode) console.debug('braceless');",
433
+ '\tif (isDebugEnabled()) {',
434
+ '\t\tfor (const item of items) {',
435
+ "\t\t\tconsole.log('nested', item);",
436
+ '\t\t}',
437
+ '\t}',
438
+ '}'
439
+ );
440
+ assertKept(input, Array(3).fill(KEPT_REASONS.debugSwitch));
441
+ });
442
+
443
+ it('comments out the else side of a debug switch: the switch still decides what the then side does', () => {
444
+ const input = lines('function run() {', '\tif (DEBUG_X) {', "\t\tconsole.log('on');", '\t} else {', "\t\tconsole.log('off');", '\t}', '}');
445
+ const result = commentOut(input);
446
+ assert.equal(result.updatedText, lines('function run() {', '\tif (DEBUG_X) {', "\t\tconsole.log('on');", '\t} else {', "\t\t// console.log('off');", '\t}', '}'));
447
+ assert.deepEqual(keptReasons(result), [KEPT_REASONS.debugSwitch]);
448
+ });
449
+
450
+ it('comments out a statement in a function inside a debug switch: the function runs when it is called, not when the switch is on', () => {
451
+ const input = lines('if (DEBUG_X) {', '\tregister(() => {', "\t\tconsole.log('called');", '\t});', '}');
452
+ assert.equal(commentedText(input), lines('if (DEBUG_X) {', '\tregister(() => {', "\t\t// console.log('called');", '\t});', '}'));
453
+ });
454
+
455
+ it('does not take an `if` that is not a debug switch for one', () => {
456
+ const input = lines('function run(debuggable) {', '\tif (debuggable) {', "\t\tconsole.log('x');", '\t}', '}');
457
+ assert.equal(commentedText(input), lines('function run(debuggable) {', '\tif (debuggable) {', "\t\t// console.log('x');", '\t}', '}'));
458
+ });
459
+ });
460
+
461
+ describe('calls inside calls', () => {
462
+ it('comments out a statement inside the arguments of a call that is commented out once, with its outer statement', () => {
463
+ const input = lines('function run(items) {', '\tconsole.log(items.map((item) => {', '\t\tconsole.log(item);', '\t\treturn item;', '\t}));', '}');
464
+ const result = commentOut(input);
465
+ assert.equal(result.updatedText, lines('function run(items) {', '\t// console.log(items.map((item) => {', '\t// \tconsole.log(item);', '\t// \treturn item;', '\t// }));', '}'));
466
+ assert.equal(result.commented.length, 1);
467
+ assert.equal(result.commentedAlong, 1);
468
+ assert.equal(result.kept.length, 0);
469
+ });
470
+
471
+ it('does not list a kept call that sits inside a statement that is commented out', () => {
472
+ const input = lines('function run(ok) {', "\tconsole.log(ok && console.log('inner'));", '}');
473
+ const result = commentOut(input);
474
+ assert.equal(result.updatedText, lines('function run(ok) {', "\t// console.log(ok && console.log('inner'));", '}'));
475
+ assert.equal(result.commentedAlong, 1);
476
+ assert.deepEqual(result.kept, []);
477
+ });
478
+
479
+ it('comments out an inner statement when its outer statement has to stay', () => {
480
+ const input = lines('function run(items) {', '\tfirst(); console.log(items.map((item) => { /* why */', '\t\tconsole.log(item);', '\t\treturn item;', '\t}));', '}');
481
+ const result = commentOut(input);
482
+ assert.equal(result.updatedText, lines('function run(items) {', '\tfirst(); console.log(items.map((item) => { /* why */', '\t\t// console.log(item);', '\t\treturn item;', '\t}));', '}'));
483
+ assert.deepEqual(keptReasons(result), [KEPT_REASONS.holdsCommentEnd]);
484
+ assert.equal(result.commented.length, 1);
485
+ });
486
+ });
487
+
488
+ describe('what the tool says about a file', () => {
489
+ it('says the line of each statement and the call on one line, cut at 110 characters', () => {
490
+ const longArgument = 'x'.repeat(200);
491
+ const input = lines('function run() {', '', `\tconsole.log('${longArgument}');`, '}');
492
+ const [finding] = commentOut(input).commented;
493
+ assert.equal(finding.line, 3);
494
+ assert.equal(finding.text.length, 110);
495
+ assert.ok(finding.text.startsWith("console.log('xxx"));
496
+ });
497
+
498
+ it('counts the lines from the start of the file, a statement at the start of a line included', () => {
499
+ const input = lines('first();', 'second();', "console.log('third');", "\tconsole.log('fourth');");
500
+ assert.deepEqual(
501
+ commentOut(input).commented.map((finding) => finding.line),
502
+ [3, 4]
503
+ );
504
+ });
505
+
506
+ it('shows a call that spans lines on one line, the blanks between its words collapsed', () => {
507
+ const input = lines('function run(items) {', '\tconsole.log(', "\t\t'a',", '\t\titems', '\t);', '}');
508
+ assert.equal(commentOut(input).commented[0].text, "console.log( 'a', items );");
509
+ });
510
+
511
+ it('finds nothing more to do in its own result', () => {
512
+ const input = lines('function run() {', "\tconsole.log('a');", "\tif (x) console.log('b');", '}');
513
+ const firstRun = commentOut(input);
514
+ const secondRun = commentOut(firstRun.updatedText);
515
+ assert.equal(secondRun.status, 'unchanged');
516
+ assert.equal(secondRun.updatedText, firstRun.updatedText);
517
+ assert.deepEqual(keptReasons(secondRun), keptReasons(firstRun));
518
+ });
519
+
520
+ it('leaves a file that does not parse alone, and says why', () => {
521
+ const result = commentOut("function run( {\n\tconsole.log('a');\n");
522
+ assert.equal(result.status, 'left alone');
523
+ assert.match(result.reason, /parse error/);
524
+ assert.equal(result.updatedText, "function run( {\n\tconsole.log('a');\n");
525
+ assert.deepEqual(result.commented, []);
526
+ });
527
+
528
+ it('leaves a Svelte file that is not valid alone, and says why', () => {
529
+ const input = '<script>\n\tlet a = ;\n\tconsole.log(a);\n</script>\n';
530
+ const result = commentOut(input, 'broken.svelte');
531
+ assert.equal(result.status, 'left alone');
532
+ assert.match(result.reason, /could not read it as code/);
533
+ assert.equal(result.updatedText, input);
534
+ });
535
+
536
+ it('is a no-op for an empty file', () => {
537
+ for (const fileName of ['empty.ts', 'empty.svelte']) {
538
+ const result = commentOut('', fileName);
539
+ assert.equal(result.status, 'unchanged', fileName);
540
+ assert.equal(result.updatedText, '');
541
+ }
542
+ });
543
+
544
+ it('names the parser that is missing instead of calling the file broken', () => {
545
+ assert.throws(() => commentOutConsoleLogs('console.log(1);\n', 'a.ts', {}), { code: 'PARSER_NOT_LOADED', message: /typescript was not loaded/ });
546
+ assert.throws(() => commentOutConsoleLogs('<p />\n', 'a.svelte', { typescript: parsers.typescript }), { code: 'PARSER_NOT_LOADED', message: /svelte\/compiler was not loaded/ });
547
+ });
548
+
549
+ it('reads its result again: a text that no longer parses, one with a statement still to comment out, or one whose kept calls changed, does not check out', () => {
550
+ const expected = { skippedCount: 0, keptCount: 0 };
551
+ const brokenResult = checkCommentedText('function run( {\n', 'a.ts', parsers, expected);
552
+ assert.equal(brokenResult.ok, false);
553
+ assert.match(brokenResult.reason, /parse error/);
554
+
555
+ const statementLeft = checkCommentedText("console.log('x');\n", 'a.ts', parsers, expected);
556
+ assert.equal(statementLeft.ok, false);
557
+ assert.match(statementLeft.reason, /still to comment out/);
558
+
559
+ const keptChanged = checkCommentedText("if (a) console.log('x');\n", 'a.ts', parsers, expected);
560
+ assert.equal(keptChanged.ok, false);
561
+ assert.match(keptChanged.reason, /kept in the result/);
562
+
563
+ assert.deepEqual(checkCommentedText("// console.log('x');\n", 'a.ts', parsers, expected), { ok: true });
564
+ assert.deepEqual(checkCommentedText("if (a) console.log('x');\n", 'a.ts', parsers, { skippedCount: 0, keptCount: 1 }), { ok: true });
565
+ assert.deepEqual(checkCommentedText("first(); console.log(1 /* x */); last();\n", 'a.ts', parsers, { skippedCount: 1, keptCount: 0 }), { ok: true });
566
+ });
567
+
568
+ it('leaves a file alone when the result it made does not read as code, and says why', () => {
569
+ let reads = 0;
570
+ const parsersThatFindTheResultBroken = {
571
+ ...parsers,
572
+ typescript: {
573
+ ...parsers.typescript,
574
+ // The second read of a text is the check of the result: report a parse error there, as a change that broke the file would.
575
+ createSourceFile: (...readArguments) => {
576
+ const sourceFile = parsers.typescript.createSourceFile(...readArguments);
577
+ reads += 1;
578
+ if (reads === 2) sourceFile.parseDiagnostics.push({ messageText: 'made up for the test' });
579
+ return sourceFile;
580
+ }
581
+ }
582
+ };
583
+ const input = lines('function run() {', "\tconsole.log('a');", '}');
584
+ const result = commentOutConsoleLogs(input, 'a.ts', parsersThatFindTheResultBroken);
585
+ assert.equal(result.status, 'left alone');
586
+ assert.match(result.reason, /the result has 1 parse error/);
587
+ assert.equal(result.updatedText, input);
588
+ assert.deepEqual(result.commented, []);
589
+ });
590
+
591
+ it('does not call a file broken when the parser it needs is missing while it checks the result', () => {
592
+ assert.throws(() => checkCommentedText('x;\n', 'a.ts', {}, { skippedCount: 0, keptCount: 0 }), { code: 'PARSER_NOT_LOADED' });
593
+ });
594
+
595
+ it('applies edits last one first, so the offsets of the others stay right', () => {
596
+ assert.equal(
597
+ applyEdits('aaa bbb ccc', [
598
+ { start: 0, end: 3, replacement: 'A' },
599
+ { start: 8, end: 11, replacement: 'CCCC' }
600
+ ]),
601
+ 'A bbb CCCC'
602
+ );
603
+ });
604
+
605
+ it('plans nothing for a template tag that holds `-->`, and a comment for one that does not', () => {
606
+ const tag = { start: 0, end: 18, line: 1, shape: 'template tag', action: 'comment', text: '' };
607
+ assert.deepEqual(planEdit("{console.log('-->')}", { ...tag, end: 20 }), { skip: KEPT_REASONS.holdsHtmlCommentEnd });
608
+ assert.deepEqual(planEdit("{console.log('ok')}", { ...tag, end: 19 }), { start: 0, end: 19, replacement: "<!-- {console.log('ok')} -->" });
609
+ });
610
+ });
611
+
612
+ // ---- The rules, on Svelte files -----------------------------------------------------------------------------------
613
+
614
+ describe('Svelte files', () => {
615
+ it('comments out the statements of the scripts and the standalone tags of the markup', () => {
616
+ const input = lines(
617
+ '<script module>',
618
+ "\tconsole.log('module');",
619
+ '</script>',
620
+ '',
621
+ '<script lang="ts">',
622
+ '\tlet count = $state(0);',
623
+ '\t$effect(() => {',
624
+ "\t\tconsole.info('effect', count);",
625
+ '\t});',
626
+ '</script>',
627
+ '',
628
+ "{console.log('tag', count)}",
629
+ '{#if count > 1}',
630
+ "\t{console.debug('big')}",
631
+ '{/if}'
632
+ );
633
+ assert.equal(
634
+ commentedText(input, 'a.svelte'),
635
+ lines(
636
+ '<script module>',
637
+ "\t// console.log('module');",
638
+ '</script>',
639
+ '',
640
+ '<script lang="ts">',
641
+ '\tlet count = $state(0);',
642
+ '\t$effect(() => {',
643
+ "\t\t// console.info('effect', count);",
644
+ '\t});',
645
+ '</script>',
646
+ '',
647
+ "<!-- {console.log('tag', count)} -->",
648
+ '{#if count > 1}',
649
+ "\t<!-- {console.debug('big')} -->",
650
+ '{/if}'
651
+ )
652
+ );
653
+ });
654
+
655
+ it('lists the findings in the order they stand in the file, markup before or after the script', () => {
656
+ const input = lines("{console.log('tag')}", '<script>', "\tconsole.log('script');", '</script>');
657
+ assert.deepEqual(
658
+ commentOut(input, 'a.svelte').commented.map((finding) => finding.line),
659
+ [1, 3]
660
+ );
661
+ // The parser's tree holds the markup apart from the scripts, so each order has to be put right on its own.
662
+ const scriptFirst = lines('<script>', "\tconsole.log('script');", '</script>', "{console.log('tag')}");
663
+ assert.deepEqual(
664
+ commentOut(scriptFirst, 'a.svelte').commented.map((finding) => finding.line),
665
+ [2, 4]
666
+ );
667
+ });
668
+
669
+ it('comments out a multi-line tag as one HTML comment', () => {
670
+ const input = lines('{#each items as item}', "\t{console.log('item', item, {", '\t\tdeep: true', '\t})}', '{/each}');
671
+ assert.equal(commentedText(input, 'a.svelte'), lines('{#each items as item}', "\t<!-- {console.log('item', item, {", '\t\tdeep: true', '\t})} -->', '{/each}'));
672
+ });
673
+
674
+ it('keeps a tag inside an attribute: a comment cannot go there', () => {
675
+ assertKept("<p title={console.log('x')}>hi</p>\n", [KEPT_REASONS.insideAttribute], 'a.svelte');
676
+ });
677
+
678
+ it('keeps a handler whose body is the call, and comments out a statement in a handler with a block', () => {
679
+ const input = lines("<button onclick={() => console.log('a')}>a</button>", "<button onclick={() => { console.log('b'); save(); }}>b</button>");
680
+ const result = commentOut(input, 'a.svelte');
681
+ assert.equal(result.updatedText, lines("<button onclick={() => console.log('a')}>a</button>", "<button onclick={() => { /* console.log('b'); */ save(); }}>b</button>"));
682
+ assert.deepEqual(keptReasons(result), [KEPT_REASONS.usedAsValue]);
683
+ });
684
+
685
+ it('keeps a tag that holds `-->`, and says so', () => {
686
+ assertKept("{console.log('-->')}\n", [KEPT_REASONS.holdsHtmlCommentEnd], 'a.svelte');
687
+ });
688
+
689
+ it('keeps a statement and a tag behind a debug switch, comments out the else side and a function inside the switch', () => {
690
+ const input = lines(
691
+ '<script>',
692
+ '\tconst DEBUG_Z = false;',
693
+ '\tfunction quiet() {',
694
+ "\t\tif (DEBUG_Z) console.log('gated braceless');",
695
+ "\t\tif (DEBUG_Z) { console.log('gated block'); }",
696
+ '\t}',
697
+ '\tif (DEBUG_Z) {',
698
+ "\t\tregister(() => { console.log('called'); });",
699
+ '\t}',
700
+ '</script>',
701
+ '',
702
+ '{#if debugMode}',
703
+ "\t{console.log('on')}",
704
+ '{:else}',
705
+ "\t{console.log('off')}",
706
+ '{/if}'
707
+ );
708
+ const result = commentOut(input, 'a.svelte');
709
+ assert.equal(
710
+ result.updatedText,
711
+ lines(
712
+ '<script>',
713
+ '\tconst DEBUG_Z = false;',
714
+ '\tfunction quiet() {',
715
+ "\t\tif (DEBUG_Z) console.log('gated braceless');",
716
+ "\t\tif (DEBUG_Z) { console.log('gated block'); }",
717
+ '\t}',
718
+ '\tif (DEBUG_Z) {',
719
+ "\t\tregister(() => { /* console.log('called'); */ });",
720
+ '\t}',
721
+ '</script>',
722
+ '',
723
+ '{#if debugMode}',
724
+ "\t{console.log('on')}",
725
+ '{:else}',
726
+ "\t<!-- {console.log('off')} -->",
727
+ '{/if}'
728
+ )
729
+ );
730
+ assert.deepEqual(keptReasons(result), Array(3).fill(KEPT_REASONS.debugSwitch));
731
+ });
732
+
733
+ it('keeps the braceless body of a control statement in a script', () => {
734
+ assertKept(lines('<script>', "\tif (a) console.log('x');", '</script>'), [KEPT_REASONS.bracelessBody], 'a.svelte');
735
+ });
736
+
737
+ it('does not touch {@debug}, text that says console.log, or an attribute that says it', () => {
738
+ const input = lines('<script>', '\tlet count = 1;', '</script>', '', '{@debug count}', "<p>console.log('x') is text</p>", '<p class="console.log(1)">y</p>');
739
+ const result = commentOut(input, 'a.svelte');
740
+ assert.equal(result.status, 'unchanged');
741
+ assert.deepEqual(result.kept, []);
742
+ });
743
+
744
+ it('comments out the statements of a switch and of a class static block in a script', () => {
745
+ const input = lines(
746
+ '<script>',
747
+ '\tswitch (kind) {',
748
+ '\t\tcase 1:',
749
+ "\t\t\tconsole.log('one');",
750
+ '\t\t\tbreak;',
751
+ '\t\tdefault:',
752
+ "\t\t\tconsole.log('other');",
753
+ '\t}',
754
+ "\tclass Probe { static { console.log('init'); } }",
755
+ '</script>'
756
+ );
757
+ assert.equal(
758
+ commentedText(input, 'a.svelte'),
759
+ lines(
760
+ '<script>',
761
+ '\tswitch (kind) {',
762
+ '\t\tcase 1:',
763
+ "\t\t\t// console.log('one');",
764
+ '\t\t\tbreak;',
765
+ '\t\tdefault:',
766
+ "\t\t\t// console.log('other');",
767
+ '\t}',
768
+ "\tclass Probe { static { /* console.log('init'); */ } }",
769
+ '</script>'
770
+ )
771
+ );
772
+ });
773
+
774
+ it('comments out a tag in a snippet inside a debug switch: the snippet runs when it is rendered, not when the switch is on', () => {
775
+ const input = lines('{#if debugMode}', '\t{#snippet row()}', "\t\t{console.log('in snippet')}", '\t{/snippet}', '{/if}');
776
+ assert.equal(commentedText(input, 'a.svelte'), lines('{#if debugMode}', '\t{#snippet row()}', "\t\t<!-- {console.log('in snippet')} -->", '\t{/snippet}', '{/if}'));
777
+ });
778
+
779
+ it('does not read console[method] as a call it knows', () => {
780
+ const input = lines('<script>', "\tconst log = 'log';", "\tconsole[log]('x');", '</script>');
781
+ assert.deepEqual(findConsoleCalls(input, 'a.svelte', parsers).findings, []);
782
+ });
783
+
784
+ it('keeps a statement whose position the parser gave wrongly, instead of cutting out something else', () => {
785
+ const sourceText = 'let a = 1;\nconsole.log(a);\n';
786
+ const consoleLogCall = {
787
+ type: 'CallExpression',
788
+ callee: { type: 'MemberExpression', computed: false, object: { type: 'Identifier', name: 'console' }, property: { type: 'Identifier', name: 'log' } },
789
+ arguments: []
790
+ };
791
+ const fakeSvelteCompiler = {
792
+ parse: () => ({
793
+ type: 'Root',
794
+ fragment: { type: 'Fragment', nodes: [] },
795
+ instance: { type: 'Script', content: { type: 'Program', body: [{ type: 'ExpressionStatement', start: 0, end: 10, expression: consoleLogCall }] } }
796
+ })
797
+ };
798
+ const result = commentOutConsoleLogs(sourceText, 'fake.svelte', { svelteCompiler: fakeSvelteCompiler });
799
+ assert.equal(result.status, 'unchanged');
800
+ assert.deepEqual(keptReasons(result), [KEPT_REASONS.wrongPosition]);
801
+ });
802
+
803
+ it('handles a one-line script', () => {
804
+ assert.equal(commentedText("<script>console.log('a')</script>\n", 'a.svelte'), "<script>/* console.log('a') */</script>\n");
805
+ });
806
+ });
807
+
808
+ // ---- Parsers and files --------------------------------------------------------------------------------------------
809
+
810
+ describe('loading the parsers', () => {
811
+ it('loads what is asked for and nothing else', () => {
812
+ const onlyTypescript = loadParsers(parserHosts[0].directory, { typescript: true });
813
+ assert.ok(onlyTypescript.typescript);
814
+ assert.equal(onlyTypescript.svelteCompiler, undefined);
815
+ const onlySvelte = loadParsers(parserHosts[0].directory, { svelte: true });
816
+ assert.ok(onlySvelte.svelteCompiler);
817
+ assert.equal(onlySvelte.typescript, undefined);
818
+ });
819
+
820
+ it('names what it could not load and where it looked', () => {
821
+ const emptyDirectory = makeTemporaryDirectory('no-parsers');
822
+ assert.throws(() => loadParsers(emptyDirectory), (error) => {
823
+ assert.match(error.message, /could not load typescript and svelte from /);
824
+ assert.ok(error.message.includes(emptyDirectory));
825
+ return true;
826
+ });
827
+ assert.throws(() => loadParsers(emptyDirectory, { svelte: true }), /could not load svelte from /);
828
+ });
829
+
830
+ it('says which parsers the files need', () => {
831
+ assert.deepEqual(parsersNeededFor(['a.ts', 'b.mjs']), { typescript: true, svelte: false });
832
+ assert.deepEqual(parsersNeededFor(['a.svelte']), { typescript: false, svelte: true });
833
+ assert.deepEqual(parsersNeededFor(['a.ts', 'b.svelte']), { typescript: true, svelte: true });
834
+ assert.deepEqual(parsersNeededFor([]), { typescript: false, svelte: false });
835
+ });
836
+
837
+ it('knows the files it reads', () => {
838
+ for (const name of ['a.ts', 'a.mts', 'a.cts', 'a.tsx', 'a.js', 'a.mjs', 'a.cjs', 'a.jsx', 'a.svelte', 'A.TS', 'store.svelte.ts']) assert.equal(isSourceFile(name), true, name);
839
+ for (const name of ['a.css', 'a.json', 'a.md', 'a', 'a.html']) assert.equal(isSourceFile(name), false, name);
840
+ });
841
+ });
842
+
843
+ describe('finding the files to read', () => {
844
+ it('takes a file as it is, walks a directory in name order, and does not enter what a checkout keeps its output and packages in', () => {
845
+ const root = makeTemporaryDirectory('walk');
846
+ const write = (relativePath, text = '') => {
847
+ mkdirSync(dirname(join(root, relativePath)), { recursive: true });
848
+ writeFileSync(join(root, relativePath), text);
849
+ };
850
+ write('src/b.svelte');
851
+ write('src/a.ts');
852
+ write('src/deep/d.mjs');
853
+ write('src/style.css');
854
+ write('node_modules/pkg/index.js');
855
+ write('dist/built.js');
856
+ write('build/built.js');
857
+ write('.svelte-kit/generated.js');
858
+ write('.git/hooks/pre-commit.js');
859
+ write('coverage/report.js');
860
+ write('.output/server.js');
861
+ const { files, problems } = collectSourceFiles([join(root, 'src')]);
862
+ assert.deepEqual(
863
+ files,
864
+ [join(root, 'src/a.ts'), join(root, 'src/b.svelte'), join(root, 'src/deep/d.mjs')]
865
+ );
866
+ assert.deepEqual(problems, []);
867
+
868
+ // A directory named on the command line is entered whatever it is called, but not the ones inside it that are skipped.
869
+ assert.deepEqual(collectSourceFiles([join(root, 'dist')]).files, [join(root, 'dist/built.js')]);
870
+ // Scanning the whole root skips every one of them.
871
+ assert.deepEqual(collectSourceFiles([root]).files, [join(root, 'src/a.ts'), join(root, 'src/b.svelte'), join(root, 'src/deep/d.mjs')]);
872
+ });
873
+
874
+ it('names a path that is not there and a file it does not read, and reads each file once', () => {
875
+ const root = makeTemporaryDirectory('paths');
876
+ writeFileSync(join(root, 'a.ts'), '');
877
+ writeFileSync(join(root, 'notes.md'), '');
878
+ const { files, problems } = collectSourceFiles([join(root, 'a.ts'), root, join(root, 'missing.ts'), join(root, 'notes.md')]);
879
+ assert.deepEqual(files, [join(root, 'a.ts')]);
880
+ assert.deepEqual(
881
+ problems.map((problem) => [problem.path.replace(root, '<root>'), problem.reason.split(' (')[0]]),
882
+ [
883
+ ['<root>/missing.ts', 'not found'],
884
+ ['<root>/notes.md', 'not a kind of file this tool reads']
885
+ ]
886
+ );
887
+ });
888
+
889
+ it('does not follow a link', () => {
890
+ const root = makeTemporaryDirectory('links');
891
+ mkdirSync(join(root, 'real'));
892
+ writeFileSync(join(root, 'real/a.ts'), '');
893
+ symlinkSync(join(root, 'real'), join(root, 'linked'));
894
+ symlinkSync(root, join(root, 'real/loop'));
895
+ symlinkSync(join(root, 'real/a.ts'), join(root, 'real/alias.ts'));
896
+ assert.deepEqual(collectSourceFiles([root]).files, [join(root, 'real/a.ts')]);
897
+ });
898
+ });
899
+
900
+ // ---- The command ---------------------------------------------------------------------------------------------------
901
+
902
+ /** Runs the command with the parsers of the first host unless the test says otherwise. */
903
+ function runCommand(args, options = {}) {
904
+ const resolveFromArguments = options.resolveFrom === null ? [] : ['--resolve-from', options.resolveFrom ?? parserHosts[0].directory];
905
+ const run = spawnSync(process.execPath, [BIN, ...resolveFromArguments, ...args], { encoding: 'utf8', cwd: options.cwd, maxBuffer: 64 * 1024 * 1024 });
906
+ return { status: run.status, stdout: run.stdout, stderr: run.stderr };
907
+ }
908
+
909
+ describe('the command', () => {
910
+ const sourceWithOneStatement = lines('function run() {', "\tconsole.log('a');", '}');
911
+
912
+ it('reports and leaves every file as it is unless it is told to write', () => {
913
+ const root = makeTemporaryDirectory('dry');
914
+ const filePath = join(root, 'a.ts');
915
+ writeFileSync(filePath, sourceWithOneStatement);
916
+ const run = runCommand([filePath]);
917
+ assert.equal(run.status, 0, run.stderr);
918
+ assert.match(run.stdout, /dry run: no file is touched/);
919
+ assert.match(run.stdout, new RegExp(`comment ${escapeRegExp(filePath)}:2 ${escapeRegExp("console.log('a');")}`));
920
+ assert.match(run.stdout, /Would comment out: 1 in 1 file\. Kept: 0\./);
921
+ assert.equal(readFileSync(filePath, 'utf8'), sourceWithOneStatement);
922
+ });
923
+
924
+ it('writes the changes with --write, and then has nothing left to do', () => {
925
+ const root = makeTemporaryDirectory('write');
926
+ const filePath = join(root, 'a.ts');
927
+ writeFileSync(filePath, sourceWithOneStatement);
928
+ const run = runCommand(['--write', filePath]);
929
+ assert.equal(run.status, 0, run.stderr);
930
+ assert.match(run.stdout, /writing the changes/);
931
+ assert.match(run.stdout, /Commented out: 1 in 1 file\./);
932
+ assert.equal(readFileSync(filePath, 'utf8'), lines('function run() {', "\t// console.log('a');", '}'));
933
+ const secondRun = runCommand([filePath]);
934
+ assert.match(secondRun.stdout, /Would comment out: 0 in 0 files\. Kept: 0\./);
935
+ });
936
+
937
+ it('does not rewrite a file that has nothing to comment out', () => {
938
+ const root = makeTemporaryDirectory('untouched');
939
+ const filePath = join(root, 'a.ts');
940
+ writeFileSync(filePath, "console.warn('w');\n");
941
+ const modifiedBefore = statSync(filePath).mtimeMs;
942
+ const run = runCommand(['--write', filePath]);
943
+ assert.equal(run.status, 0, run.stderr);
944
+ assert.equal(statSync(filePath).mtimeMs, modifiedBefore);
945
+ });
946
+
947
+ it('walks a directory, skips what a checkout keeps its output in, and counts the files that change', () => {
948
+ const root = makeTemporaryDirectory('tree');
949
+ mkdirSync(join(root, 'src'));
950
+ mkdirSync(join(root, 'node_modules'));
951
+ writeFileSync(join(root, 'src/a.ts'), sourceWithOneStatement);
952
+ writeFileSync(join(root, 'src/b.svelte'), lines('<script>', "\tconsole.log('b');", '</script>'));
953
+ writeFileSync(join(root, 'src/c.ts'), "console.warn('c');\n");
954
+ writeFileSync(join(root, 'node_modules/d.js'), "console.log('d');\n");
955
+ const run = runCommand(['--write', root]);
956
+ assert.equal(run.status, 0, run.stderr);
957
+ assert.match(run.stdout, /Commented out: 2 in 2 files\. Kept: 0\./);
958
+ assert.equal(readFileSync(join(root, 'node_modules/d.js'), 'utf8'), "console.log('d');\n");
959
+ assert.match(readFileSync(join(root, 'src/b.svelte'), 'utf8'), /\/\/ console\.log\('b'\);/);
960
+ });
961
+
962
+ it('says how many more calls went with the statements they sit inside', () => {
963
+ const root = makeTemporaryDirectory('along');
964
+ const filePath = join(root, 'a.ts');
965
+ writeFileSync(filePath, lines('function run(items) {', '\tconsole.log(items.map((item) => {', '\t\tconsole.log(item);', '\t\treturn item;', '\t}));', '}'));
966
+ const run = runCommand([filePath]);
967
+ assert.equal(run.status, 0, run.stderr);
968
+ assert.match(run.stdout, /Would comment out: 1 \(1 more inside them\) in 1 file\. Kept: 0\./);
969
+ });
970
+
971
+ it('lists what it kept, with the reason, after the counts', () => {
972
+ const root = makeTemporaryDirectory('kept');
973
+ const filePath = join(root, 'a.ts');
974
+ writeFileSync(filePath, lines("if (a) console.log('x');", "const f = () => console.log('y');"));
975
+ const run = runCommand([filePath]);
976
+ assert.equal(run.status, 0, run.stderr);
977
+ assert.match(run.stdout, /Kept: 2\./);
978
+ assert.match(run.stdout, /\nKept:\n/);
979
+ assert.ok(run.stdout.includes(`a.ts:1 ${KEPT_REASONS.bracelessBody} if (a) console.log('x');`) || run.stdout.includes(`a.ts:1 ${KEPT_REASONS.bracelessBody} console.log('x');`));
980
+ assert.ok(run.stdout.includes(`a.ts:2 ${KEPT_REASONS.usedAsValue} console.log('y')`));
981
+ });
982
+
983
+ it('does not cut a long report short when its output is a pipe', () => {
984
+ const root = makeTemporaryDirectory('long');
985
+ const filePath = join(root, 'a.ts');
986
+ const count = 4000;
987
+ writeFileSync(filePath, lines(...Array.from({ length: count }, (_, index) => `if (a) console.log(${index});`)));
988
+ const run = runCommand([filePath]);
989
+ assert.equal(run.status, 0, run.stderr);
990
+ assert.match(run.stdout, new RegExp(`Kept: ${count}\\.`));
991
+ assert.ok(run.stdout.includes(`a.ts:${count} `), 'the last line of the report is there');
992
+ });
993
+
994
+ it('says why it cannot load the parsers, and touches nothing', () => {
995
+ const root = makeTemporaryDirectory('noparsers');
996
+ const filePath = join(root, 'a.ts');
997
+ writeFileSync(filePath, sourceWithOneStatement);
998
+ const run = runCommand(['--write', filePath], { resolveFrom: root });
999
+ assert.equal(run.status, 1);
1000
+ assert.match(run.stderr, /could not load typescript from /);
1001
+ assert.ok(run.stderr.includes(root));
1002
+ assert.equal(readFileSync(filePath, 'utf8'), sourceWithOneStatement);
1003
+ });
1004
+
1005
+ it('needs svelte only for .svelte files', () => {
1006
+ const root = makeTemporaryDirectory('onlyscripts');
1007
+ const typescriptOnlyHost = makeTemporaryDirectory('typescript-only');
1008
+ mkdirSync(join(typescriptOnlyHost, 'node_modules'), { recursive: true });
1009
+ symlinkSync(dirname(createRequire(pathToFileURL(join(parserHosts[0].directory, 'package.json'))).resolve('typescript/package.json')), join(typescriptOnlyHost, 'node_modules/typescript'));
1010
+ writeFileSync(join(root, 'a.ts'), sourceWithOneStatement);
1011
+ const scriptRun = runCommand([join(root, 'a.ts')], { resolveFrom: typescriptOnlyHost });
1012
+ assert.equal(scriptRun.status, 0, scriptRun.stderr);
1013
+ writeFileSync(join(root, 'b.svelte'), '<p />\n');
1014
+ const svelteRun = runCommand([join(root, 'b.svelte')], { resolveFrom: typescriptOnlyHost });
1015
+ assert.equal(svelteRun.status, 1);
1016
+ assert.match(svelteRun.stderr, /could not load svelte from /);
1017
+ });
1018
+
1019
+ it('reads the parsers from the current directory when --resolve-from is not given', () => {
1020
+ const root = makeTemporaryDirectory('cwd');
1021
+ writeFileSync(join(root, 'a.ts'), sourceWithOneStatement);
1022
+ const run = runCommand([join(root, 'a.ts')], { resolveFrom: null, cwd: parserHosts[0].directory });
1023
+ assert.equal(run.status, 0, run.stderr);
1024
+ assert.match(run.stdout, /Would comment out: 1 in 1 file\./);
1025
+ });
1026
+
1027
+ it('goes on with the other files when one cannot be read as code, leaves that one as it was, and exits 1', () => {
1028
+ const root = makeTemporaryDirectory('broken');
1029
+ const brokenText = "function run( {\n\tconsole.log('x');\n";
1030
+ writeFileSync(join(root, 'a-good.ts'), sourceWithOneStatement);
1031
+ writeFileSync(join(root, 'b-broken.ts'), brokenText);
1032
+ writeFileSync(join(root, 'c-good.ts'), sourceWithOneStatement);
1033
+ const run = runCommand(['--write', root]);
1034
+ assert.equal(run.status, 1);
1035
+ assert.match(run.stderr, /b-broken\.ts: \d+ parse error\(s\) before any change; left alone/);
1036
+ assert.equal(readFileSync(join(root, 'b-broken.ts'), 'utf8'), brokenText);
1037
+ assert.match(readFileSync(join(root, 'a-good.ts'), 'utf8'), /\/\/ console\.log/);
1038
+ assert.match(readFileSync(join(root, 'c-good.ts'), 'utf8'), /\/\/ console\.log/);
1039
+ assert.match(run.stdout, /Commented out: 2 in 2 files\./);
1040
+ });
1041
+
1042
+ it('names a path that is not there, goes on with the others, and exits 1', () => {
1043
+ const root = makeTemporaryDirectory('missing');
1044
+ writeFileSync(join(root, 'a.ts'), sourceWithOneStatement);
1045
+ const run = runCommand([join(root, 'missing.ts'), join(root, 'a.ts')]);
1046
+ assert.equal(run.status, 1);
1047
+ assert.match(run.stderr, /missing\.ts: not found; skipped/);
1048
+ assert.match(run.stdout, /Would comment out: 1 in 1 file\./);
1049
+ });
1050
+
1051
+ it('exits 1 when the only path it was given is not there, though there is nothing left to read', () => {
1052
+ const root = makeTemporaryDirectory('onlymissing');
1053
+ const run = runCommand([join(root, 'missing.ts')]);
1054
+ assert.equal(run.status, 1);
1055
+ assert.match(run.stderr, /missing\.ts: not found; skipped/);
1056
+ assert.match(run.stdout, /no source files to read/);
1057
+ });
1058
+
1059
+ it('says there is nothing to read for a directory with no source files, and exits 0', () => {
1060
+ const root = makeTemporaryDirectory('nosource');
1061
+ writeFileSync(join(root, 'notes.md'), '# nothing\n');
1062
+ const run = runCommand([root]);
1063
+ assert.equal(run.status, 0, run.stderr);
1064
+ assert.match(run.stdout, /no source files to read/);
1065
+ });
1066
+
1067
+ it('shows how to use it for --help, and for wrong arguments exits 1 with the same text', () => {
1068
+ const help = runCommand(['--help'], { resolveFrom: null });
1069
+ assert.equal(help.status, 0);
1070
+ assert.match(help.stdout, /Usage: comment-console-logs/);
1071
+ assert.match(help.stdout, /--write/);
1072
+ assert.match(help.stdout, /--resolve-from/);
1073
+
1074
+ const noPaths = runCommand([], { resolveFrom: null });
1075
+ assert.equal(noPaths.status, 1);
1076
+ assert.match(noPaths.stderr, /no file or directory given/);
1077
+ assert.match(noPaths.stderr, /Usage: comment-console-logs/);
1078
+
1079
+ const unknownOption = runCommand(['--wipe', 'a.ts'], { resolveFrom: null });
1080
+ assert.equal(unknownOption.status, 1);
1081
+ assert.match(unknownOption.stderr, /Unknown option '--wipe'/);
1082
+ assert.match(unknownOption.stderr, /Usage: comment-console-logs/);
1083
+
1084
+ const missingValue = runCommand(['a.ts', '--resolve-from'], { resolveFrom: null });
1085
+ assert.equal(missingValue.status, 1);
1086
+ assert.match(missingValue.stderr, /resolve-from/);
1087
+ });
1088
+ });
1089
+
1090
+ // ---- The same fixtures, against every pair of parsers the checkouts have --------------------------------------------
1091
+
1092
+ describe('against every TypeScript and Svelte pair the checkouts have installed', () => {
1093
+ for (const host of parserHosts) {
1094
+ it(host.pair, () => {
1095
+ const hostParsers = loadParsers(host.directory);
1096
+ for (const fixture of CROSS_VERSION_CASES) {
1097
+ const result = commentOut(fixture.input, fixture.fileName, hostParsers);
1098
+ assert.equal(result.status, 'commented', `${fixture.name}: ${result.reason ?? ''}`);
1099
+ assert.equal(result.updatedText, fixture.expected, fixture.name);
1100
+ assert.equal(result.kept.length, fixture.keptCount, `${fixture.name}: what is kept`);
1101
+ }
1102
+ });
1103
+ }
1104
+ });