fallow-core 3.40.0

Internal detector backend for fallow-engine and fallow-api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
use crate::scripts::{
    ArgumentEntries, DeclaredScriptCall, IgnoredCommandEntries, MAX_SCRIPT_EXPANSIONS,
    MAX_SCRIPT_INDIRECTION_DEPTH, MAX_SUBSTITUTION_DEPTH, ScriptCatalog,
};

/// Shells whose `-c` value is a command.
const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash"];

/// Extract file path references from a package.json script value.
///
/// Recognises patterns like:
/// - `node path/to/script.js`
/// - `ts-node path/to/script.ts`
/// - `tsx path/to/script.ts`
/// - `npx ts-node path/to/script.ts`
/// - Bare file paths ending in `.js`, `.ts`, `.mjs`, `.cjs`, `.mts`, `.cts`
///
/// Script values are split by `&&`, `||`, and `;` to handle chained commands.
/// A segment that invokes a formatter or linter (`eslint src/a.ts`) yields no
/// references for its targets, because the tool reads them but does not
/// execute them. A module that such a tool loads through a flag, such as
/// `eslint -f ./tools/fmt.js`, is still a reference. A segment whose command
/// `ignored` lists yields no references.
///
/// A segment that calls a script that `context.scripts` declares
/// (`npm run lint -- src/a.ts`) resolves to the script body with the
/// forwarded arguments appended, as the package manager runs it. The rules
/// above then apply to that command.
///
/// The body of a `$(...)` or backtick command substitution is scanned as a
/// script of its own, because the shell runs it.
pub fn extract_script_file_refs(script: &str, context: CommandRefContext<'_>) -> Vec<String> {
    let mut refs = Vec::new();
    let mut expansions = 0;
    collect_script_file_refs(
        script,
        context,
        Depth::default(),
        &mut expansions,
        &mut refs,
    );
    refs
}

/// How deep the scan is in script calls and in command substitutions.
#[derive(Debug, Clone, Copy, Default)]
struct Depth {
    scripts: usize,
    substitutions: usize,
}

/// The inputs that decide which file arguments of a command become file
/// references.
#[derive(Debug, Clone, Copy)]
pub struct CommandRefContext<'a> {
    /// Commands whose file arguments are never references
    /// (`ignoreCommandEntries`).
    pub ignored: IgnoredCommandEntries<'a>,
    /// Declared package.json scripts, so a call such as
    /// `npm run lint -- src/a.ts` resolves to the command it runs.
    pub scripts: &'a ScriptCatalog,
}

#[cfg(test)]
impl CommandRefContext<'static> {
    /// No ignored command and no declared script.
    pub const NONE: Self = Self {
        ignored: IgnoredCommandEntries::NONE,
        scripts: ScriptCatalog::EMPTY,
    };
}

fn collect_script_file_refs(
    script: &str,
    context: CommandRefContext<'_>,
    depth: Depth,
    expansions: &mut usize,
    refs: &mut Vec<String>,
) {
    if depth.substitutions < MAX_SUBSTITUTION_DEPTH {
        let inner = Depth {
            substitutions: depth.substitutions + 1,
            ..depth
        };
        for body in crate::scripts::command_substitutions(script) {
            collect_script_file_refs(body, context, inner, expansions, refs);
        }
    }
    let called = Depth {
        scripts: depth.scripts + 1,
        ..depth
    };
    for segment in script.split(&['&', '|', ';'][..]) {
        let segment = segment.trim();
        if segment.is_empty() {
            continue;
        }

        let tokens: Vec<&str> = segment.split_whitespace().collect();
        if tokens.is_empty() {
            continue;
        }
        let mut unknown_body = false;
        match crate::scripts::declared_script_call(&tokens, context.scripts) {
            Some(DeclaredScriptCall::NoFileRefs) => continue,
            Some(DeclaredScriptCall::Command(command)) => {
                if depth.scripts < MAX_SCRIPT_INDIRECTION_DEPTH
                    && *expansions < MAX_SCRIPT_EXPANSIONS
                {
                    *expansions += 1;
                    collect_script_file_refs(&command, context, called, expansions, refs);
                }
                continue;
            }
            Some(DeclaredScriptCall::InPackages(commands)) => {
                for command in &commands {
                    if depth.scripts >= MAX_SCRIPT_INDIRECTION_DEPTH
                        || *expansions >= MAX_SCRIPT_EXPANSIONS
                    {
                        break;
                    }
                    *expansions += 1;
                    let scripts = context.scripts.for_package_command(command);
                    let mut package_refs = Vec::new();
                    collect_script_file_refs(
                        &command.command,
                        CommandRefContext {
                            ignored: context.ignored,
                            scripts: &scripts,
                        },
                        called,
                        expansions,
                        &mut package_refs,
                    );
                    refs.extend(
                        package_refs
                            .iter()
                            .map(|path| crate::scripts::rebase_path(&command.dir, path)),
                    );
                }
                continue;
            }
            Some(DeclaredScriptCall::UnknownBody) => unknown_body = true,
            None => {}
        }
        // A call of a script with an unknown body, such as
        // `npm run gen -- scripts/a.ts` with no `gen` body, has no binary;
        // scan the whole segment for script files. This includes
        // `yarn eslint src/a.ts` when `eslint` is a declared script: the
        // package manager runs the script, not the `eslint` binary.
        let invoked = crate::scripts::invoked_command(&tokens, 0, context.scripts);
        if invoked
            .as_ref()
            .is_some_and(crate::scripts::InvokedCommand::runs_in_other_packages)
        {
            continue;
        }
        let start = invoked.as_ref().map_or(0, |invoked| invoked.index);
        let resolve = |path: &str| {
            invoked
                .as_ref()
                .map_or_else(|| vec![path.to_string()], |invoked| invoked.file_refs(path))
        };

        let cmd = tokens[start];
        if context.ignored.contains(cmd) || crate::scripts::is_task_runner(cmd) {
            continue;
        }
        let Some((cmd, start)) = crate::scripts::vite_plus::scan_command(&tokens, start) else {
            continue;
        };
        if let Some(body) = shell_command_body(cmd, &tokens, start, segment)
            && depth.substitutions < MAX_SUBSTITUTION_DEPTH
        {
            let inner = Depth {
                substitutions: depth.substitutions + 1,
                ..depth
            };
            collect_script_file_refs(body, context, inner, expansions, refs);
            continue;
        }
        let files = script_file_args(cmd, &tokens, start, unknown_body);
        refs.extend(files.iter().flat_map(|path| resolve(path)));
    }
}

/// Return the quoted command of `sh -c "watchee app/a.js"`. The shell runs
/// it, so it is read as a command of its own and the same rules apply.
fn shell_command_body<'a>(
    cmd: &str,
    tokens: &[&str],
    start: usize,
    segment: &'a str,
) -> Option<&'a str> {
    if !SHELLS.contains(&cmd) {
        return None;
    }
    // Shell flags such as `-e`, `-eu` or `-o pipefail` can come before `-c`.
    let mut idx = start + 1;
    loop {
        match *tokens.get(idx)? {
            "-c" => break,
            "-o" | "+o" => idx += 2,
            flag if flag.starts_with(['-', '+']) => idx += 1,
            _ => return None,
        }
    }
    let (_, body) = segment.split_once(" -c ")?;
    Some(body.trim().trim_matches(|ch| ch == '"' || ch == '\''))
}

/// The arguments of the command `cmd` at `start` that name script files. A
/// runner such as `node` takes any file path, another command a script file.
///
/// The program of the command decides which arguments count (issue #3967):
/// a runtime such as `node` gives only its script and the modules that its
/// flags load, and a program that fallow does not know gives no glob. A
/// call of a script with an unknown body (`unknown_body`) can run any
/// program, so every argument can name a file.
fn script_file_args(cmd: &str, tokens: &[&str], start: usize, unknown_body: bool) -> Vec<String> {
    const RUNNERS: &[&str] = &["node", "bun", "ts-node", "tsx", "babel-node"];
    // A package manager that stays the command runs a script that the
    // catalog does not declare.
    const PACKAGE_MANAGERS: &[&str] = &["npm", "pnpm", "yarn"];
    if crate::scripts::is_file_target_tool(cmd) {
        return crate::scripts::file_target_tool_loaded_files(cmd, &tokens[start + 1..]);
    }
    let entries = if unknown_body || PACKAGE_MANAGERS.contains(&cmd) {
        ArgumentEntries::All
    } else {
        crate::scripts::argument_entries(cmd, &tokens[start + 1..])
    };
    let (args, is_ref): (Vec<&str>, fn(&str) -> bool) = match entries {
        ArgumentEntries::All if RUNNERS.contains(&cmd) => {
            (tokens[start + 1..].to_vec(), looks_like_file_path)
        }
        ArgumentEntries::All => (tokens[start..].to_vec(), looks_like_script_file),
        ArgumentEntries::Literal => (
            tokens[start..]
                .iter()
                .copied()
                .filter(|token| !crate::scripts::is_glob(token))
                .collect(),
            looks_like_script_file,
        ),
        // An executable script file (`bun --smol app/tool.js`) is the
        // command itself, so it stays a reference.
        ArgumentEntries::Listed(listed) => (
            std::iter::once(tokens[start])
                .filter(|cmd| looks_like_script_file(cmd))
                .chain(listed)
                .collect(),
            looks_like_file_path,
        ),
        ArgumentEntries::Loaded(loaded) => return loaded,
    };
    args.into_iter()
        .filter(|token| !token.starts_with('-') && is_ref(token))
        .map(str::to_string)
        .collect()
}

/// Check if a token looks like a file path argument (has a directory separator
/// or a script-like source file extension).
pub fn looks_like_file_path(token: &str) -> bool {
    if !crate::scripts::could_be_file_path(token) {
        return false;
    }
    let extensions = [
        ".js", ".ts", ".mjs", ".cjs", ".mts", ".cts", ".jsx", ".tsx", ".gts", ".gjs",
    ];
    if extensions.iter().any(|ext| token.ends_with(ext)) {
        return true;
    }
    token.starts_with("./")
        || token.starts_with("../")
        || (token.contains('/') && !token.starts_with('@') && !token.contains("://"))
}

pub use crate::scripts::looks_like_script_file;

#[cfg(test)]
mod tests {
    use super::*;

    fn refs(script: &str) -> Vec<String> {
        extract_script_file_refs(script, CommandRefContext::NONE)
    }

    fn with_scripts(scripts: &ScriptCatalog) -> CommandRefContext<'_> {
        CommandRefContext {
            ignored: IgnoredCommandEntries::NONE,
            scripts,
        }
    }

    #[expect(
        clippy::disallowed_types,
        reason = "ScriptCatalog takes the serde-deserialized std HashMap"
    )]
    fn catalog(scripts: &[(&str, &str)]) -> ScriptCatalog {
        let scripts: std::collections::HashMap<String, String> = scripts
            .iter()
            .map(|(name, body)| ((*name).to_string(), (*body).to_string()))
            .collect();
        ScriptCatalog::from_scripts(&scripts)
    }

    #[test]
    fn script_call_of_a_linter_script_yields_no_target_refs() {
        let scripts = catalog(&[("lint", "eslint"), ("fmt", "prettier --check")]);
        for script in [
            "npm run lint -- src/a.ts",
            "yarn lint src/b.ts",
            "pnpm fmt src/c.ts",
            "pnpm run lint src/d.ts",
            "CI=1 npm run lint -- src/e.ts",
            "npm run lint src/f.ts",
            "npm run -s fmt --cache src/g.ts",
        ] {
            assert!(
                extract_script_file_refs(script, with_scripts(&scripts)).is_empty(),
                "`{script}` must not yield file refs"
            );
        }
    }

    #[test]
    fn script_call_resolves_to_the_body_with_forwarded_arguments() {
        let scripts = catalog(&[
            ("gen", "mocha"),
            ("codegen", "my-codegen"),
            ("run-tool", "node scripts/tool.ts"),
        ]);
        assert_eq!(
            extract_script_file_refs("npm run gen -- src/gen-input.ts", with_scripts(&scripts)),
            vec!["src/gen-input.ts"]
        );
        // A program that fallow does not know expands no glob, and `node`
        // gives the arguments after its script to that script (issue #3967).
        assert!(
            extract_script_file_refs("npm run codegen -- src/**/*.ts", with_scripts(&scripts))
                .is_empty()
        );
        assert_eq!(
            extract_script_file_refs(
                "npm run run-tool -- src/gen-input.ts",
                with_scripts(&scripts)
            ),
            vec!["scripts/tool.ts"]
        );
        let ignored = vec!["mocha".to_string()];
        assert!(
            extract_script_file_refs(
                "npm run gen -- src/gen-input.ts",
                CommandRefContext {
                    ignored: IgnoredCommandEntries::new(&ignored),
                    scripts: &scripts,
                }
            )
            .is_empty()
        );
        assert_eq!(
            extract_script_file_refs("npm run run-tool -- --out dist", with_scripts(&scripts)),
            vec!["scripts/tool.ts"]
        );
        assert_eq!(
            extract_script_file_refs("npm run gen src/gen-input.ts", with_scripts(&scripts)),
            vec!["src/gen-input.ts"]
        );
        assert!(extract_script_file_refs("npm run gen", with_scripts(&scripts)).is_empty());
    }

    #[test]
    fn script_call_of_an_unknown_script_scans_the_segment() {
        assert_eq!(
            refs("npm run gen -- src/gen-input.ts"),
            vec!["src/gen-input.ts"]
        );
    }

    #[test]
    fn script_arguments_after_the_runtime_script_are_data() {
        assert_eq!(refs("node tool.js src/**/*.js"), vec!["tool.js"]);
        assert_eq!(refs("node tool.js --input src/lib/b.js"), vec!["tool.js"]);
        assert_eq!(
            refs("node api-docs/build-openapi.js --definition a.json src/*.js src/**/*.js"),
            vec!["api-docs/build-openapi.js"]
        );
        assert!(refs("watchee -f './src/**/*' -c 'echo hi'").is_empty());
        assert!(refs("pnpm watchee -f ./src/**/*.js -c 'echo hi'").is_empty());
        assert_eq!(
            refs("jscodeshift -t codemods/transform.js"),
            vec!["codemods/transform.js"]
        );
        assert_eq!(refs("time node app/x.js data/a.js"), vec!["app/x.js"]);
        assert_eq!(
            refs("node --import=./app/instrument.mjs app/server.js"),
            vec!["./app/instrument.mjs", "app/server.js"]
        );
        assert_eq!(
            refs("bun build ./app/x.ts --outdir dist"),
            vec!["./app/x.ts"]
        );
        assert_eq!(refs("deno serve app/x.ts"), vec!["app/x.ts"]);
        assert_eq!(refs("sh -c \"watchee app/data.js\""), vec!["app/data.js"]);
        assert_eq!(refs("sh -c 'node app/x.js data/a.js'"), vec!["app/x.js"]);
        assert!(refs("sh -c \"watchee -f 'src/**/*'\"").is_empty());
    }

    #[test]
    fn wrapped_program_needs_a_bare_name_before_any_literal_file() {
        assert_eq!(
            refs("foo --target node app/x.js app/y.js"),
            vec!["app/x.js", "app/y.js"]
        );
        assert_eq!(refs("my-cli app/a.js --engine node"), vec!["app/a.js"]);
        assert_eq!(
            refs("run scripts/deno app/a.ts app/b.ts"),
            vec!["app/a.ts", "app/b.ts"]
        );
        assert_eq!(
            refs("mocha test/a.spec.js test/b.spec.js"),
            vec!["test/a.spec.js", "test/b.spec.js"]
        );
    }

    #[test]
    fn package_binary_path_and_shell_e_flag_keep_their_files() {
        let mut failures = Vec::new();
        for (script, expected) in [
            (
                "./node_modules/.bin/jscodeshift -t codemods/transform.js src",
                &["codemods/transform.js"][..],
            ),
            (
                "node_modules/.bin/some-tool app/a.js app/b.js",
                &["app/a.js", "app/b.js"],
            ),
            ("bash -e scripts/gen.sh out", &["scripts/gen.sh"]),
            ("sh -e scripts/gen.sh app/a.js", &["scripts/gen.sh"]),
            (
                "bash -o pipefail -c \"node app/x.js data/a.js\"",
                &["app/x.js"],
            ),
            (
                "bash -o pipefail -c \"watchee app/data.js\"",
                &["app/data.js"],
            ),
        ] {
            let found = refs(script);
            if found != expected {
                failures.push(format!("{script}: {found:?}"));
            }
        }
        assert!(failures.is_empty(), "{failures:#?}");
    }

    #[test]
    fn shell_flags_before_c_keep_the_quoted_command() {
        assert_eq!(
            refs("bash -e -c \"node app/a.js data/b.js\""),
            vec!["app/a.js"]
        );
        assert_eq!(
            refs("bash -eu -c \"watchee app/data.js\""),
            vec!["app/data.js"]
        );
    }

    #[test]
    fn bun_script_arguments_are_data() {
        let failures: Vec<String> = [
            "bun --smol app/tool.js app/data.js",
            "bun --bun app/tool.js app/data.js",
            "bun run app/tool.js app/data.js",
        ]
        .into_iter()
        .map(|script| (script, refs(script)))
        .filter(|(_, found)| {
            found.contains(&"app/data.js".to_string())
                || !found.contains(&"app/tool.js".to_string())
        })
        .map(|(script, found)| format!("{script}: {found:?}"))
        .collect();
        assert!(failures.is_empty(), "{failures:#?}");
    }

    #[test]
    fn bun_preload_after_runtime_flags_stays_a_ref() {
        let refs = refs(
            "CA=./c.pem bun --bun --smol --preload ./test/preload.js \
             ./node_modules/jest-cli/bin/jest.js --logHeapUsage",
        );
        assert!(refs.contains(&"./test/preload.js".to_string()), "{refs:?}");
    }

    #[test]
    fn script_call_cycles_terminate() {
        let scripts = catalog(&[("a", "npm run b -- x/a.ts"), ("b", "npm run a -- x/b.ts")]);
        let refs = extract_script_file_refs("npm run a -- x/c.ts", with_scripts(&scripts));
        assert!(refs.len() <= MAX_SCRIPT_EXPANSIONS * 3, "{refs:?}");
    }

    #[test]
    fn workspace_and_env_wrapper_forms_of_a_linter_yield_no_target_refs() {
        for script in [
            "pnpm --filter web exec eslint src/a.ts",
            "pnpm --filter=web exec eslint src/a.ts",
            "pnpm -F web exec eslint src/a.ts",
            "pnpm -r exec prettier --check src/b.ts",
            "pnpm --recursive --parallel exec eslint src/b.ts",
            "pnpm exec -r eslint src/b.ts",
            "dotenv -e .env.ci -- eslint src/g.ts",
            "dotenv -e .env.ci eslint src/g.ts",
            "dotenv -c production -- eslint src/g.ts",
            "dotenv -c -- eslint src/g.ts",
            "dotenv -v CI=1 -o -- eslint src/g.ts",
            "env -u HOME eslint src/g.ts",
            "env -i CI=1 eslint src/g.ts",
        ] {
            assert!(
                refs(script).is_empty(),
                "`{script}` must not yield file refs: {:?}",
                refs(script)
            );
        }
        assert_eq!(
            refs("dotenv -e .env.ci -- node scripts/run.ts"),
            vec!["scripts/run.ts"]
        );
        assert!(
            refs("pnpm --filter web exec tsx scripts/run.ts").is_empty(),
            "a runner in another workspace package resolves its file there"
        );
        assert_eq!(
            refs("pnpm -C packages/web exec tsx scripts/run.ts"),
            vec!["packages/web/scripts/run.ts"]
        );
    }

    #[test]
    fn commands_in_other_workspace_packages_yield_no_refs() {
        for script in [
            "yarn workspace web eslint src/a.ts",
            "yarn workspace web tsx scripts/run.ts",
            "yarn workspace web lint src/a.ts",
            "yarn workspaces foreach -A run lint src/a.ts",
            "yarn workspaces run lint src/a.ts",
            "pnpm --filter web eslint src/a.ts",
            "pnpm --filter web run lint src/a.ts",
            "pnpm -r run lint -- src/a.ts",
            "pnpm -r exec tsx scripts/run.ts",
            "npm -w web run lint -- src/a.ts",
            "npm run lint --workspaces -- src/a.ts",
            "turbo run lint -- src/a.ts",
            "npx turbo lint -- src/a.ts",
            "nx run-many -t lint -- src/a.ts",
            "lerna run lint -- src/a.ts",
        ] {
            assert!(
                refs(script).is_empty(),
                "`{script}` must not yield file refs: {:?}",
                refs(script)
            );
        }
    }

    #[test]
    #[expect(
        clippy::disallowed_types,
        reason = "ScriptCatalog takes the serde-deserialized std HashMap"
    )]
    fn a_declared_script_named_after_a_linter_keeps_its_target_refs() {
        let scripts = catalog(&[("eslint", "mocha tools/check.js")]);
        assert_eq!(
            extract_script_file_refs(
                "varlock run -- yarn eslint src/a.ts",
                with_scripts(&scripts)
            ),
            vec!["tools/check.js", "src/a.ts"]
        );

        let mut ambiguous = catalog(&[("eslint", "node tools/check.js")]);
        ambiguous.merge_workspace_scripts(&std::collections::HashMap::from([(
            "eslint".to_string(),
            "eslint .".to_string(),
        )]));
        assert_eq!(
            extract_script_file_refs("yarn eslint src/a.ts", with_scripts(&ambiguous)),
            vec!["src/a.ts"],
            "an unknown body keeps the target, as for `npm run eslint -- src/a.ts`"
        );
    }

    #[test]
    fn a_wrapped_call_of_a_linter_script_yields_no_target_refs() {
        let scripts = catalog(&[("lint", "eslint")]);
        assert!(
            extract_script_file_refs("varlock run -- yarn lint src/a.ts", with_scripts(&scripts))
                .is_empty()
        );
    }

    #[test]
    fn script_node_runner() {
        let refs = refs("node utilities/generate-coverage-badge.js");
        assert_eq!(refs, vec!["utilities/generate-coverage-badge.js"]);
    }

    #[test]
    fn script_formatter_and_linter_targets_are_not_refs() {
        for script in [
            "oxfmt --check src/dead.ts",
            "eslint src/dead.ts",
            "npx prettier --write src/dead.ts",
            "pnpm exec oxlint src/dead.ts",
            "pnpm eslint src/dead.ts",
            "CI=1 eslint src/dead.ts",
        ] {
            assert!(
                refs(script).is_empty(),
                "`{script}` must not yield file refs"
            );
        }
        assert_eq!(
            refs("eslint src/dead.ts && node scripts/build.js"),
            vec!["scripts/build.js"]
        );
    }

    #[test]
    fn script_formatter_and_linter_keep_loaded_module_refs() {
        assert_eq!(refs("eslint -f ./tools/fmt.js src"), vec!["./tools/fmt.js"]);
        assert_eq!(
            refs("prettier --plugin=./p.mjs --check src/a.ts"),
            vec!["./p.mjs"]
        );
        assert_eq!(
            refs("npx stylelint --custom-formatter ./tools/fmt.js \"**/*.css\""),
            vec!["./tools/fmt.js"]
        );
    }

    #[test]
    fn script_ts_node_runner() {
        let refs = refs("ts-node scripts/seed.ts");
        assert_eq!(refs, vec!["scripts/seed.ts"]);
    }

    #[test]
    fn script_tsx_runner() {
        let refs = refs("tsx scripts/migrate.ts");
        assert_eq!(refs, vec!["scripts/migrate.ts"]);
    }

    #[test]
    fn script_bun_runner() {
        let refs = refs("bun scripts/build.ts");
        assert_eq!(refs, vec!["scripts/build.ts"]);
    }

    #[test]
    fn script_npx_prefix() {
        let refs = refs("npx ts-node scripts/generate.ts");
        assert_eq!(refs, vec!["scripts/generate.ts"]);
    }

    #[test]
    fn script_chained_commands() {
        let refs = refs("node scripts/build.js && node scripts/post-build.js");
        assert_eq!(refs, vec!["scripts/build.js", "scripts/post-build.js"]);
    }

    #[test]
    fn script_with_flags() {
        let refs = refs("node --experimental-specifier-resolution=node scripts/run.mjs");
        assert_eq!(refs, vec!["scripts/run.mjs"]);
    }

    #[test]
    #[expect(
        clippy::disallowed_types,
        reason = "WorkspacePackages takes the serde-deserialized std HashMap"
    )]
    fn a_command_in_a_named_workspace_package_resolves_there() {
        let web_scripts: std::collections::HashMap<String, String> = [
            ("gen".to_string(), "tsx".to_string()),
            ("lint".to_string(), "eslint".to_string()),
        ]
        .into_iter()
        .collect();
        let mut packages = crate::scripts::WorkspacePackages::default();
        packages.add("web", "packages/web", Some(&web_scripts));
        let scripts = catalog(&[]).with_workspaces(std::sync::Arc::new(packages), "");
        for command in [
            "yarn workspace web node scripts/a.ts",
            "pnpm --filter web exec tsx scripts/a.ts",
            "npm run -w web gen -- scripts/a.ts",
            "yarn workspace web gen scripts/a.ts",
        ] {
            assert_eq!(
                extract_script_file_refs(command, with_scripts(&scripts)),
                vec!["packages/web/scripts/a.ts"],
                "`{command}`"
            );
        }
        for command in [
            "yarn workspace web eslint src/a.ts",
            "npm run -w web lint -- src/a.ts",
            "yarn workspace docs node scripts/a.ts",
        ] {
            assert!(
                extract_script_file_refs(command, with_scripts(&scripts)).is_empty(),
                "`{command}`"
            );
        }
    }

    #[test]
    #[expect(
        clippy::disallowed_types,
        reason = "WorkspacePackages takes the serde-deserialized std HashMap"
    )]
    fn a_command_in_every_package_or_a_package_directory_resolves_there() {
        let package_scripts: std::collections::HashMap<String, String> = [
            ("gen".to_string(), "tsx".to_string()),
            ("lint".to_string(), "eslint".to_string()),
        ]
        .into_iter()
        .collect();
        let mut packages = crate::scripts::WorkspacePackages::default();
        packages.add("web", "packages/web", Some(&package_scripts));
        packages.add("api", "packages/api", Some(&package_scripts));
        let scripts = catalog(&[]).with_workspaces(std::sync::Arc::new(packages), "");
        for command in [
            "pnpm -r exec tsx scripts/a.ts",
            "pnpm -r run gen -- scripts/a.ts",
            "npm --workspaces run gen -- scripts/a.ts",
            "yarn workspaces foreach -A run gen scripts/a.ts",
            "yarn workspaces run gen scripts/a.ts",
        ] {
            let mut refs = extract_script_file_refs(command, with_scripts(&scripts));
            refs.sort();
            assert_eq!(
                refs,
                vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"],
                "`{command}`"
            );
        }
        for command in [
            "pnpm -C packages/web run gen scripts/a.ts",
            "npm --prefix packages/web run gen -- scripts/a.ts",
            "yarn --cwd packages/web gen scripts/a.ts",
        ] {
            assert_eq!(
                extract_script_file_refs(command, with_scripts(&scripts)),
                vec!["packages/web/scripts/a.ts"],
                "`{command}`"
            );
        }
        for command in [
            "pnpm -r exec eslint src/a.ts",
            "pnpm -r run lint -- src/a.ts",
            "yarn --cwd packages/web lint src/a.ts",
        ] {
            assert!(
                extract_script_file_refs(command, with_scripts(&scripts)).is_empty(),
                "`{command}`"
            );
        }
    }

    #[test]
    fn script_no_file_ref() {
        let refs = refs("next build");
        assert!(refs.is_empty());
    }

    #[test]
    fn script_bare_file_path() {
        let refs = refs("echo done && node ./scripts/check.js");
        assert_eq!(refs, vec!["./scripts/check.js"]);
    }

    #[test]
    fn script_semicolon_separator() {
        let refs = refs("node scripts/a.js; node scripts/b.ts");
        assert_eq!(refs, vec!["scripts/a.js", "scripts/b.ts"]);
    }

    #[test]
    fn script_command_substitution_bodies() {
        assert_eq!(
            refs(r#"STAMP="$(node scripts/a.ts)" LABEL=`tsx scripts/b.ts`"#),
            vec!["scripts/a.ts", "scripts/b.ts"]
        );
        assert_eq!(
            refs(r#"X="$(echo "$(node scripts/inner.ts)")""#),
            vec!["scripts/inner.ts"]
        );
        assert!(refs("echo '$(node scripts/none.ts)'").is_empty());
    }

    #[test]
    fn file_path_with_extension() {
        assert!(looks_like_file_path("scripts/build.js"));
        assert!(looks_like_file_path("scripts/build.ts"));
        assert!(looks_like_file_path("scripts/build.mjs"));
    }

    #[test]
    fn file_path_with_slash() {
        assert!(looks_like_file_path("scripts/build"));
    }

    #[test]
    fn not_file_path() {
        assert!(!looks_like_file_path("--watch"));
        assert!(!looks_like_file_path("build"));
    }

    #[test]
    fn script_file_with_path() {
        assert!(looks_like_script_file("scripts/build.js"));
        assert!(looks_like_script_file("./scripts/build.ts"));
        assert!(looks_like_script_file("../scripts/build.mjs"));
    }

    #[test]
    fn not_script_file_bare_name() {
        assert!(!looks_like_script_file("webpack.js"));
        assert!(!looks_like_script_file("build"));
    }

    #[test]
    fn looks_like_file_path_rejects_gha_fragments() {
        assert!(!looks_like_file_path("${{ env.URL }}/api.ts"));
        assert!(!looks_like_file_path("}}/api/health.ts"));
    }

    #[test]
    fn looks_like_file_path_rejects_backslash_and_bracket_class() {
        assert!(!looks_like_file_path(r"path\to\file.ts"));
        assert!(!looks_like_file_path(".[]"));
        assert!(!looks_like_file_path("prefix/[^unclosed.ts"));
    }

    #[test]
    fn looks_like_file_path_passes_nextjs_dynamic_route() {
        assert!(looks_like_file_path("app/[id]/page.tsx"));
        assert!(looks_like_file_path("pages/[...slug].ts"));
    }

    #[test]
    fn looks_like_script_file_rejects_gha_and_regex_fragments() {
        assert!(!looks_like_script_file("${{ env.X }}/path.ts"));
        assert!(!looks_like_script_file(r"path\file.ts"));
    }

    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            /// looks_like_file_path should never panic on arbitrary strings.
            /// The class carries the metacharacters `could_be_file_path`
            /// branches on (`$`, `{`, `}`, `[`, `]`, `\`), so the GitHub-Actions
            /// template guard, the backslash guard and the `[` bracket scan are
            /// all reachable instead of only the final fall-through.
            #[test]
            fn looks_like_file_path_no_panic(s in r"[a-zA-Z0-9_./@$\[\]{}\\-]{1,80}") {
                let _ = looks_like_file_path(&s);
            }

            /// looks_like_script_file should never panic on arbitrary strings.
            /// Same widened class as `looks_like_file_path_no_panic`: both open
            /// with `crate::scripts::could_be_file_path`, whose guards are all
            /// on `$`, `{`, `}`, `\` and `[`.
            #[test]
            fn looks_like_script_file_no_panic(s in r"[a-zA-Z0-9_./@$\[\]{}\\-]{1,80}") {
                let _ = looks_like_script_file(&s);
            }

            /// extract_script_file_refs should never panic on arbitrary input.
            /// Keeps the whitespace and `&`/`|`/`;` segment separators and adds
            /// the `could_be_file_path` metacharacters, so tokenisation and the
            /// per-token guards are fuzzed together.
            #[test]
            fn extract_script_file_refs_no_panic(s in r"[a-zA-Z0-9 _./@&|;$\[\]{}\\-]{1,200}") {
                let _ = refs(&s);
            }
        }
    }
}