cuke-dedup 0.10.1

Static analysis for duplicate and reusable Cucumber step definitions
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
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
use super::assertions::RequireBindings;
use super::ast::{
    call_string_argument, import_has_runtime_bindings, import_module, import_requires_loader,
    is_star_export, is_top_level_variable, is_type_only_declaration, is_type_only_specifier,
    push_named_children_reverse, string_literal,
};
use super::frameworks::{
    framework_for_module, is_supported_module, registration_exports_for_framework,
    registration_exports_for_module, RegistrationExports,
};
use super::node_text;
use super::project_resolution::ProjectResolution;
use crate::model::Framework;
use crate::resource_limits::{
    read_utf8, MAX_PROJECT_INPUT_BYTES, MAX_REGISTRATION_MODULES, MAX_REGISTRATION_MODULE_BYTES,
    MAX_REGISTRATION_RESOLUTION_STATES,
};
use crate::source_adapter::{grammar_for_language, language_for_path};
use anyhow::{bail, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use tree_sitter::{Node, Parser};

mod export_values;
use export_values::{ExportScope, ExportValue};

/// What a module's export statements declare, gathered in one walk.
#[derive(Default)]
struct ExportFacts {
    /// `(local, exported)` pairs, resolved against local registrations once the walk ends.
    direct_export_names: Vec<(String, String)>,
    reexports: Vec<Reexport>,
    /// Set when a CommonJS `module.exports`/`exports.x` assignment uses a form the analyzer cannot
    /// turn into an export, so the file resolves to *fewer* registrations than it really has. The
    /// caller reports the file incomplete rather than treating the partial result as authoritative.
    incomplete: bool,
}

const MAX_REEXPORT_DEPTH: usize = 16;
type CachedExports = (Option<RegistrationExports>, Framework, bool);

#[derive(Debug, Clone)]
struct Reexport {
    module: String,
    specifiers: Vec<(String, String)>,
    star: bool,
}

#[derive(Debug, Clone)]
struct ModuleFacts {
    reexports: Vec<Reexport>,
    direct_exports: RegistrationExports,
    framework: Framework,
    /// A CommonJS export assignment used a form the analyzer does not model, so the resolved
    /// exports may be a subset of what the module registers.
    exports_incomplete: bool,
}

#[derive(Default)]
struct ResolutionState {
    active: BTreeSet<PathBuf>,
    exports: BTreeMap<(PathBuf, usize), CachedExports>,
    modules: BTreeMap<PathBuf, Option<ModuleFacts>>,
    module_bytes: usize,
    resolutions_started: usize,
}

#[derive(Debug)]
struct ResolvedExports {
    exports: Option<RegistrationExports>,
    framework: Framework,
    cacheable: bool,
    /// A resolved module (or one it re-exports) declared exports in a form the analyzer does not
    /// model, so `exports` may be a subset of the real registration set.
    exports_incomplete: bool,
}

#[derive(Debug)]
pub(super) struct RegistrationResolution {
    pub(super) module_path: Option<PathBuf>,
    pub(super) exports: RegistrationExports,
    pub(super) framework: Framework,
}

/// Outcome of resolving one import specifier to its registration exports.
///
/// A specifier that cannot be resolved statically is a recall limitation, not an analyzer
/// failure: the importing file simply contributes no registration aliases. `reason` carries the
/// static-resolution failure so the caller can explain *why* in a source-localized diagnostic
/// rather than aborting the run.
#[derive(Debug, Default)]
pub(super) struct RegistrationOutcome {
    pub(super) resolution: Option<RegistrationResolution>,
    pub(super) reason: Option<String>,
}

#[derive(Default)]
pub(super) struct RegistrationResolver {
    boundary: Option<PathBuf>,
    project: ProjectResolution,
    state: ResolutionState,
}

impl RegistrationResolver {
    pub(super) fn for_root(root: &Path) -> Self {
        Self {
            boundary: root.canonicalize().ok(),
            project: ProjectResolution::for_root(root),
            state: ResolutionState::default(),
        }
    }

    pub(super) fn registration_exports(
        &mut self,
        importer: &Path,
        specifier: &str,
    ) -> Result<RegistrationOutcome> {
        let boundary = self.boundary.clone().or_else(|| project_boundary(importer));
        let Some(boundary) = boundary else {
            return Ok(RegistrationOutcome::default());
        };
        match resolve_exports(
            importer,
            specifier,
            &boundary,
            &mut self.project,
            &mut self.state,
            0,
        ) {
            Ok(resolved) => {
                // A module that resolved but declared some exports in an unmodeled CommonJS form
                // may register more than the analyzer could see. Report it so the corpus is marked
                // incomplete, while still using the exports that did resolve.
                let reason = resolved.exports_incomplete.then(|| {
                    "some exports use a CommonJS form the analyzer does not model".to_owned()
                });
                Ok(RegistrationOutcome {
                    resolution: resolved.exports.map(|exports| RegistrationResolution {
                        module_path: self
                            .project
                            .resolve(importer, specifier, &boundary)
                            .ok()
                            .flatten(),
                        exports,
                        framework: resolved.framework,
                    }),
                    reason,
                })
            }
            // A module the filesystem refused to hand over is an operational failure, exactly as
            // it is for a definition source: the analyzer could not read input it was told to
            // read, and silently continuing would understate the corpus. Everything else here
            // means "this specifier is not statically resolvable" — outside the analysis root, a
            // malformed or cyclic project config, or a resolution resource limit — which bounds
            // recall without making any surviving finding wrong, so it degrades to a warning.
            Err(error) if is_io_failure(&error) => Err(error),
            Err(error) => Ok(RegistrationOutcome {
                resolution: None,
                reason: Some(format!("{error:#}")),
            }),
        }
    }
}

fn resolve_exports(
    importer: &Path,
    specifier: &str,
    boundary: &Path,
    project: &mut ProjectResolution,
    state: &mut ResolutionState,
    depth: usize,
) -> Result<ResolvedExports> {
    if depth >= MAX_REEXPORT_DEPTH {
        return Ok(ResolvedExports {
            exports: None,
            framework: Framework::Unknown,
            cacheable: true,
            exports_incomplete: false,
        });
    }
    let Some(path) = project.resolve(importer, specifier, boundary)? else {
        return Ok(ResolvedExports {
            exports: None,
            framework: Framework::Unknown,
            cacheable: true,
            exports_incomplete: false,
        });
    };
    let remaining_depth = MAX_REEXPORT_DEPTH - depth;
    let cache_key = (path.clone(), remaining_depth);
    if let Some((exports, framework, exports_incomplete)) = state.exports.get(&cache_key) {
        return Ok(ResolvedExports {
            exports: exports.clone(),
            framework: *framework,
            cacheable: true,
            exports_incomplete: *exports_incomplete,
        });
    }
    if !state.active.insert(path.clone()) {
        return Ok(ResolvedExports {
            exports: None,
            framework: Framework::Unknown,
            cacheable: false,
            exports_incomplete: false,
        });
    }
    let resolved = resolve_active_exports(&path, boundary, project, state, depth);
    // Resolution failures are converted to source-local diagnostics by the caller. Always clear
    // the active-path marker before propagating one, or a later independent import is mistaken
    // for a cycle and silently loses registrations.
    state.active.remove(&path);
    let resolved = resolved?;
    if resolved.cacheable {
        state.exports.insert(
            cache_key,
            (
                resolved.exports.clone(),
                resolved.framework,
                resolved.exports_incomplete,
            ),
        );
    }
    Ok(resolved)
}

fn resolve_active_exports(
    path: &Path,
    boundary: &Path,
    project: &mut ProjectResolution,
    state: &mut ResolutionState,
    depth: usize,
) -> Result<ResolvedExports> {
    if state.resolutions_started >= MAX_REGISTRATION_RESOLUTION_STATES {
        bail!(
            "registration module graph exceeds the {}-state resolution limit",
            MAX_REGISTRATION_RESOLUTION_STATES
        );
    }
    state.resolutions_started += 1;

    let Some(module) = load_module(path, state)? else {
        return Ok(ResolvedExports {
            exports: None,
            framework: Framework::Unknown,
            cacheable: true,
            exports_incomplete: false,
        });
    };
    let mut exports = module.direct_exports;
    let mut framework = module.framework;
    let mut cacheable = true;
    let mut exports_incomplete = module.exports_incomplete;
    for reexport in module.reexports {
        let (available, available_framework) = if is_supported_module(&reexport.module) {
            (
                registration_exports_for_module(&reexport.module),
                framework_for_module(&reexport.module),
            )
        } else {
            let resolved =
                resolve_exports(path, &reexport.module, boundary, project, state, depth + 1)?;
            cacheable &= resolved.cacheable;
            exports_incomplete |= resolved.exports_incomplete;
            (resolved.exports.unwrap_or_default(), resolved.framework)
        };
        framework = merge_framework(framework, available_framework);
        for (imported, exported) in &reexport.specifiers {
            if let Some(canonical) = available.get(imported) {
                exports.insert(exported.clone(), canonical.clone());
            }
        }
        if reexport.star {
            exports.extend(available);
        }
    }
    Ok(ResolvedExports {
        exports: Some(exports),
        framework,
        cacheable,
        exports_incomplete,
    })
}

/// Returns whether `error` was caused by the filesystem refusing a read.
///
/// Resource limits carry their own typed cause, so an `io::Error` anywhere in the chain means a
/// genuine read failure — a permission change, a vanished file, or exhausted descriptors.
fn is_io_failure(error: &anyhow::Error) -> bool {
    error
        .chain()
        .any(|cause| cause.downcast_ref::<std::io::Error>().is_some())
}

pub(super) fn merge_framework(current: Framework, evidence: Framework) -> Framework {
    match (current, evidence) {
        (Framework::PlaywrightBdd, _) | (_, Framework::PlaywrightBdd) => Framework::PlaywrightBdd,
        (Framework::CypressCucumber, _) | (_, Framework::CypressCucumber) => {
            Framework::CypressCucumber
        }
        (Framework::CucumberJs, _) | (_, Framework::CucumberJs) => Framework::CucumberJs,
        (Framework::JestCucumber, _) | (_, Framework::JestCucumber) => Framework::JestCucumber,
        (Framework::VitestCucumber, _) | (_, Framework::VitestCucumber) => {
            Framework::VitestCucumber
        }
        _ => Framework::Unknown,
    }
}

fn load_module(path: &Path, state: &mut ResolutionState) -> Result<Option<ModuleFacts>> {
    if let Some(module) = state.modules.get(path) {
        return Ok(module.clone());
    }
    if state.modules.len() >= MAX_REGISTRATION_MODULES {
        bail!(
            "registration module graph exceeds the {}-module resolution limit",
            MAX_REGISTRATION_MODULES
        );
    }
    let source = read_utf8(path, "registration module", MAX_PROJECT_INPUT_BYTES)?;
    let module_bytes = state.module_bytes.saturating_add(source.len());
    if module_bytes > MAX_REGISTRATION_MODULE_BYTES {
        bail!(
            "registration module graph exceeds the {}-byte aggregate resolution limit",
            MAX_REGISTRATION_MODULE_BYTES
        );
    }
    state.module_bytes = module_bytes;
    let module = if let Some(tree) = parse_module(&source, path) {
        if tree.root_node().has_error() {
            bail!(
                "registration module {} contains JavaScript/TypeScript syntax errors; refusing recovered exports",
                path.display()
            );
        }
        Some(collect_module_facts(&tree, &source))
    } else {
        None
    };
    state.modules.insert(path.to_owned(), module.clone());
    Ok(module)
}

fn collect_module_facts(tree: &tree_sitter::Tree, source: &str) -> ModuleFacts {
    let source = source.as_bytes();
    let scope = ExportScope::new(tree.root_node(), source);
    let mut create_bdd_aliases = BTreeSet::new();
    let mut local_registrations = RegistrationExports::new();
    let mut imported_bindings = BTreeMap::new();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        match node.kind() {
            "import_statement"
                if import_has_runtime_bindings(node)
                    && (!import_requires_loader(node) || scope.loader.available(node)) =>
            {
                if let Some(module) = import_module(node, source) {
                    collect_imported_binding_origins(node, source, module, &mut imported_bindings);
                    if is_supported_module(module) {
                        let available = registration_exports_for_module(module);
                        collect_imported_registrations(
                            node,
                            source,
                            &available,
                            &mut local_registrations,
                        );
                    }
                    collect_factory_aliases(
                        node,
                        source,
                        &registration_exports_for_module(module),
                        &mut create_bdd_aliases,
                    );
                }
            }
            "variable_declarator" if is_top_level_variable(node) => {
                collect_commonjs_imports(
                    node,
                    source,
                    &mut create_bdd_aliases,
                    &mut local_registrations,
                    &scope.loader,
                );
            }
            _ => {}
        }
        push_named_children_reverse(node, &mut stack);
    }

    let mut facts = ExportFacts::default();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        match node.kind() {
            "variable_declarator" if is_top_level_variable(node) => {
                collect_create_bdd_bindings(
                    node,
                    source,
                    &create_bdd_aliases,
                    &mut local_registrations,
                    &mut facts.direct_export_names,
                );
            }
            "export_statement" if !is_type_only_declaration(node) => {
                if let Some(module) = import_module(node, source) {
                    let specifiers = export_specifiers(node, source);
                    let star = is_star_export(node);
                    if star || !specifiers.is_empty() {
                        facts.reexports.push(Reexport {
                            module: module.to_owned(),
                            specifiers,
                            star,
                        });
                    }
                } else {
                    facts
                        .direct_export_names
                        .extend(export_specifiers(node, source));
                }
            }
            "assignment_expression" => {
                collect_commonjs_export_assignment(node, source, &scope, &mut facts);
            }
            "call_expression" => {
                collect_object_assign_exports(node, source, &scope, &mut facts);
            }
            _ => {}
        }
        push_named_children_reverse(node, &mut stack);
    }

    let mut direct_exports = RegistrationExports::new();
    let ExportFacts {
        direct_export_names,
        mut reexports,
        incomplete: mut exports_incomplete,
    } = facts;
    for (local, exported) in direct_export_names {
        if let Some(registration) = local_registrations.get(&local).cloned() {
            direct_exports.insert(exported, registration);
        } else if let Some((module, imported)) = imported_bindings.get(&local) {
            // `import { Given as Setup } from './a'; export { Setup as Given }` is semantically
            // a re-export even though its syntax is split across two statements. Keeping the
            // module edge preserves provenance through arbitrarily chained local barrels.
            reexports.push(Reexport {
                module: module.clone(),
                specifiers: vec![(imported.clone(), exported)],
                star: false,
            });
        } else if scope.rejected_loader_dependencies.contains(&local) {
            exports_incomplete = true;
        }
    }
    let framework = direct_exports
        .values()
        .fold(Framework::Unknown, |current, export| {
            merge_framework(current, export.framework)
        });
    ModuleFacts {
        reexports,
        direct_exports,
        framework,
        exports_incomplete,
    }
}

/// Records a CommonJS `module.exports = …` or `exports.<name> = …` assignment as exports.
///
/// Only a value that could hide a registration sets incompleteness; see `export_values`. An inert
/// value (`exports.helper = () => {}`, `module.exports = class Page {}`) cannot, and is left
/// silent, so an ordinary CommonJS module does not warn.
fn collect_commonjs_export_assignment<'a>(
    node: Node<'a>,
    source: &'a [u8],
    scope: &ExportScope<'a>,
    facts: &mut ExportFacts,
) {
    // A well-formed assignment always has both sides; a partial one from error recovery matches
    // nothing below, so no separate guard is needed.
    let target = node
        .child_by_field_name("left")
        .and_then(|left| commonjs_export_target(left, source));
    match export_position(node) {
        // Not a module export: `module`/`exports` inside a callable are ordinary names.
        ExportPosition::InsideCallable => return,
        // A conditional export cannot be resolved, but if it touches the exports object a
        // registration may be hidden behind it, so the module fails closed.
        ExportPosition::ModuleConditional => {
            if target.is_some() {
                facts.incomplete = true;
            }
            return;
        }
        ExportPosition::ModuleBody => {}
    }
    let right = node.child_by_field_name("right");
    match (target, right) {
        (Some(CommonjsExportTarget::All), Some(right)) => {
            collect_commonjs_object_exports(right, source, scope, facts);
        }
        // A bracket export names something the analyzer cannot resolve; fail closed.
        (Some(CommonjsExportTarget::Opaque), _) => facts.incomplete = true,
        (Some(CommonjsExportTarget::Named(name)), Some(right)) => {
            if let Some((module, imported)) = required_member(right, source, &scope.loader) {
                // `exports.step = require('./a').step`
                facts.reexports.push(Reexport {
                    module: module.to_owned(),
                    specifiers: vec![(imported.to_owned(), name.to_owned())],
                    star: false,
                });
            } else if require_specifier(right, source, &scope.loader).is_some() {
                // `exports.steps = require('./a')` assigns the whole module object to one name; the
                // analyzer does not model namespace-member registration, so it may hide steps.
                facts.incomplete = true;
            } else if right.kind() == "identifier" {
                // `exports.Given = Given` re-exports a local binding; resolves against
                // `local_registrations`, contributing nothing when the local is not a registration.
                facts
                    .direct_export_names
                    .push((node_text(right, source).to_owned(), name.to_owned()));
            } else if !matches!(scope.classify(right, source), ExportValue::Inert) {
                // `exports.Given = makeGiven()`, `= cucumber.Given`, or `= { Given }` can carry a
                // registration the analyzer cannot resolve, so it fails closed rather than dropping
                // it silently. An inert value exports nothing and stays quiet.
                facts.incomplete = true;
            }
        }
        _ => {}
    }
}

/// Records the value on the right of `module.exports = …`.
fn collect_commonjs_object_exports<'a>(
    right: Node<'a>,
    source: &'a [u8],
    scope: &ExportScope<'a>,
    facts: &mut ExportFacts,
) {
    let right = match scope.classify(right, source) {
        // `module.exports = require('./a')`, directly or through a `const`.
        ExportValue::Module(module) => {
            facts.reexports.push(Reexport {
                module: module.to_owned(),
                specifiers: Vec::new(),
                star: true,
            });
            return;
        }
        // `module.exports = class Page {}`, a plain helper function, a literal.
        ExportValue::Inert => return,
        // An object literal, directly or through an unmutated `const`.
        ExportValue::Object(object) => object,
        // A factory call, an instance, a mutated or reassigned binding, or any other form the
        // analyzer cannot introspect can hide registrations.
        ExportValue::Opaque => {
            facts.incomplete = true;
            return;
        }
    };
    let mut cursor = right.walk();
    for property in right.named_children(&mut cursor) {
        match property.kind() {
            "comment" => {}
            "shorthand_property_identifier" => {
                let name = node_text(property, source);
                facts
                    .direct_export_names
                    .push((name.to_owned(), name.to_owned()));
            }
            "pair" => {
                let exported = property
                    .child_by_field_name("key")
                    .and_then(|key| property_name(key, source));
                let value = property.child_by_field_name("value");
                if let (Some(exported), Some(value)) = (exported, value) {
                    if value.kind() == "identifier" {
                        facts
                            .direct_export_names
                            .push((node_text(value, source).to_owned(), exported.to_owned()));
                    } else if !scope.is_inert(value, source) {
                        // `Given: makeGiven()` and other values that are not inert are containers
                        // the analyzer cannot introspect.
                        facts.incomplete = true;
                    }
                } else {
                    // A computed key, or a malformed pair, is a form the analyzer cannot model.
                    facts.incomplete = true;
                }
            }
            "spread_element" => {
                if let Some(module) = property
                    .named_child(0)
                    .and_then(|argument| require_specifier(argument, source, &scope.loader))
                {
                    facts.reexports.push(Reexport {
                        module: module.to_owned(),
                        specifiers: Vec::new(),
                        star: true,
                    });
                } else {
                    facts.incomplete = true;
                }
            }
            // A method that never refers to a registration is inert; see `export_values`.
            "method_definition" if scope.is_inert(property, source) => {}
            // Any other method, or an unmodeled property form, can carry a registration.
            _ => facts.incomplete = true,
        }
    }
}

/// Records `Object.assign(module.exports, require('./a'), { … })` as re-exports.
fn collect_object_assign_exports<'a>(
    node: Node<'a>,
    source: &'a [u8],
    scope: &ExportScope<'a>,
    facts: &mut ExportFacts,
) {
    // An `Object.assign` call always carries an argument list; the absent case matches nothing.
    let arguments = (call_member(node, source) == Some(("Object", "assign")))
        .then(|| node.child_by_field_name("arguments"))
        .flatten();
    let Some(arguments) = arguments else {
        return;
    };
    let mut cursor = arguments.walk();
    let mut arguments = arguments.named_children(&mut cursor);
    // The first argument is the assignment target; it must be `module.exports` for this to be an
    // export merge rather than an unrelated `Object.assign`.
    let is_export_merge = arguments.next().is_some_and(|target| {
        matches!(
            commonjs_export_target(target, source),
            Some(CommonjsExportTarget::All)
        )
    });
    if !is_export_merge {
        return;
    }
    match export_position(node) {
        // A merge inside a callable does not touch the module record.
        ExportPosition::InsideCallable => return,
        // A conditional merge into `module.exports` may hide registrations; fail closed.
        ExportPosition::ModuleConditional => {
            facts.incomplete = true;
            return;
        }
        ExportPosition::ModuleBody => {}
    }
    for argument in arguments {
        if let Some(module) = require_specifier(argument, source, &scope.loader) {
            facts.reexports.push(Reexport {
                module: module.to_owned(),
                specifiers: Vec::new(),
                star: true,
            });
        } else if !scope.is_inert(argument, source) {
            facts.incomplete = true;
        }
    }
}

enum CommonjsExportTarget<'a> {
    All,
    Named(&'a str),
    /// An `exports`/`module.exports` target the analyzer recognizes but cannot name — a bracket
    /// access such as `exports[name]` or `module.exports['Given']`. It touches the exports object,
    /// so a registration behind it must fail closed rather than being silently dropped.
    Opaque,
}

/// Where an assignment or call sits relative to the module record.
enum ExportPosition {
    /// A direct statement of the program body: a real, unconditional CommonJS export.
    ModuleBody,
    /// Module scope but under control flow — an `if`, loop, `try`, or bare block — so whether it
    /// runs cannot be known statically. An export here cannot be resolved but must not vanish.
    ModuleConditional,
    /// Inside a function or class, where `module`/`exports` are ordinary names rather than the
    /// module record, so an assignment to them is not a module export at all.
    InsideCallable,
}

/// Classifies where `node` sits: a direct module-body statement, module scope under control flow, or
/// inside a function or class.
fn export_position(node: Node<'_>) -> ExportPosition {
    // A callable or class anywhere above means `module`/`exports` here are ordinary names bound in
    // that scope, not the module record.
    let mut current = node;
    while let Some(parent) = current.parent() {
        if matches!(
            parent.kind(),
            "function_declaration"
                | "generator_function_declaration"
                | "function_expression"
                | "generator_function"
                | "arrow_function"
                | "method_definition"
                | "class_declaration"
                | "abstract_class_declaration"
                | "class"
        ) {
            return ExportPosition::InsideCallable;
        }
        current = parent;
    }
    // At module scope: a direct body statement (`program → expression_statement → node`) is an
    // unconditional export; anything reached through control flow — an `if`, loop, `try`, or bare
    // block — is conditional.
    let direct_body = node.parent().is_some_and(|statement| {
        statement.kind() == "expression_statement"
            && statement
                .parent()
                .is_some_and(|parent| parent.kind() == "program")
    });
    if direct_body {
        ExportPosition::ModuleBody
    } else {
        ExportPosition::ModuleConditional
    }
}

/// Recognizes an assignment's left-hand side as a CommonJS export target: `module.exports` (→ `All`),
/// `exports.<name>` / `module.exports.<name>` (→ `Named`), or a bracket access on either (→ `Opaque`,
/// which fails closed).
fn commonjs_export_target<'a>(
    node: Node<'_>,
    source: &'a [u8],
) -> Option<CommonjsExportTarget<'a>> {
    match node.kind() {
        "member_expression" => {
            let object = node.child_by_field_name("object")?;
            let name = node
                .child_by_field_name("property")
                .filter(|property| property.kind() == "property_identifier")
                .map(|property| node_text(property, source))?;
            match object.kind() {
                // `module.exports = …` / `exports.name = …`
                "identifier" => match (node_text(object, source), name) {
                    ("module", "exports") => Some(CommonjsExportTarget::All),
                    ("exports", _) => Some(CommonjsExportTarget::Named(name)),
                    _ => None,
                },
                // `module.exports.name = …` names a single export off the module object.
                "member_expression" if is_module_exports(object, source) => {
                    Some(CommonjsExportTarget::Named(name))
                }
                _ => None,
            }
        }
        // `exports[…] = …` / `module.exports[…] = …`. A static key could be modeled, but the
        // documented contract only requires the form to fail closed, so every bracket export is
        // opaque and marks the module incomplete.
        "subscript_expression" => {
            let object = node.child_by_field_name("object")?;
            let targets_exports = (object.kind() == "identifier"
                && node_text(object, source) == "exports")
                || is_module_exports(object, source);
            targets_exports.then_some(CommonjsExportTarget::Opaque)
        }
        _ => None,
    }
}

/// Whether `node` is exactly the member expression `module.exports`.
fn is_module_exports(node: Node<'_>, source: &[u8]) -> bool {
    node.kind() == "member_expression"
        && node.child_by_field_name("object").is_some_and(|object| {
            object.kind() == "identifier" && node_text(object, source) == "module"
        })
        && node
            .child_by_field_name("property")
            .is_some_and(|property| node_text(property, source) == "exports")
}

/// Returns the specifier of a `require('…')` call, unwrapping transparent wrappers.
fn require_specifier<'a>(
    node: Node<'_>,
    source: &'a [u8],
    loader: &RequireBindings,
) -> Option<&'a str> {
    (call_identifier(node, source) == Some("require") && loader.available(node))
        .then(|| call_string_argument(node, source))
        .flatten()
}

/// Returns `(module, member)` for `require('…').member`.
fn required_member<'a>(
    node: Node<'_>,
    source: &'a [u8],
    loader: &RequireBindings,
) -> Option<(&'a str, &'a str)> {
    if node.kind() != "member_expression" {
        return None;
    }
    let module = require_specifier(node.child_by_field_name("object")?, source, loader)?;
    let property = node.child_by_field_name("property")?;
    (property.kind() == "property_identifier").then(|| (module, node_text(property, source)))
}

/// Returns the `(object, property)` identifiers of a plain `object.property(...)` call.
fn call_member<'a>(call: Node<'_>, source: &'a [u8]) -> Option<(&'a str, &'a str)> {
    let function = call.child_by_field_name("function")?;
    if function.kind() != "member_expression" {
        return None;
    }
    let object = function.child_by_field_name("object")?;
    let property = function.child_by_field_name("property")?;
    (object.kind() == "identifier" && property.kind() == "property_identifier")
        .then(|| (node_text(object, source), node_text(property, source)))
}

/// Returns the static name of an object-literal property key.
fn property_name<'a>(key: Node<'_>, source: &'a [u8]) -> Option<&'a str> {
    match key.kind() {
        "property_identifier" => Some(node_text(key, source)),
        "string" => string_literal(key, source),
        _ => None,
    }
}

fn collect_imported_registrations(
    import: Node<'_>,
    source: &[u8],
    available: &RegistrationExports,
    local_registrations: &mut RegistrationExports,
) {
    let mut stack = vec![import];
    while let Some(node) = stack.pop() {
        if node.kind() == "import_specifier" && !is_type_only_specifier(node) {
            if let Some(name) = node.child_by_field_name("name") {
                let imported = node_text(name, source);
                if let Some(registration) = available.get(imported) {
                    let local = node
                        .child_by_field_name("alias")
                        .map_or(imported, |alias| node_text(alias, source));
                    local_registrations.insert(local.to_owned(), registration.clone());
                }
            }
        }
        push_named_children_reverse(node, &mut stack);
    }
}

fn collect_imported_binding_origins(
    import: Node<'_>,
    source: &[u8],
    module: &str,
    origins: &mut BTreeMap<String, (String, String)>,
) {
    let mut stack = vec![import];
    while let Some(node) = stack.pop() {
        if node.kind() == "import_specifier" && !is_type_only_specifier(node) {
            if let Some(name) = node.child_by_field_name("name") {
                let imported = node_text(name, source);
                let local = node
                    .child_by_field_name("alias")
                    .map_or(imported, |alias| node_text(alias, source));
                origins.insert(local.to_owned(), (module.to_owned(), imported.to_owned()));
            }
        }
        push_named_children_reverse(node, &mut stack);
    }
}

fn collect_factory_aliases(
    import: Node<'_>,
    source: &[u8],
    available: &RegistrationExports,
    aliases: &mut BTreeSet<String>,
) {
    let mut stack = vec![import];
    while let Some(node) = stack.pop() {
        if node.kind() == "import_specifier" && !is_type_only_specifier(node) {
            if let Some(name) = node.child_by_field_name("name") {
                let imported = node_text(name, source);
                if available.get(imported).is_some_and(|export| {
                    export.kind == super::frameworks::RegistrationExportKind::Factory
                }) {
                    let local = node
                        .child_by_field_name("alias")
                        .map_or(imported, |alias| node_text(alias, source));
                    aliases.insert(local.to_owned());
                }
            }
        }
        push_named_children_reverse(node, &mut stack);
    }
}

fn collect_commonjs_imports(
    declarator: Node<'_>,
    source: &[u8],
    create_bdd_aliases: &mut BTreeSet<String>,
    local_registrations: &mut RegistrationExports,
    loader: &RequireBindings,
) {
    let (Some(pattern), Some(value)) = (
        declarator.child_by_field_name("name"),
        declarator.child_by_field_name("value"),
    ) else {
        return;
    };
    if pattern.kind() != "object_pattern"
        || call_identifier(value, source) != Some("require")
        || !loader.available(value)
    {
        return;
    }
    let Some(module) = call_string_argument(value, source) else {
        return;
    };
    if is_supported_module(module) {
        collect_pattern_registrations(
            pattern,
            source,
            &registration_exports_for_module(module),
            local_registrations,
        );
    }
    if module == super::frameworks::PLAYWRIGHT_MODULE {
        collect_pattern_alias(pattern, source, "createBdd", create_bdd_aliases);
    }
}

fn collect_pattern_registrations(
    pattern: Node<'_>,
    source: &[u8],
    available: &RegistrationExports,
    local_registrations: &mut RegistrationExports,
) {
    let mut cursor = pattern.walk();
    for binding in pattern.named_children(&mut cursor) {
        let (imported, local) = pattern_binding(binding, source);
        if let (Some(imported), Some(local)) = (imported, local) {
            if let Some(registration) = available.get(imported) {
                local_registrations.insert(local.to_owned(), registration.clone());
            }
        }
    }
}

fn collect_pattern_alias(
    pattern: Node<'_>,
    source: &[u8],
    expected: &str,
    aliases: &mut BTreeSet<String>,
) {
    let mut cursor = pattern.walk();
    for binding in pattern.named_children(&mut cursor) {
        let (imported, local) = pattern_binding(binding, source);
        if imported == Some(expected) {
            if let Some(local) = local {
                aliases.insert(local.to_owned());
            }
        }
    }
}

fn pattern_binding<'a>(binding: Node<'_>, source: &'a [u8]) -> (Option<&'a str>, Option<&'a str>) {
    match binding.kind() {
        "shorthand_property_identifier_pattern" => {
            let name = node_text(binding, source);
            (Some(name), Some(name))
        }
        "pair_pattern" => {
            let key = binding.child_by_field_name("key");
            let value = binding.child_by_field_name("value");
            match (key, value) {
                (Some(key), Some(value)) if value.kind() == "identifier" => {
                    (Some(node_text(key, source)), Some(node_text(value, source)))
                }
                _ => (None, None),
            }
        }
        _ => (None, None),
    }
}

fn collect_create_bdd_bindings(
    declarator: Node<'_>,
    source: &[u8],
    create_bdd_aliases: &BTreeSet<String>,
    local_registrations: &mut RegistrationExports,
    direct_export_names: &mut Vec<(String, String)>,
) {
    let (Some(pattern), Some(value)) = (
        declarator.child_by_field_name("name"),
        declarator.child_by_field_name("value"),
    ) else {
        return;
    };
    if pattern.kind() != "object_pattern"
        || call_identifier(value, source).is_none_or(|name| !create_bdd_aliases.contains(name))
    {
        return;
    }

    let directly_exported = is_directly_exported_variable(declarator);
    let available = registration_exports_for_framework(Framework::PlaywrightBdd);
    let mut cursor = pattern.walk();
    for binding in pattern.named_children(&mut cursor) {
        let (registration, local) = match binding.kind() {
            "shorthand_property_identifier_pattern" => {
                let name = node_text(binding, source);
                (name, name)
            }
            "pair_pattern" => {
                let (Some(key), Some(value)) = (
                    binding.child_by_field_name("key"),
                    binding.child_by_field_name("value"),
                ) else {
                    continue;
                };
                if value.kind() != "identifier" {
                    continue;
                }
                (node_text(key, source), node_text(value, source))
            }
            _ => continue,
        };
        if let Some(registration) = available.get(registration) {
            local_registrations.insert(local.to_owned(), registration.clone());
            if directly_exported {
                direct_export_names.push((local.to_owned(), local.to_owned()));
            }
        }
    }
}

fn call_identifier<'a>(mut call: Node<'_>, source: &'a [u8]) -> Option<&'a str> {
    while matches!(
        call.kind(),
        "parenthesized_expression"
            | "as_expression"
            | "satisfies_expression"
            | "non_null_expression"
    ) {
        call = call.named_child(0)?;
    }
    if call.kind() != "call_expression" {
        return None;
    }
    let mut function = call.child_by_field_name("function")?;
    while matches!(
        function.kind(),
        "parenthesized_expression"
            | "as_expression"
            | "satisfies_expression"
            | "non_null_expression"
            | "instantiation_expression"
    ) {
        function = function.named_child(0)?;
    }
    (function.kind() == "identifier").then(|| node_text(function, source))
}

fn is_directly_exported_variable(declarator: Node<'_>) -> bool {
    declarator
        .parent()
        .and_then(|declaration| declaration.parent())
        .is_some_and(|parent| parent.kind() == "export_statement")
}

fn project_boundary(importer: &Path) -> Option<PathBuf> {
    let parent = importer.parent()?;
    let parent = parent.canonicalize().ok()?;
    for ancestor in parent.ancestors() {
        if ancestor.join("package.json").is_file() {
            return Some(ancestor.to_owned());
        }
    }
    Some(parent)
}

fn parse_module(source: &str, path: &Path) -> Option<tree_sitter::Tree> {
    let language = language_for_path(path)?;
    let mut parser = Parser::new();
    parser.set_language(&grammar_for_language(language)).ok()?;
    parser.parse(source, None)
}

fn export_specifiers(export: Node<'_>, source: &[u8]) -> Vec<(String, String)> {
    let mut specifiers = Vec::new();
    let mut stack = vec![export];
    while let Some(node) = stack.pop() {
        if node.kind() == "export_specifier" && !is_type_only_specifier(node) {
            if let Some(name) = node.child_by_field_name("name") {
                let imported = node_text(name, source);
                let exported = node
                    .child_by_field_name("alias")
                    .map_or(imported, |alias| node_text(alias, source));
                specifiers.push((imported.to_owned(), exported.to_owned()));
            }
        }
        push_named_children_reverse(node, &mut stack);
    }
    specifiers
}

#[cfg(test)]
mod tests;