Skip to main content

fallow_core/plugins/
config_parser.rs

1//! AST-based config file parser utilities.
2//!
3//! Helpers for statically extracting config values from JS/TS files.
4
5use std::path::{Path, PathBuf};
6
7use crate::discover::project_read::{carry_project_root, config_project_root, read_project_file};
8use fallow_extract::{JsText, visitor::extract_import_from_callable};
9use oxc_ast::ast::*;
10use oxc_span::SourceType;
11use rustc_hash::FxHashSet;
12
13#[path = "config_parser_const_inline.rs"]
14mod const_inline;
15use const_inline::holds_one_stable_object;
16#[path = "config_parser_local_inline.rs"]
17mod local_inline;
18#[path = "config_parser_merge_config.rs"]
19mod merge_config;
20use merge_config::{read_each_config, read_last_config, read_last_match};
21#[path = "config_parser_multi_config.rs"]
22mod multi_config;
23use multi_config::find_default_export_array;
24#[path = "config_parser_string_values.rs"]
25mod string_values;
26pub(crate) use multi_config::{
27    extract_each_config_entries, extract_each_config_path_aliases,
28    extract_each_config_require_strings, extract_each_config_shallow_strings, find_config_objects,
29};
30use string_values::string_or_array_in;
31#[path = "config_parser_alias_constant.rs"]
32mod alias_constant;
33#[path = "config_parser_alias_entry.rs"]
34pub(super) mod alias_entry;
35#[path = "config_parser_vite_plugin_call.rs"]
36pub(crate) mod vite_plugin_call;
37pub(crate) use vite_plugin_call::extract_vite_plugin_call_option_path;
38use vite_plugin_call::is_plugin_binding_call;
39
40/// Extract all import source specifiers from JS/TS source code.
41#[must_use]
42pub(crate) fn extract_imports(source: &str, path: &Path) -> Vec<String> {
43    extract_from_source(source, path, |program| {
44        let mut sources = Vec::new();
45        for stmt in &program.body {
46            if let Statement::ImportDeclaration(decl) = stmt {
47                sources.push(decl.source.value.text().into_owned());
48            }
49        }
50        Some(sources)
51    })
52    .unwrap_or_default()
53}
54
55/// Extract import sources and top-level `require('...')` statements.
56#[must_use]
57pub(crate) fn extract_imports_and_requires(source: &str, path: &Path) -> Vec<String> {
58    extract_from_source(source, path, |program| {
59        let mut sources = Vec::new();
60        for stmt in &program.body {
61            match stmt {
62                Statement::ImportDeclaration(decl) => {
63                    sources.push(decl.source.value.text().into_owned());
64                }
65                Statement::ExpressionStatement(expr) => {
66                    if let Expression::CallExpression(call) = &expr.expression
67                        && is_require_call(call)
68                        && let Some(s) = get_require_source(call)
69                    {
70                        sources.push(s);
71                    }
72                }
73                _ => {}
74            }
75        }
76        Some(sources)
77    })
78    .unwrap_or_default()
79}
80
81/// Extract string array from a property at a nested path in a config's default export.
82#[must_use]
83pub(crate) fn extract_config_string_array(
84    source: &str,
85    path: &Path,
86    prop_path: &[&str],
87) -> Vec<String> {
88    extract_from_source(source, path, |program| {
89        read_each_config(program, |obj| {
90            get_nested_string_array_from_object(obj, prop_path)
91        })
92    })
93    .unwrap_or_default()
94}
95
96/// Extract a single string from a property at a nested path.
97#[must_use]
98pub(crate) fn extract_config_string(
99    source: &str,
100    path: &Path,
101    prop_path: &[&str],
102) -> Option<String> {
103    extract_from_source(source, path, |program| {
104        read_last_config(program, prop_path, get_nested_string_from_object)
105    })
106}
107
108/// Extract a shell command string from a property at a nested path.
109#[must_use]
110pub(crate) fn extract_config_command(
111    source: &str,
112    path: &Path,
113    prop_path: &[&str],
114) -> Option<String> {
115    extract_from_source(source, path, |program| {
116        read_last_config(program, prop_path, get_nested_command_from_object)
117    })
118}
119
120/// Extract string values from top-level properties of the default export or
121/// `module.exports` object.
122#[must_use]
123pub(crate) fn extract_config_property_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
124    extract_from_source(source, path, |program| {
125        read_each_config(program, |obj| {
126            let mut values = Vec::new();
127            if let Some(prop) = find_property(obj, key) {
128                collect_all_string_values(&prop.value, &mut values);
129            }
130            Some(values)
131        })
132    })
133    .unwrap_or_default()
134}
135
136/// Extract only top-level string values from a property's array.
137#[must_use]
138pub(crate) fn extract_config_shallow_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
139    extract_from_source(source, path, |program| {
140        read_each_config(program, |obj| {
141            let prop = find_property(obj, key)?;
142            Some(collect_shallow_string_values(&prop.value))
143        })
144    })
145    .unwrap_or_default()
146}
147
148/// Extract top-level string values from a config array, including object entries.
149#[must_use]
150pub(crate) fn extract_config_shallow_strings_or_object_property(
151    source: &str,
152    path: &Path,
153    key: &str,
154    object_property: &str,
155) -> Vec<String> {
156    extract_from_source(source, path, |program| {
157        read_each_config(program, |obj| {
158            let prop = find_property(obj, key)?;
159            Some(collect_shallow_string_or_object_property_values(
160                &prop.value,
161                object_property,
162            ))
163        })
164    })
165    .unwrap_or_default()
166}
167
168/// Extract shallow strings from an array property inside a nested object path.
169#[must_use]
170pub(crate) fn extract_config_nested_shallow_strings(
171    source: &str,
172    path: &Path,
173    outer_path: &[&str],
174    key: &str,
175) -> Vec<String> {
176    extract_from_source(source, path, |program| {
177        read_each_config(program, |obj| {
178            let nested = get_nested_expression(obj, outer_path)?;
179            if let Expression::ObjectExpression(nested_obj) = nested {
180                let prop = find_property(nested_obj, key)?;
181                Some(collect_shallow_string_values(&prop.value))
182            } else {
183                None
184            }
185        })
186    })
187    .unwrap_or_default()
188}
189
190/// Get a top-level property expression from an object.
191pub(crate) fn property_expr<'a>(
192    obj: &'a ObjectExpression<'a>,
193    key: &str,
194) -> Option<&'a Expression<'a>> {
195    find_property(obj, key).map(|prop| &prop.value)
196}
197
198/// Get a top-level property object from an object.
199pub(crate) fn property_object<'a>(
200    obj: &'a ObjectExpression<'a>,
201    key: &str,
202) -> Option<&'a ObjectExpression<'a>> {
203    property_expr(obj, key).and_then(object_expression)
204}
205
206/// Get a string-like top-level property value from an object.
207pub(crate) fn property_string(obj: &ObjectExpression<'_>, key: &str) -> Option<String> {
208    property_expr(obj, key).and_then(expression_to_string)
209}
210
211/// Convert an expression to an object expression when it is statically recoverable.
212pub(crate) fn object_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ObjectExpression<'a>> {
213    match expr {
214        Expression::ObjectExpression(obj) => Some(obj),
215        Expression::ParenthesizedExpression(paren) => object_expression(&paren.expression),
216        Expression::TSSatisfiesExpression(ts_sat) => object_expression(&ts_sat.expression),
217        Expression::TSAsExpression(ts_as) => object_expression(&ts_as.expression),
218        _ => None,
219    }
220}
221
222/// Convert an expression to an array expression when it is statically recoverable.
223pub(crate) fn array_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ArrayExpression<'a>> {
224    match expr {
225        Expression::ArrayExpression(arr) => Some(arr),
226        Expression::ParenthesizedExpression(paren) => array_expression(&paren.expression),
227        Expression::TSSatisfiesExpression(ts_sat) => array_expression(&ts_sat.expression),
228        Expression::TSAsExpression(ts_as) => array_expression(&ts_as.expression),
229        _ => None,
230    }
231}
232
233/// Convert a config path string to a `PathBuf` with platform-independent
234/// separator handling.
235pub(crate) fn path_from_config_string(raw: &str) -> PathBuf {
236    PathBuf::from(raw.replace('\\', "/"))
237}
238
239/// Convert a config path to the forward-slash string form used in plugin output.
240pub(crate) fn path_to_config_string(path: &Path) -> String {
241    path.to_string_lossy().replace('\\', "/")
242}
243
244/// Convert a path-like expression to a statically recoverable path.
245pub(crate) fn expression_to_path(expr: &Expression<'_>) -> Option<PathBuf> {
246    expression_to_path_string(expr).map(|path| path_from_config_string(&path))
247}
248
249/// Convert a path-like expression to zero or more statically recoverable paths.
250pub(crate) fn expression_to_path_values(expr: &Expression<'_>) -> Vec<PathBuf> {
251    match expr {
252        Expression::ArrayExpression(arr) => arr
253            .elements
254            .iter()
255            .filter_map(|element| element.as_expression().and_then(expression_to_path))
256            .collect(),
257        _ => expression_to_path(expr).into_iter().collect(),
258    }
259}
260
261/// True when an expression explicitly disables a config section.
262pub(crate) fn is_disabled_expression(expr: &Expression<'_>) -> bool {
263    matches!(expr, Expression::BooleanLiteral(boolean) if !boolean.value)
264        || matches!(expr, Expression::NullLiteral(_))
265}
266
267/// True when a nested config property is a static `true` boolean or object value.
268#[must_use]
269pub(crate) fn extract_config_truthy_bool_or_object(
270    source: &str,
271    path: &Path,
272    prop_path: &[&str],
273) -> bool {
274    extract_from_source(source, path, |program| {
275        read_last_config(program, prop_path, |obj, key_path| {
276            let expr = get_nested_expression(obj, key_path)?;
277            Some(is_truthy_bool_or_object(expr))
278        })
279    })
280    .unwrap_or(false)
281}
282
283fn is_truthy_bool_or_object(expr: &Expression<'_>) -> bool {
284    match expr {
285        Expression::BooleanLiteral(boolean) => boolean.value,
286        Expression::ObjectExpression(_) => true,
287        Expression::ParenthesizedExpression(paren) => is_truthy_bool_or_object(&paren.expression),
288        Expression::TSSatisfiesExpression(ts_sat) => is_truthy_bool_or_object(&ts_sat.expression),
289        Expression::TSAsExpression(ts_as) => is_truthy_bool_or_object(&ts_as.expression),
290        _ => false,
291    }
292}
293
294/// Extract keys of an object property at a nested path.
295#[must_use]
296pub(crate) fn extract_config_object_keys(
297    source: &str,
298    path: &Path,
299    prop_path: &[&str],
300) -> Vec<String> {
301    extract_from_source(source, path, |program| {
302        read_each_config(program, |obj| get_nested_object_keys(obj, prop_path))
303    })
304    .unwrap_or_default()
305}
306
307/// Extract a value that may be a single string, string array, or object with
308/// string/array values.
309#[must_use]
310pub(crate) fn extract_config_string_or_array(
311    source: &str,
312    path: &Path,
313    prop_path: &[&str],
314) -> Vec<String> {
315    extract_from_source(source, path, |program| {
316        read_each_config(program, |obj| {
317            get_nested_string_or_array(obj, prop_path, PathScope::Program(program))
318        })
319    })
320    .unwrap_or_default()
321}
322
323/// Extract a string, array, or object-map value from each config of a
324/// default-exported config array, or from the single config object.
325///
326/// Supports `export default [...]` and `export default defineConfig([...])`.
327/// The function reads `prop_path` from each object element of the array. When
328/// the default export is not an array, it reads the config object.
329#[must_use]
330pub(crate) fn extract_config_array_or_object_string_or_array(
331    source: &str,
332    path: &Path,
333    prop_path: &[&str],
334) -> Vec<String> {
335    extract_from_source(source, path, |program| {
336        let Some(arr) = find_default_export_array(program) else {
337            return read_each_config(program, |obj| {
338                get_nested_string_or_array(obj, prop_path, PathScope::Program(program))
339            });
340        };
341        let values = arr
342            .elements
343            .iter()
344            .filter_map(|element| element.as_expression().and_then(object_expression))
345            .filter_map(|element_obj| {
346                get_nested_string_or_array(element_obj, prop_path, PathScope::Program(program))
347            })
348            .flatten()
349            .collect();
350        Some(values)
351    })
352    .unwrap_or_default()
353}
354
355/// Extract a statically recoverable path-like value from a property path.
356#[must_use]
357pub(crate) fn extract_config_path(
358    source: &str,
359    path: &Path,
360    prop_path: &[&str],
361) -> Option<PathBuf> {
362    extract_from_source(source, path, |program| {
363        read_last_config(program, prop_path, |obj, key_path| {
364            let expr = get_nested_expression(obj, key_path)?;
365            expression_to_path(expr)
366        })
367    })
368}
369
370/// Extract string values from a property path, also searching inside array elements.
371#[must_use]
372pub(crate) fn extract_config_array_nested_string_or_array(
373    source: &str,
374    path: &Path,
375    array_path: &[&str],
376    inner_path: &[&str],
377) -> Vec<String> {
378    extract_from_source(source, path, |program| {
379        read_each_config(program, |obj| {
380            let array_expr = get_nested_expression(obj, array_path)?;
381            let Expression::ArrayExpression(arr) = array_expr else {
382                return None;
383            };
384            let mut results = Vec::new();
385            for element in &arr.elements {
386                if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
387                    && let Some(values) = get_nested_string_or_array(
388                        element_obj,
389                        inner_path,
390                        PathScope::Program(program),
391                    )
392                {
393                    results.extend(values);
394                }
395            }
396            if results.is_empty() {
397                None
398            } else {
399                Some(results)
400            }
401        })
402    })
403    .unwrap_or_default()
404}
405
406/// Extract the string values of each key, one entry per object element of an
407/// array.
408///
409/// Each entry holds one value list per key, in the order of `keys`. A missing
410/// key gives an empty list. Use this function when values of one element must
411/// stay together, for example a `rootDir` and the paths that it anchors.
412#[must_use]
413pub(crate) fn extract_config_array_object_fields(
414    source: &str,
415    path: &Path,
416    array_path: &[&str],
417    keys: &[&str],
418) -> Vec<Vec<Vec<String>>> {
419    extract_from_source(source, path, |program| {
420        read_each_config(program, |obj| {
421            let Expression::ArrayExpression(arr) = get_nested_expression(obj, array_path)? else {
422                return None;
423            };
424            let elements = arr
425                .elements
426                .iter()
427                .filter_map(|element| match element.as_expression() {
428                    Some(Expression::ObjectExpression(element_obj)) => Some(
429                        keys.iter()
430                            .map(|key| {
431                                get_nested_string_or_array(
432                                    element_obj,
433                                    &[key],
434                                    PathScope::Program(program),
435                                )
436                                .unwrap_or_default()
437                            })
438                            .collect(),
439                    ),
440                    _ => None,
441                })
442                .collect();
443            Some(elements)
444        })
445    })
446    .unwrap_or_default()
447}
448
449/// Extract string values from a property path, searching inside all values of an object.
450#[must_use]
451pub(crate) fn extract_config_object_nested_string_or_array(
452    source: &str,
453    path: &Path,
454    object_path: &[&str],
455    inner_path: &[&str],
456) -> Vec<String> {
457    extract_config_object_nested(source, path, object_path, |value_obj| {
458        get_nested_string_or_array(value_obj, inner_path, PathScope::Bare)
459    })
460}
461
462/// Extract a single string value from each object under a property path.
463#[must_use]
464pub(crate) fn extract_config_object_nested_strings(
465    source: &str,
466    path: &Path,
467    object_path: &[&str],
468    inner_path: &[&str],
469) -> Vec<String> {
470    extract_config_object_nested(source, path, object_path, |value_obj| {
471        get_nested_string_from_object(value_obj, inner_path).map(|s| vec![s])
472    })
473}
474
475/// Shared helper for object-nested extraction.
476fn extract_config_object_nested(
477    source: &str,
478    path: &Path,
479    object_path: &[&str],
480    extract_fn: impl Fn(&ObjectExpression<'_>) -> Option<Vec<String>> + Sync,
481) -> Vec<String> {
482    extract_from_source(source, path, |program| {
483        read_each_config(program, |obj| {
484            let obj_expr = get_nested_expression(obj, object_path)?;
485            let Expression::ObjectExpression(target_obj) = obj_expr else {
486                return None;
487            };
488            let mut results = Vec::new();
489            for prop in &target_obj.properties {
490                if let ObjectPropertyKind::ObjectProperty(p) = prop
491                    && let Expression::ObjectExpression(value_obj) = &p.value
492                    && let Some(values) = extract_fn(value_obj)
493                {
494                    results.extend(values);
495                }
496            }
497            if results.is_empty() {
498                None
499            } else {
500                Some(results)
501            }
502        })
503    })
504    .unwrap_or_default()
505}
506
507/// Extract `require('...')` call argument strings from a property's value.
508#[must_use]
509pub(crate) fn extract_config_require_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
510    extract_from_source(source, path, |program| {
511        read_each_config(program, |obj| {
512            let prop = find_property(obj, key)?;
513            Some(collect_require_sources(&prop.value))
514        })
515    })
516    .unwrap_or_default()
517}
518
519/// Extract alias mappings from an object or array-based alias config.
520#[must_use]
521pub(crate) fn extract_config_aliases(
522    source: &str,
523    path: &Path,
524    prop_path: &[&str],
525) -> Vec<(String, String)> {
526    extract_config_aliases_kinded(source, path, prop_path)
527        .into_iter()
528        .map(|(find, replacement, _is_bare)| (find, replacement))
529        .collect()
530}
531
532/// Extract alias mappings where the replacement is a filesystem path value.
533#[must_use]
534pub(crate) fn extract_config_path_aliases(
535    source: &str,
536    path: &Path,
537    prop_path: &[&str],
538) -> Vec<(String, PathBuf)> {
539    extract_config_aliases_kinded(source, path, prop_path)
540        .into_iter()
541        .map(|(find, replacement, _is_bare)| (find, path_from_config_string(&replacement)))
542        .collect()
543}
544
545/// Like [`extract_config_aliases`] but each tuple carries a bare-string flag.
546#[must_use]
547pub(crate) fn extract_config_aliases_kinded(
548    source: &str,
549    path: &Path,
550    prop_path: &[&str],
551) -> Vec<(String, String, bool)> {
552    extract_from_source(source, path, |program| {
553        read_each_config(program, |obj| {
554            let expr = get_nested_expression(obj, prop_path)?;
555            let mut visited = FxHashSet::default();
556            let aliases = resolve_alias_pairs_kinded(program, path, expr, &mut visited, 0);
557            (!aliases.is_empty()).then_some(aliases)
558        })
559    })
560    .unwrap_or_default()
561}
562
563/// Extract kinded alias mappings nested inside an array of config objects.
564///
565/// Each tuple has the same shape as in [`extract_config_aliases_kinded`].
566#[must_use]
567pub(crate) fn extract_config_array_nested_aliases_kinded(
568    source: &str,
569    path: &Path,
570    array_path: &[&str],
571    alias_path: &[&str],
572) -> Vec<(String, String, bool)> {
573    extract_from_source(source, path, |program| {
574        read_each_config(program, |obj| {
575            let array_expr = get_nested_expression(obj, array_path)?;
576            let Expression::ArrayExpression(arr) = array_expr else {
577                return None;
578            };
579            let mut results = Vec::new();
580            for element in &arr.elements {
581                if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
582                    && let Some(alias_expr) = get_nested_expression(element_obj, alias_path)
583                {
584                    results.extend(alias_constant::expression_to_alias_pairs_kinded(
585                        alias_expr,
586                        PathScope::Program(program),
587                    ));
588                }
589            }
590            (!results.is_empty()).then_some(results)
591        })
592    })
593    .unwrap_or_default()
594}
595
596/// Extract kinded aliases from a default-exported ARRAY config.
597#[must_use]
598pub(crate) fn extract_default_export_array_aliases_kinded(
599    source: &str,
600    path: &Path,
601    alias_path: &[&str],
602) -> Vec<(String, String, bool)> {
603    extract_from_source(source, path, |program| {
604        let arr = find_default_export_array(program)?;
605        let mut results = Vec::new();
606        for element in &arr.elements {
607            if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
608                && let Some(alias_expr) = get_nested_expression(element_obj, alias_path)
609            {
610                results.extend(alias_constant::expression_to_alias_pairs_kinded(
611                    alias_expr,
612                    PathScope::Program(program),
613                ));
614            }
615        }
616        (!results.is_empty()).then_some(results)
617    })
618    .unwrap_or_default()
619}
620
621/// True when a parsed config has neither an object nor array default export.
622#[must_use]
623pub(crate) fn config_default_export_unreachable(source: &str, path: &Path) -> bool {
624    extract_from_source(source, path, |program| {
625        let reachable =
626            find_config_object(program).is_some() || find_default_export_array(program).is_some();
627        Some(reachable)
628    })
629    .is_some_and(|reachable| !reachable)
630}
631
632/// Extract string values from a nested array, supporting both string elements and
633/// object elements with a named string/path field.
634///
635/// Useful for configs like:
636/// - `components: ["~/components", { path: "~/feature-components" }]`
637#[must_use]
638pub(crate) fn extract_config_array_object_strings(
639    source: &str,
640    path: &Path,
641    array_path: &[&str],
642    key: &str,
643) -> Vec<String> {
644    extract_from_source(source, path, |program| {
645        read_each_config(program, |obj| {
646            let array_expr = get_nested_expression(obj, array_path)?;
647            let Expression::ArrayExpression(arr) = array_expr else {
648                return None;
649            };
650
651            let mut results = Vec::new();
652            for element in &arr.elements {
653                let Some(expr) = element.as_expression() else {
654                    continue;
655                };
656                match expr {
657                    Expression::ObjectExpression(item) => {
658                        if let Some(prop) = find_property(item, key)
659                            && let Some(value) = expression_to_path_string(&prop.value)
660                        {
661                            results.push(value);
662                        }
663                    }
664                    _ => {
665                        if let Some(value) = expression_to_path_string(expr) {
666                            results.push(value);
667                        }
668                    }
669                }
670            }
671
672            (!results.is_empty()).then_some(results)
673        })
674    })
675    .unwrap_or_default()
676}
677
678/// Extract Storybook-style static directory entries from an array.
679///
680/// Supports string entries and object entries with a string-like `from` plus
681/// optional string-like `to`.
682#[must_use]
683pub(crate) fn extract_config_static_dir_entries(
684    source: &str,
685    path: &Path,
686    array_path: &[&str],
687) -> Vec<(String, Option<String>)> {
688    extract_from_source(source, path, |program| {
689        read_each_config(program, |obj| {
690            let array_expr = get_nested_expression(obj, array_path)?;
691            let Expression::ArrayExpression(arr) = array_expr else {
692                return None;
693            };
694
695            let mut results = Vec::new();
696            for element in &arr.elements {
697                let Some(expr) = element.as_expression() else {
698                    continue;
699                };
700                match expr {
701                    Expression::ObjectExpression(item) => {
702                        if let Some(from) = property_string(item, "from") {
703                            let to = property_string(item, "to");
704                            results.push((from, to));
705                        }
706                    }
707                    _ => {
708                        if let Some(from) = expression_to_path_string(expr) {
709                            results.push((from, None));
710                        }
711                    }
712                }
713            }
714
715            (!results.is_empty()).then_some(results)
716        })
717    })
718    .unwrap_or_default()
719}
720
721/// Extract paired shell command and string values from each object element of an array.
722#[must_use]
723pub(crate) fn extract_config_array_object_command_pairs(
724    source: &str,
725    path: &Path,
726    array_path: &[&str],
727    primary_key: &str,
728    secondary_key: &str,
729) -> Vec<(String, Option<String>)> {
730    extract_from_source(source, path, |program| {
731        read_each_config(program, |obj| {
732            let array_expr = get_nested_expression(obj, array_path)?;
733            let Expression::ArrayExpression(arr) = array_expr else {
734                return None;
735            };
736
737            let mut results = Vec::new();
738            for element in &arr.elements {
739                let Some(Expression::ObjectExpression(item)) = element.as_expression() else {
740                    continue;
741                };
742                let Some(primary) = find_property(item, primary_key)
743                    .and_then(|prop| expression_to_command(&prop.value))
744                else {
745                    continue;
746                };
747                let secondary = find_property(item, secondary_key)
748                    .and_then(|prop| expression_to_path_string(&prop.value));
749                results.push((primary, secondary));
750            }
751
752            (!results.is_empty()).then_some(results)
753        })
754    })
755    .unwrap_or_default()
756}
757
758/// Extract static specifiers from thunk-wrapped dynamic imports inside an
759/// array property.
760///
761/// Captures the `SPEC` argument from each `() => import('SPEC')` element of
762/// an array nested under `prop_path` in the config's default-exported object.
763///
764/// # The pattern
765///
766/// Configs and registries that need to defer module evaluation commonly hold
767/// arrays of *thunks* — zero-argument arrow functions whose body is a single
768/// dynamic import:
769///
770/// ```ts
771/// export default defineConfig({
772///     modules: [
773///         () => import('./feature-a'),
774///         { file: () => import('./feature-b'), enabled: true },
775///     ],
776/// })
777/// ```
778///
779/// `import('SPEC')` is the ECMAScript dynamic-import expression (TC39
780/// dynamic-import proposal, shipped in ES2020): a runtime module loader call
781/// that returns a `Promise<Module>`. Wrapping it in `() => import('SPEC')`
782/// turns "load module X now" into "value that, when invoked, loads module X"
783/// — a thunk the host can call lazily.
784///
785/// The technique predates any single framework. It's the same shape used by
786/// route-level code-splitting (`Vue Router`, `React Router`, `Next.js`),
787/// `React.lazy`, Webpack's documented dynamic-import code-splitting recipes,
788/// and any registry that wants to keep boot cheap, break import cycles, or
789/// let bundlers tree-shake unused branches. Configs that adopt the pattern
790/// can therefore declare large module graphs without forcing eager
791/// evaluation of every entry at config parse time.
792///
793/// # Recognised array element shapes
794///
795/// - Concise arrow: `() => import('SPEC')`
796/// - Block-body arrow with explicit return: `() => { return import('SPEC') }`
797/// - Object form with a `file` property holding the arrow:
798///   `{ file: () => import('SPEC'), /* peer fields */ }`
799///
800/// Non-matching elements (string literals, variables, template-string
801/// specifiers, computed expressions) are silently skipped: callers receive
802/// only the statically-resolvable specifiers, in source order.
803#[must_use]
804pub(crate) fn extract_lazy_imports_in_array(
805    source: &str,
806    path: &Path,
807    prop_path: &[&str],
808) -> Vec<String> {
809    extract_from_source(source, path, |program| {
810        read_each_config(program, |obj| {
811            let array_expr = get_nested_expression(obj, prop_path)?;
812            let Expression::ArrayExpression(arr) = array_expr else {
813                return None;
814            };
815            let mut specs = Vec::new();
816            for element in &arr.elements {
817                let Some(expr) = element.as_expression() else {
818                    continue;
819                };
820                if let Some(spec) = lazy_import_specifier(expr) {
821                    specs.push(spec);
822                }
823            }
824            (!specs.is_empty()).then_some(specs)
825        })
826    })
827    .unwrap_or_default()
828}
829
830/// Read a lazy-import specifier from a single array element expression.
831///
832/// Two outer shapes are accepted at this level (array-element navigation):
833/// - A bare callable: `() => import('SPEC')` or the function-expression
834///   equivalent.
835/// - An object with a `file` property holding the callable:
836///   `{ file: () => import('SPEC'), /* peer fields */ }`.
837///
838/// The actual callable → import peeling is delegated to
839/// [`extract_import_from_callable`], which is shared with the visitor-side
840/// dynamic-import helpers so all three navigation pipelines stay in lockstep
841/// when ECMAScript adds new wrapper shapes.
842fn lazy_import_specifier(expr: &Expression<'_>) -> Option<String> {
843    let callable = match expr {
844        Expression::ObjectExpression(obj) => &find_property(obj, "file")?.value,
845        _ => expr,
846    };
847    let import_expr = extract_import_from_callable(callable)?;
848    expression_to_string(&import_expr.source)
849}
850
851/// Extract the first string of each `[name, options]` tuple in an array at a
852/// property path, such as `modules: [["@nuxt/content", { ... }]]`. Plain
853/// string entries are not returned; read them with
854/// [`extract_config_string_array`].
855#[must_use]
856pub(crate) fn extract_config_array_tuple_heads(
857    source: &str,
858    path: &Path,
859    array_path: &[&str],
860) -> Vec<String> {
861    extract_from_source(source, path, |program| {
862        read_each_config(program, |obj| {
863            let Expression::ArrayExpression(entries) = get_nested_expression(obj, array_path)?
864            else {
865                return None;
866            };
867            let heads = entries
868                .elements
869                .iter()
870                .filter_map(|entry| match entry.as_expression() {
871                    Some(Expression::ArrayExpression(tuple)) => tuple
872                        .elements
873                        .first()
874                        .and_then(ArrayExpressionElement::as_expression)
875                        .and_then(expression_to_string),
876                    _ => None,
877                })
878                .collect();
879            Some(heads)
880        })
881    })
882    .unwrap_or_default()
883}
884
885/// Extract a string-like option from a plugin tuple inside a config plugin array.
886///
887/// Supports config shapes like:
888/// - `{ expo: { plugins: [["expo-router", { root: "src/app" }]] } }`
889/// - `export default { expo: { plugins: [["expo-router", { root: "./src/app" }]] } }`
890/// - `{ plugins: [["expo-router", { root: "./src/routes" }]] }`
891#[must_use]
892fn extract_config_plugin_option_string(
893    source: &str,
894    path: &Path,
895    plugins_path: &[&str],
896    plugin_name: &str,
897    option_key: &str,
898) -> Option<String> {
899    extract_from_source(source, path, |program| {
900        read_last_match(program, |obj| {
901            let plugins_expr = get_nested_expression(obj, plugins_path)?;
902            let Expression::ArrayExpression(plugins) = plugins_expr else {
903                return None;
904            };
905
906            for entry in &plugins.elements {
907                let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
908                    continue;
909                };
910                let Some(plugin_expr) = tuple
911                    .elements
912                    .first()
913                    .and_then(ArrayExpressionElement::as_expression)
914                else {
915                    continue;
916                };
917                if expression_to_string(plugin_expr).as_deref() != Some(plugin_name) {
918                    continue;
919                }
920
921                let Some(options_expr) = tuple
922                    .elements
923                    .get(1)
924                    .and_then(ArrayExpressionElement::as_expression)
925                else {
926                    continue;
927                };
928                let Expression::ObjectExpression(options_obj) = options_expr else {
929                    continue;
930                };
931                let option = find_property(options_obj, option_key)?;
932                return expression_to_path_string(&option.value);
933            }
934
935            None
936        })
937    })
938}
939
940/// Extract a string-like option from the first plugin array path that contains it.
941#[must_use]
942pub(crate) fn extract_config_plugin_option_string_from_paths(
943    source: &str,
944    path: &Path,
945    plugin_paths: &[&[&str]],
946    plugin_name: &str,
947    option_key: &str,
948) -> Option<String> {
949    plugin_paths.iter().find_map(|plugins_path| {
950        extract_config_plugin_option_string(source, path, plugins_path, plugin_name, option_key)
951    })
952}
953
954/// A Vite plugin package whose options object names other packages as strings.
955struct VitePluginOptionReader {
956    package: &'static str,
957    read: fn(&ObjectExpression<'_>, &mut Vec<String>),
958}
959
960/// The Vite plugins whose options name packages that the plugin loads at
961/// build time. The list is closed so that an unknown plugin option never
962/// credits a package.
963const VITE_PLUGIN_OPTION_READERS: &[VitePluginOptionReader] = &[
964    VitePluginOptionReader {
965        package: "@vitejs/plugin-react",
966        read: collect_vite_react_babel_dependencies,
967    },
968    VitePluginOptionReader {
969        package: "@vitejs/plugin-react-swc",
970        read: collect_vite_react_swc_dependencies,
971    },
972    VitePluginOptionReader {
973        package: "@wyw-in-js/vite",
974        read: collect_wyw_babel_options_dependencies,
975    },
976];
977
978/// How many wrapper calls, such as `profile(wyw({ ... }))`, the reader looks
979/// through to find a known plugin call in a `plugins` array entry.
980const MAX_VITE_PLUGIN_WRAPPER_DEPTH: usize = 3;
981
982/// Extract package names that known Vite plugins read from their options in a
983/// Vite-style `plugins` array: Babel plugins and presets of
984/// `@vitejs/plugin-react`, SWC plugins of `@vitejs/plugin-react-swc`, and
985/// `babelOptions` of `@wyw-in-js/vite`.
986#[must_use]
987pub(crate) fn extract_vite_plugin_option_dependencies(source: &str, path: &Path) -> Vec<String> {
988    extract_from_source(source, path, |program| {
989        let bindings: Vec<(PluginImportBindings, &VitePluginOptionReader)> =
990            VITE_PLUGIN_OPTION_READERS
991                .iter()
992                .map(|reader| {
993                    (
994                        collect_plugin_import_bindings(program, reader.package),
995                        reader,
996                    )
997                })
998                .filter(|(imports, _)| !imports.is_empty())
999                .collect();
1000        if bindings.is_empty() {
1001            return None;
1002        }
1003
1004        read_each_config(program, |obj| {
1005            let plugins = get_nested_expression(obj, &["plugins"])?;
1006            let Expression::ArrayExpression(plugin_array) = plugins else {
1007                return None;
1008            };
1009
1010            let mut deps = Vec::new();
1011            for element in &plugin_array.elements {
1012                if let Some(Expression::CallExpression(call)) = element.as_expression() {
1013                    read_vite_plugin_call(call, &bindings, 0, &mut deps);
1014                }
1015            }
1016
1017            (!deps.is_empty()).then_some(deps)
1018        })
1019    })
1020    .unwrap_or_default()
1021}
1022
1023fn read_vite_plugin_call(
1024    call: &CallExpression<'_>,
1025    bindings: &[(PluginImportBindings, &VitePluginOptionReader)],
1026    depth: usize,
1027    deps: &mut Vec<String>,
1028) {
1029    if let Some((_, reader)) = bindings
1030        .iter()
1031        .find(|(imports, _)| is_plugin_binding_call(call, imports))
1032    {
1033        if let Some(Expression::ObjectExpression(options)) =
1034            call.arguments.first().and_then(Argument::as_expression)
1035        {
1036            (reader.read)(options, deps);
1037        }
1038        return;
1039    }
1040    if depth >= MAX_VITE_PLUGIN_WRAPPER_DEPTH {
1041        return;
1042    }
1043    for argument in &call.arguments {
1044        if let Some(Expression::CallExpression(inner)) = argument.as_expression() {
1045            read_vite_plugin_call(inner, bindings, depth + 1, deps);
1046        }
1047    }
1048}
1049
1050/// The package name that a config string names, such as an SWC plugin in a
1051/// `[name, options]` tuple. A relative or absolute path, a protocol value, or
1052/// an invalid specifier names no package. A subpath maps to its package.
1053#[must_use]
1054pub(crate) fn config_string_package_name(raw: &str) -> Option<String> {
1055    let specifier = raw.trim();
1056    is_package_specifier(specifier).then(|| crate::resolve::extract_package_name(specifier))
1057}
1058
1059/// Extract the package names of SWC plugin tuples, such as
1060/// `swcPlugins: [["@lingui/swc-plugin", {}]]`, at a property path.
1061#[must_use]
1062pub(crate) fn extract_config_swc_plugin_dependencies(
1063    source: &str,
1064    path: &Path,
1065    array_path: &[&str],
1066) -> Vec<String> {
1067    extract_config_array_tuple_heads(source, path, array_path)
1068        .iter()
1069        .filter_map(|raw| config_string_package_name(raw))
1070        .fold(Vec::new(), |mut deps, dep| {
1071            push_unique_string(&mut deps, dep);
1072            deps
1073        })
1074}
1075
1076/// How a config reader reads a path value with a leading `/`.
1077#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1078enum LeadingSlash {
1079    /// Relative to the project root, as Vite reads `/src`.
1080    RootRelative,
1081    /// A filesystem path, as webpack and Node read `/src`.
1082    Filesystem,
1083}
1084
1085/// Normalize a config-relative path to a project-root-relative path.
1086///
1087/// Handles values extracted from config files such as `"./src"`, `"src/lib"`,
1088/// `"/src"`, or absolute filesystem paths under `root`. An absolute path under
1089/// `root` is read as absolute. Any other leading `/` is read as relative to
1090/// `root`, the same as Vite: this includes the root itself and, when
1091/// `<root>/<root>` is a directory, every leading-`/` value. Use [`normalize_filesystem_config_path_buf`] for a reader whose tool
1092/// reads a leading `/` as a filesystem path.
1093#[must_use]
1094pub(crate) fn normalize_config_path_buf(
1095    raw: impl AsRef<Path>,
1096    config_path: &Path,
1097    root: &Path,
1098) -> Option<PathBuf> {
1099    normalize_path_value(raw.as_ref(), config_path, root, LeadingSlash::RootRelative)
1100}
1101
1102/// Normalize a config path value for a reader whose tool reads a leading `/`
1103/// as a filesystem path, such as webpack. A leading-`/` path outside `root`
1104/// resolves to `None` (issue #2806).
1105#[must_use]
1106pub(crate) fn normalize_filesystem_config_path_buf(
1107    raw: impl AsRef<Path>,
1108    config_path: &Path,
1109    root: &Path,
1110) -> Option<PathBuf> {
1111    normalize_path_value(raw.as_ref(), config_path, root, LeadingSlash::Filesystem)
1112}
1113
1114fn normalize_path_value(
1115    raw: &Path,
1116    config_path: &Path,
1117    root: &Path,
1118    leading_slash: LeadingSlash,
1119) -> Option<PathBuf> {
1120    if raw.as_os_str().is_empty() {
1121        return None;
1122    }
1123
1124    let raw_string = path_to_config_string(raw);
1125    let raw_path = Path::new(&raw_string);
1126    let root_relative_slash =
1127        leading_slash == LeadingSlash::RootRelative && raw_string.starts_with('/');
1128    let absolute = raw_path
1129        .is_absolute()
1130        .then(|| lexical_normalize(raw_path))
1131        .filter(|absolute| absolute.starts_with(root))
1132        .filter(|absolute| !(root_relative_slash && (absolute == root || root_in_root(root))));
1133    let candidate = if let Some(absolute) = absolute {
1134        absolute
1135    } else if let Some(stripped) = raw_string.strip_prefix('/') {
1136        match leading_slash {
1137            LeadingSlash::RootRelative => lexical_normalize(&root.join(stripped)),
1138            LeadingSlash::Filesystem => return None,
1139        }
1140    } else if raw_path.is_absolute() {
1141        return None;
1142    } else {
1143        let base = config_path.parent().unwrap_or(root);
1144        lexical_normalize(&base.join(raw_path))
1145    };
1146
1147    let relative = candidate.strip_prefix(root).ok()?;
1148    (!relative.as_os_str().is_empty()).then(|| relative.to_path_buf())
1149}
1150
1151/// Vite's `rootInRoot` rule: when `<root>/<root>` is a directory, Vite reads
1152/// every leading-`/` value as relative to the root, also one that starts with
1153/// the root path.
1154fn root_in_root(root: &Path) -> bool {
1155    let root_string = path_to_config_string(root);
1156    let Some(stripped) = root_string.strip_prefix('/') else {
1157        return false;
1158    };
1159    !stripped.is_empty() && root.join(stripped).is_dir()
1160}
1161
1162/// [`normalize_filesystem_config_path_buf`] as a project-root-relative
1163/// forward-slash string.
1164#[must_use]
1165pub(crate) fn normalize_filesystem_config_path(
1166    raw: impl AsRef<Path>,
1167    config_path: &Path,
1168    root: &Path,
1169) -> Option<String> {
1170    normalize_filesystem_config_path_buf(raw, config_path, root)
1171        .map(|path| path_to_config_string(&path))
1172}
1173
1174/// Normalize a config-relative path to a project-root-relative forward-slash string.
1175#[must_use]
1176pub(crate) fn normalize_config_path(
1177    raw: impl AsRef<Path>,
1178    config_path: &Path,
1179    root: &Path,
1180) -> Option<String> {
1181    normalize_config_path_buf(raw, config_path, root).map(|path| path_to_config_string(&path))
1182}
1183
1184/// A relative config path that climbs out of the plugin root, as a path
1185/// relative to that root with its leading `../` segments. The path is read
1186/// relative to the directory of `config_path`.
1187///
1188/// A workspace package is read with its own directory as the root, so a path
1189/// into a sibling workspace climbs out of it while it stays inside the project.
1190/// The caller registers the result as a parent-relative entry pattern, so the
1191/// workspace prefix resolves the `../` segments later. A path that climbs out
1192/// of the project keeps them and matches no project file.
1193pub(crate) fn parent_relative_config_path(
1194    target: &str,
1195    config_path: &Path,
1196    root: &Path,
1197) -> Option<String> {
1198    if !target.starts_with("../") {
1199        return None;
1200    }
1201    let directory = config_path.parent().unwrap_or(root);
1202    let candidate = lexical_normalize(&directory.join(target));
1203    let root = lexical_normalize(root);
1204    let mut ancestor = root.as_path();
1205    let mut climbs = 0;
1206    while !candidate.starts_with(ancestor) {
1207        ancestor = ancestor.parent()?;
1208        climbs += 1;
1209    }
1210    let rest = candidate.strip_prefix(ancestor).ok()?;
1211    (climbs > 0 && !rest.as_os_str().is_empty())
1212        .then(|| format!("{}{}", "../".repeat(climbs), path_to_config_string(rest)))
1213}
1214
1215/// Parse source and run an extraction function on the AST.
1216///
1217/// JSON files (`.json`, `.jsonc`) are parsed as JavaScript expressions wrapped in
1218/// parentheses to produce an AST compatible with `find_config_object`. The native
1219/// JSON source type in Oxc produces a different AST structure that our helpers
1220/// don't handle.
1221///
1222/// Before the extraction, a JavaScript or TypeScript program gets the literal
1223/// value of each stable same-file constant in the property values and array
1224/// elements that name it, so `projects: [UNIT]` reads like an inline object.
1225/// An object spread of such a constant gets its properties. The values that an
1226/// exported config callback returns also get the literal value of the stable
1227/// locals of that callback, so `return { ...common, entry }` reads the same way.
1228pub(crate) fn extract_from_source<T: Send>(
1229    source: &str,
1230    path: &Path,
1231    extractor: impl FnOnce(&Program) -> Option<T> + Send,
1232) -> Option<T> {
1233    let is_json = path
1234        .extension()
1235        .is_some_and(|ext| ext == "json" || ext == "jsonc");
1236    if is_json {
1237        let wrapped = wrap_json_as_expression(source);
1238        return fallow_extract::parse_bounded_or_default(&wrapped, SourceType::mjs(), |parsed| {
1239            extractor(&parsed.program)
1240        });
1241    }
1242    let source_type = SourceType::from_path(path).unwrap_or_default();
1243    let parse = carry_project_root(|| {
1244        let allocator = oxc_allocator::Allocator::default();
1245        let mut parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
1246        const_inline::with_inlined_program(&allocator, &mut parsed.program, source.len(), extractor)
1247    });
1248    fallow_extract::parse_bounded(source, parse).flatten()
1249}
1250
1251/// Wrap JSON or JSONC source in parentheses so Oxc parses it as one JavaScript
1252/// expression. The newline ends a trailing `//` comment, so the comment cannot
1253/// hide the closing parenthesis.
1254pub(crate) fn wrap_json_as_expression(source: &str) -> String {
1255    format!("({source}\n)")
1256}
1257
1258/// The local names that `import` declarations bind to the default export of
1259/// one plugin package.
1260#[derive(Default)]
1261struct PluginImportBindings {
1262    callables: Vec<String>,
1263    namespaces: Vec<String>,
1264}
1265
1266impl PluginImportBindings {
1267    fn is_empty(&self) -> bool {
1268        self.callables.is_empty() && self.namespaces.is_empty()
1269    }
1270}
1271
1272fn collect_plugin_import_bindings(program: &Program<'_>, package: &str) -> PluginImportBindings {
1273    let mut imports = PluginImportBindings::default();
1274
1275    for stmt in &program.body {
1276        let Statement::ImportDeclaration(decl) = stmt else {
1277            continue;
1278        };
1279        if decl.source.value != package {
1280            continue;
1281        }
1282        let Some(specifiers) = &decl.specifiers else {
1283            continue;
1284        };
1285        for specifier in specifiers {
1286            match specifier {
1287                ImportDeclarationSpecifier::ImportDefaultSpecifier(specifier) => {
1288                    push_unique_string(&mut imports.callables, specifier.local.name.to_string());
1289                }
1290                ImportDeclarationSpecifier::ImportSpecifier(specifier)
1291                    if specifier.imported.name().as_ref() == "default" =>
1292                {
1293                    push_unique_string(&mut imports.callables, specifier.local.name.to_string());
1294                }
1295                ImportDeclarationSpecifier::ImportNamespaceSpecifier(specifier) => {
1296                    push_unique_string(&mut imports.namespaces, specifier.local.name.to_string());
1297                }
1298                ImportDeclarationSpecifier::ImportSpecifier(_) => {}
1299            }
1300        }
1301    }
1302
1303    imports
1304}
1305
1306fn collect_vite_react_babel_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1307    if let Some(babel) = property_object(options, "babel") {
1308        collect_babel_plugin_and_preset_dependencies(babel, deps);
1309    }
1310}
1311
1312/// `@wyw-in-js/vite` passes `babelOptions` to Babel, which loads each named
1313/// plugin and preset.
1314fn collect_wyw_babel_options_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1315    if let Some(babel) = property_object(options, "babelOptions") {
1316        collect_babel_plugin_and_preset_dependencies(babel, deps);
1317    }
1318}
1319
1320/// `@vitejs/plugin-react-swc` passes `plugins` to SWC, which loads the package
1321/// at the head of each `[name, options]` tuple.
1322fn collect_vite_react_swc_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1323    let Some(prop) = find_property(options, "plugins") else {
1324        return;
1325    };
1326    let Expression::ArrayExpression(plugins) = &prop.value else {
1327        return;
1328    };
1329    for entry in &plugins.elements {
1330        let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
1331            continue;
1332        };
1333        if let Some(dep) = tuple
1334            .elements
1335            .first()
1336            .and_then(ArrayExpressionElement::as_expression)
1337            .and_then(expression_to_string)
1338            .and_then(|raw| config_string_package_name(&raw))
1339        {
1340            push_unique_string(deps, dep);
1341        }
1342    }
1343}
1344
1345fn collect_babel_plugin_and_preset_dependencies(
1346    babel: &ObjectExpression<'_>,
1347    deps: &mut Vec<String>,
1348) {
1349    for key in ["plugins", "presets"] {
1350        let Some(prop) = find_property(babel, key) else {
1351            continue;
1352        };
1353        for raw in collect_shallow_string_values(&prop.value) {
1354            if let Some(dep) = vite_react_babel_dependency_name(&raw) {
1355                push_unique_string(deps, dep);
1356            }
1357        }
1358    }
1359}
1360
1361fn vite_react_babel_dependency_name(raw: &str) -> Option<String> {
1362    let raw = raw.trim();
1363    let specifier = raw.strip_prefix("module:").unwrap_or(raw).trim();
1364    if specifier.is_empty()
1365        || specifier.starts_with('.')
1366        || specifier.starts_with('/')
1367        || specifier.contains(':')
1368        || specifier.contains('\\')
1369    {
1370        return None;
1371    }
1372    Some(crate::resolve::extract_package_name(specifier))
1373}
1374
1375fn push_unique_string(items: &mut Vec<String>, value: String) {
1376    if !items.contains(&value) {
1377        items.push(value);
1378    }
1379}
1380
1381/// Find the "config object": the object expression in the default export or module.exports.
1382///
1383/// Handles these patterns:
1384/// - `export default { ... }`
1385/// - `export default defineConfig({ ... })`
1386/// - `export default defineConfig(async () => ({ ... }))`
1387/// - `export default { ... } satisfies Config` / `export default { ... } as Config`
1388/// - `const config = { ... }; export default config;`
1389/// - `const config: Config = { ... }; export default config;`
1390/// - `module.exports = { ... }`
1391/// - Top-level JSON object (for .json files)
1392pub(crate) fn find_config_object<'a>(program: &'a Program) -> Option<&'a ObjectExpression<'a>> {
1393    for stmt in &program.body {
1394        match stmt {
1395            Statement::ExportDefaultDeclaration(decl) => {
1396                let expr: Option<&Expression> = match &decl.declaration {
1397                    ExportDefaultDeclarationKind::ObjectExpression(obj) => {
1398                        return Some(obj);
1399                    }
1400                    ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
1401                        return extract_object_from_function(func);
1402                    }
1403                    _ => decl.declaration.as_expression(),
1404                };
1405                if let Some(expr) = expr {
1406                    if let Some(obj) =
1407                        resolve_call_config_object(program, expr, MAX_CONFIG_WRAPPER_DEPTH)
1408                    {
1409                        return Some(obj);
1410                    }
1411                    if let Some(obj) = extract_object_from_expression(expr) {
1412                        return Some(obj);
1413                    }
1414                    if let Some(name) = unwrap_to_identifier_name(expr) {
1415                        return find_variable_init_object(program, name);
1416                    }
1417                    if let Some(obj) = resolve_wrapped_config_object(program, expr) {
1418                        return Some(obj);
1419                    }
1420                }
1421            }
1422            Statement::ExpressionStatement(expr_stmt) => {
1423                if let Expression::AssignmentExpression(assign) = &expr_stmt.expression
1424                    && is_module_exports_target(&assign.left)
1425                {
1426                    if let Some(obj) =
1427                        resolve_call_config_object(program, &assign.right, MAX_CONFIG_WRAPPER_DEPTH)
1428                    {
1429                        return Some(obj);
1430                    }
1431                    if let Some(obj) = extract_object_from_expression(&assign.right) {
1432                        return Some(obj);
1433                    }
1434                    if let Some(name) = unwrap_to_identifier_name(&assign.right) {
1435                        return find_variable_init_object(program, name);
1436                    }
1437                    return resolve_wrapped_config_object(program, &assign.right);
1438                }
1439            }
1440            _ => {}
1441        }
1442    }
1443
1444    if program.body.len() == 1
1445        && let Statement::ExpressionStatement(expr_stmt) = &program.body[0]
1446    {
1447        match &expr_stmt.expression {
1448            Expression::ObjectExpression(obj) => return Some(obj),
1449            Expression::ParenthesizedExpression(paren) => {
1450                if let Expression::ObjectExpression(obj) = &paren.expression {
1451                    return Some(obj);
1452                }
1453            }
1454            _ => {}
1455        }
1456    }
1457
1458    None
1459}
1460
1461/// Extract an `ObjectExpression` from an expression, handling wrapper patterns.
1462pub(crate) fn extract_object_from_expression<'a>(
1463    expr: &'a Expression<'a>,
1464) -> Option<&'a ObjectExpression<'a>> {
1465    match expr {
1466        Expression::ObjectExpression(obj) => Some(obj),
1467        Expression::CallExpression(call) => {
1468            for arg in &call.arguments {
1469                match arg {
1470                    Argument::ObjectExpression(obj) => return Some(obj),
1471                    // Both arrow forms reach here: the concise
1472                    // `defineConfig(() => ({ ... }))` and the block body
1473                    // `defineConfig(({ mode }) => { ...; return { ... }; })`.
1474                    // The block form is the common shape for configs that
1475                    // branch on the mode, and handling only the concise one
1476                    // made every such config invisible to extraction.
1477                    Argument::ArrowFunctionExpression(arrow) => {
1478                        if let Some(obj) = extract_object_from_arrow_function(arrow) {
1479                            return Some(obj);
1480                        }
1481                    }
1482                    Argument::FunctionExpression(func) => {
1483                        if let Some(obj) = extract_object_from_function(func) {
1484                            return Some(obj);
1485                        }
1486                    }
1487                    _ => {}
1488                }
1489            }
1490            None
1491        }
1492        Expression::ParenthesizedExpression(paren) => {
1493            extract_object_from_expression(&paren.expression)
1494        }
1495        Expression::TSSatisfiesExpression(ts_sat) => {
1496            extract_object_from_expression(&ts_sat.expression)
1497        }
1498        Expression::TSAsExpression(ts_as) => extract_object_from_expression(&ts_as.expression),
1499        Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
1500        Expression::FunctionExpression(func) => extract_object_from_function(func),
1501        _ => None,
1502    }
1503}
1504
1505fn extract_object_from_arrow_function<'a>(
1506    arrow: &'a ArrowFunctionExpression<'a>,
1507) -> Option<&'a ObjectExpression<'a>> {
1508    match &arrow.body {
1509        ArrowFunctionBody::FunctionBody(body) => extract_object_from_function_body(body),
1510        body => body
1511            .as_expression()
1512            .and_then(extract_object_from_expression),
1513    }
1514}
1515
1516fn extract_object_from_function<'a>(func: &'a Function<'a>) -> Option<&'a ObjectExpression<'a>> {
1517    func.body
1518        .as_ref()
1519        .and_then(|body| extract_object_from_function_body(body))
1520}
1521
1522/// Resolve the object a config callback returns.
1523///
1524/// A return at the body's own level is the callback's main config and always
1525/// wins, which keeps the overwhelmingly common `guard clause; return { ... }`
1526/// shape resolving to the real config rather than to the guard's early return.
1527/// Only a body with no top-level return falls back to searching branches, which
1528/// is the shape Vite documents for switching config by command:
1529/// `if (command === "serve") { return { ... } } else { return { ... } }`.
1530fn extract_object_from_function_body<'a>(
1531    body: &'a FunctionBody<'a>,
1532) -> Option<&'a ObjectExpression<'a>> {
1533    find_top_level_returned_object(&body.statements)
1534        .or_else(|| find_returned_object(&body.statements, MAX_CONFIG_BRANCH_DEPTH))
1535}
1536
1537/// Maximum control-flow nesting searched for a config `return`.
1538const MAX_CONFIG_BRANCH_DEPTH: u8 = 4;
1539
1540/// Find the first object returned by a statement at this exact level.
1541fn find_top_level_returned_object<'a>(
1542    statements: &'a [Statement<'a>],
1543) -> Option<&'a ObjectExpression<'a>> {
1544    statements.iter().find_map(|stmt| match stmt {
1545        Statement::ReturnStatement(ret) => ret
1546            .argument
1547            .as_ref()
1548            .and_then(|argument| extract_object_from_expression(argument)),
1549        _ => None,
1550    })
1551}
1552
1553/// Find the first returned object literal in `statements`, descending into
1554/// control flow.
1555///
1556/// Nested function and arrow bodies are deliberately not searched: their returns
1557/// belong to the inner function, not to the config callback.
1558///
1559/// The first return in source order wins. A config whose branches declare
1560/// different values therefore contributes only the first branch's.
1561fn find_returned_object<'a>(
1562    statements: &'a [Statement<'a>],
1563    depth: u8,
1564) -> Option<&'a ObjectExpression<'a>> {
1565    if depth == 0 {
1566        return None;
1567    }
1568    for stmt in statements {
1569        let found = match stmt {
1570            Statement::ReturnStatement(ret) => ret
1571                .argument
1572                .as_ref()
1573                .and_then(|argument| extract_object_from_expression(argument)),
1574            Statement::BlockStatement(block) => find_returned_object(&block.body, depth - 1),
1575            Statement::IfStatement(if_stmt) => {
1576                find_returned_object_in_statement(&if_stmt.consequent, depth - 1).or_else(|| {
1577                    if_stmt
1578                        .alternate
1579                        .as_ref()
1580                        .and_then(|alt| find_returned_object_in_statement(alt, depth - 1))
1581                })
1582            }
1583            Statement::TryStatement(try_stmt) => {
1584                find_returned_object(&try_stmt.block.body, depth - 1)
1585                    .or_else(|| {
1586                        try_stmt
1587                            .handler
1588                            .as_ref()
1589                            .and_then(|handler| find_returned_object(&handler.body.body, depth - 1))
1590                    })
1591                    .or_else(|| {
1592                        try_stmt
1593                            .finalizer
1594                            .as_ref()
1595                            .and_then(|finalizer| find_returned_object(&finalizer.body, depth - 1))
1596                    })
1597            }
1598            Statement::SwitchStatement(switch) => switch
1599                .cases
1600                .iter()
1601                .find_map(|case| find_returned_object(&case.consequent, depth - 1)),
1602            _ => None,
1603        };
1604        if found.is_some() {
1605            return found;
1606        }
1607    }
1608    None
1609}
1610
1611fn find_returned_object_in_statement<'a>(
1612    stmt: &'a Statement<'a>,
1613    depth: u8,
1614) -> Option<&'a ObjectExpression<'a>> {
1615    match stmt {
1616        Statement::BlockStatement(block) => find_returned_object(&block.body, depth),
1617        other => find_returned_object(std::slice::from_ref(other), depth),
1618    }
1619}
1620
1621/// Check if an assignment target is `module.exports`.
1622fn is_module_exports_target(target: &AssignmentTarget) -> bool {
1623    if let AssignmentTarget::StaticMemberExpression(member) = target
1624        && let Expression::Identifier(obj) = &member.object
1625    {
1626        return obj.name == "module" && member.property.name == "exports";
1627    }
1628    false
1629}
1630
1631/// Unwrap TS annotations and return the identifier name if the expression resolves to one.
1632///
1633/// Handles `config`, `config satisfies Type`, `config as Type`.
1634fn unwrap_to_identifier_name<'a>(expr: &'a Expression<'a>) -> Option<&'a str> {
1635    match expr {
1636        Expression::Identifier(id) => Some(&id.name),
1637        Expression::TSSatisfiesExpression(ts_sat) => unwrap_to_identifier_name(&ts_sat.expression),
1638        Expression::TSAsExpression(ts_as) => unwrap_to_identifier_name(&ts_as.expression),
1639        _ => None,
1640    }
1641}
1642
1643/// Find a top-level variable declaration by name and extract its init as an object expression.
1644///
1645/// Handles `const config = { ... }`, `const config: Type = { ... }`,
1646/// and `const config = defineConfig({ ... })`.
1647fn find_variable_init_object<'a>(
1648    program: &'a Program,
1649    name: &str,
1650) -> Option<&'a ObjectExpression<'a>> {
1651    for decl in top_level_variable_declarations(program) {
1652        for declarator in &decl.declarations {
1653            if let BindingPattern::BindingIdentifier(id) = &declarator.id
1654                && id.name == name
1655                && let Some(init) = &declarator.init
1656            {
1657                return extract_object_from_expression(init);
1658            }
1659        }
1660    }
1661    None
1662}
1663
1664/// The init expression of the first top-level variable declaration of `name`.
1665fn find_variable_init<'a>(program: &'a Program<'a>, name: &str) -> Option<&'a Expression<'a>> {
1666    top_level_variable_declarations(program)
1667        .flat_map(|decl| &decl.declarations)
1668        .find(|declarator| {
1669            matches!(&declarator.id, BindingPattern::BindingIdentifier(id) if id.name == name)
1670        })
1671        .and_then(|declarator| declarator.init.as_ref())
1672}
1673
1674/// The expression that the config file exports with `export default` or
1675/// `module.exports =`.
1676fn exported_config_expression<'a>(program: &'a Program<'a>) -> Option<&'a Expression<'a>> {
1677    program.body.iter().find_map(|stmt| match stmt {
1678        Statement::ExportDefaultDeclaration(decl) => decl.declaration.as_expression(),
1679        Statement::ExpressionStatement(expr_stmt) => match &expr_stmt.expression {
1680            Expression::AssignmentExpression(assign) if is_module_exports_target(&assign.left) => {
1681                Some(&assign.right)
1682            }
1683            _ => None,
1684        },
1685        _ => None,
1686    })
1687}
1688
1689/// The call that `expr` stands for, through parentheses, type assertions and
1690/// one top-level variable binding.
1691fn config_call<'a>(
1692    program: &'a Program<'a>,
1693    expr: &'a Expression<'a>,
1694    follow_binding: bool,
1695) -> Option<&'a CallExpression<'a>> {
1696    match expr {
1697        Expression::CallExpression(call) => Some(call),
1698        Expression::ParenthesizedExpression(paren) => {
1699            config_call(program, &paren.expression, follow_binding)
1700        }
1701        Expression::TSSatisfiesExpression(ts_sat) => {
1702            config_call(program, &ts_sat.expression, follow_binding)
1703        }
1704        Expression::TSAsExpression(ts_as) => {
1705            config_call(program, &ts_as.expression, follow_binding)
1706        }
1707        Expression::Identifier(id) if follow_binding => {
1708            config_call(program, find_variable_init(program, &id.name)?, false)
1709        }
1710        _ => None,
1711    }
1712}
1713
1714/// The arguments of an exported config call with more than one argument, such
1715/// as `defineConfig(base, { ... })`, in source order.
1716///
1717/// Some tools merge every argument into one config. Each argument resolves to
1718/// its object. An argument that does not resolve to one local object is
1719/// `None`, because it can set any key: a spread, an imported binding, or a
1720/// nested call that merges more than one argument. Returns `None` when the
1721/// exported config is not a call with more than one argument.
1722pub(crate) fn find_config_merge_arguments<'a>(
1723    program: &'a Program<'a>,
1724) -> Option<Vec<Option<&'a ObjectExpression<'a>>>> {
1725    let call = config_call(program, exported_config_expression(program)?, true)?;
1726    if call.arguments.len() < 2 {
1727        return None;
1728    }
1729    let resolve = |arg: &'a Argument<'a>| {
1730        let expr = arg.as_expression()?;
1731        if config_call(program, expr, true).is_some_and(|nested| nested.arguments.len() > 1) {
1732            return None;
1733        }
1734        resolve_config_argument(program, expr, MAX_CONFIG_WRAPPER_DEPTH)
1735    };
1736    Some(call.arguments.iter().map(resolve).collect())
1737}
1738
1739/// Every top-level variable declaration, including the one an
1740/// `export const NAME = ...` declaration wraps.
1741fn top_level_variable_declarations<'a>(
1742    program: &'a Program<'a>,
1743) -> impl Iterator<Item = &'a VariableDeclaration<'a>> {
1744    program.body.iter().filter_map(|stmt| match stmt {
1745        Statement::VariableDeclaration(decl) => Some(&**decl),
1746        Statement::ExportDeclaration(export) => match &export.declaration {
1747            Declaration::VariableDeclaration(decl) => Some(&**decl),
1748            _ => None,
1749        },
1750        _ => None,
1751    })
1752}
1753
1754/// The init expression of a top-level `const` or `let` that is the only binding
1755/// of `name` in the program and that no expression writes to.
1756///
1757/// `new ModuleFederationPlugin(mfConfig)` is the common shape for plugin options
1758/// that a config declares above the plugin list, where an inline-only reader fails.
1759///
1760/// The name resolves only when the program holds one binding of that name. A
1761/// second binding, a parameter of the same name, or a write to the binding means
1762/// the expression can name another value than the top-level one, so the
1763/// resolver declines. A caller that reads `push`-style calls itself can allow them.
1764pub(crate) fn find_stable_binding_init<'a>(
1765    program: &'a Program<'a>,
1766    name: &str,
1767    allow_mutating_calls: bool,
1768) -> Option<&'a Expression<'a>> {
1769    if !holds_one_stable_object(program, name, allow_mutating_calls) {
1770        return None;
1771    }
1772    find_variable_init_expression(program, name)
1773}
1774
1775/// Resolve a config object that is passed as a NAMED CONST to a wrapper call:
1776/// `export default withMDX(nextConfig)`, `module.exports = createJestConfig(cfg)`,
1777/// nested `withMDX(withFoo(nextConfig))`, and curried `compose(...)(nextConfig)`.
1778/// This is the call-argument analog of the bare `export default config` identifier
1779/// resolution already done via [`unwrap_to_identifier_name`] +
1780/// [`find_variable_init_object`]; it lets the official `@next/mdx` /
1781/// `withSentry(nextConfig)` / `next-compose-plugins` idioms resolve so their
1782/// `pageExtensions` / plugin config is extracted instead of silently dropped.
1783///
1784/// Returns the first argument (scanning nested wrapper calls) that resolves to a
1785/// local `const NAME = { ... }`. Inline object and callback arguments are handled
1786/// by [`resolve_call_config_object`], which the caller tries first.
1787fn resolve_wrapped_config_object<'a>(
1788    program: &'a Program,
1789    expr: &'a Expression<'a>,
1790) -> Option<&'a ObjectExpression<'a>> {
1791    let call = match expr {
1792        Expression::CallExpression(call) => call,
1793        Expression::ParenthesizedExpression(paren) => {
1794            return resolve_wrapped_config_object(program, &paren.expression);
1795        }
1796        Expression::TSSatisfiesExpression(ts_sat) => {
1797            return resolve_wrapped_config_object(program, &ts_sat.expression);
1798        }
1799        Expression::TSAsExpression(ts_as) => {
1800            return resolve_wrapped_config_object(program, &ts_as.expression);
1801        }
1802        _ => return None,
1803    };
1804    for arg in &call.arguments {
1805        let Some(arg_expr) = arg.as_expression() else {
1806            continue;
1807        };
1808        if let Some(name) = unwrap_to_identifier_name(arg_expr)
1809            && let Some(obj) = find_variable_init_object(program, name)
1810        {
1811            return Some(obj);
1812        }
1813        if let Some(obj) = resolve_wrapped_config_object(program, arg_expr) {
1814            return Some(obj);
1815        }
1816    }
1817    None
1818}
1819
1820/// Maximum wrapper nesting resolved by [`resolve_call_config_object`].
1821///
1822/// Covers the shapes seen in the wild (`defineConfig(mergeConfig(base, defineConfig({..})))`)
1823/// while keeping a hand-written config from driving unbounded recursion.
1824const MAX_CONFIG_WRAPPER_DEPTH: u8 = 3;
1825
1826/// Resolve the config object carried by a wrapper call, giving each argument the
1827/// full resolution chain in source order.
1828///
1829/// Config wrappers take the config first and their own options after it, as in
1830/// `withSentryConfig(nextConfig, { org, project })` or
1831/// `mergeConfig(viteConfig, defineConfig({ test }))`. Scanning the whole argument
1832/// list for the first object literal therefore picks up the wrapper's options
1833/// object whenever the config itself arrives as an identifier or a nested call,
1834/// silently reading the wrong object. Resolving argument by argument, chain-first,
1835/// keeps the config's own position winning.
1836fn resolve_call_config_object<'a>(
1837    program: &'a Program,
1838    expr: &'a Expression<'a>,
1839    depth: u8,
1840) -> Option<&'a ObjectExpression<'a>> {
1841    if depth == 0 {
1842        return None;
1843    }
1844    let call = match expr {
1845        Expression::CallExpression(call) => call,
1846        Expression::ParenthesizedExpression(paren) => {
1847            return resolve_call_config_object(program, &paren.expression, depth);
1848        }
1849        Expression::TSSatisfiesExpression(ts_sat) => {
1850            return resolve_call_config_object(program, &ts_sat.expression, depth);
1851        }
1852        Expression::TSAsExpression(ts_as) => {
1853            return resolve_call_config_object(program, &ts_as.expression, depth);
1854        }
1855        _ => return None,
1856    };
1857
1858    call.arguments
1859        .iter()
1860        .filter_map(oxc_ast::ast::Argument::as_expression)
1861        .find_map(|arg| resolve_config_argument(program, arg, depth))
1862}
1863
1864/// Resolve one wrapper argument to the object it stands for.
1865fn resolve_config_argument<'a>(
1866    program: &'a Program,
1867    expr: &'a Expression<'a>,
1868    depth: u8,
1869) -> Option<&'a ObjectExpression<'a>> {
1870    match expr {
1871        Expression::ObjectExpression(obj) => Some(obj),
1872        Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
1873        Expression::FunctionExpression(func) => extract_object_from_function(func),
1874        Expression::ParenthesizedExpression(paren) => {
1875            resolve_config_argument(program, &paren.expression, depth)
1876        }
1877        Expression::TSSatisfiesExpression(ts_sat) => {
1878            resolve_config_argument(program, &ts_sat.expression, depth)
1879        }
1880        Expression::TSAsExpression(ts_as) => {
1881            resolve_config_argument(program, &ts_as.expression, depth)
1882        }
1883        Expression::CallExpression(_) => resolve_call_config_object(program, expr, depth - 1),
1884        _ => unwrap_to_identifier_name(expr)
1885            .and_then(|name| find_variable_init_object(program, name)),
1886    }
1887}
1888
1889/// Find a named property in an object expression.
1890pub(crate) fn find_property<'a>(
1891    obj: &'a ObjectExpression<'a>,
1892    key: &str,
1893) -> Option<&'a ObjectProperty<'a>> {
1894    for prop in &obj.properties {
1895        if let ObjectPropertyKind::ObjectProperty(p) = prop
1896            && property_key_matches(&p.key, key)
1897        {
1898            return Some(p);
1899        }
1900    }
1901    None
1902}
1903
1904/// Check if a property key matches a string.
1905fn property_key_matches(key: &PropertyKey, name: &str) -> bool {
1906    match key {
1907        PropertyKey::StaticIdentifier(id) => id.name == name,
1908        PropertyKey::StringLiteral(s) => s.value == name,
1909        _ => false,
1910    }
1911}
1912
1913/// Get a string value from an object property.
1914fn get_object_string_property(obj: &ObjectExpression, key: &str) -> Option<String> {
1915    find_property(obj, key).and_then(|p| expression_to_string(&p.value))
1916}
1917
1918/// Get an array of strings from an object property.
1919fn get_object_string_array_property(obj: &ObjectExpression, key: &str) -> Vec<String> {
1920    find_property(obj, key)
1921        .map(|p| expression_to_string_array(&p.value))
1922        .unwrap_or_default()
1923}
1924
1925/// Navigate a nested property path and get a string array.
1926fn get_nested_string_array_from_object(
1927    obj: &ObjectExpression,
1928    path: &[&str],
1929) -> Option<Vec<String>> {
1930    if path.is_empty() {
1931        return None;
1932    }
1933    if path.len() == 1 {
1934        return Some(get_object_string_array_property(obj, path[0]));
1935    }
1936    let prop = find_property(obj, path[0])?;
1937    if let Expression::ObjectExpression(nested) = &prop.value {
1938        get_nested_string_array_from_object(nested, &path[1..])
1939    } else {
1940        None
1941    }
1942}
1943
1944/// Navigate a nested property path and get a string value.
1945fn get_nested_string_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
1946    if path.is_empty() {
1947        return None;
1948    }
1949    if path.len() == 1 {
1950        return get_object_string_property(obj, path[0]);
1951    }
1952    let prop = find_property(obj, path[0])?;
1953    if let Expression::ObjectExpression(nested) = &prop.value {
1954        get_nested_string_from_object(nested, &path[1..])
1955    } else {
1956        None
1957    }
1958}
1959
1960/// Navigate a nested property path and get a shell command value.
1961fn get_nested_command_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
1962    if path.is_empty() {
1963        return None;
1964    }
1965    if path.len() == 1 {
1966        return find_property(obj, path[0]).and_then(|prop| expression_to_command(&prop.value));
1967    }
1968    let prop = find_property(obj, path[0])?;
1969    if let Expression::ObjectExpression(nested) = &prop.value {
1970        get_nested_command_from_object(nested, &path[1..])
1971    } else {
1972        None
1973    }
1974}
1975
1976/// Convert an expression to a string if it's a string literal.
1977pub(crate) fn expression_to_string(expr: &Expression) -> Option<String> {
1978    match expr {
1979        Expression::StringLiteral(s) => Some(s.value.text().into_owned()),
1980        Expression::TemplateLiteral(t) if t.expressions.is_empty() => {
1981            t.quasis.first().map(|q| q.value.raw.to_string())
1982        }
1983        _ => None,
1984    }
1985}
1986
1987/// Convert an expression to a shell command when static command tokens are recoverable.
1988fn expression_to_command(expr: &Expression) -> Option<String> {
1989    match expr {
1990        Expression::StringLiteral(s) => Some(s.value.text().into_owned()),
1991        Expression::TemplateLiteral(template) => template_literal_to_command(template),
1992        Expression::ParenthesizedExpression(paren) => expression_to_command(&paren.expression),
1993        Expression::TSAsExpression(ts_as) => expression_to_command(&ts_as.expression),
1994        Expression::TSSatisfiesExpression(ts_sat) => expression_to_command(&ts_sat.expression),
1995        _ => None,
1996    }
1997}
1998
1999fn template_literal_to_command(template: &TemplateLiteral<'_>) -> Option<String> {
2000    let first = template.quasis.first()?.value.raw.as_str();
2001    if first.trim_start().is_empty() {
2002        return None;
2003    }
2004
2005    let mut command = String::new();
2006    for (idx, quasi) in template.quasis.iter().enumerate() {
2007        command.push_str(quasi.value.raw.as_str());
2008        if idx < template.expressions.len() {
2009            let next = template
2010                .quasis
2011                .get(idx + 1)
2012                .map_or("", |next| next.value.raw.as_str());
2013            if dynamic_template_boundary_splits_static_token(quasi.value.raw.as_str(), next) {
2014                return None;
2015            }
2016            command.push(' ');
2017        }
2018    }
2019
2020    Some(command)
2021}
2022
2023fn dynamic_template_boundary_splits_static_token(before: &str, after: &str) -> bool {
2024    before
2025        .chars()
2026        .next_back()
2027        .is_some_and(is_command_token_char)
2028        && after.chars().next().is_some_and(is_command_token_char)
2029}
2030
2031fn is_command_token_char(ch: char) -> bool {
2032    !ch.is_whitespace() && !matches!(ch, '&' | '|' | ';' | '"' | '\'')
2033}
2034
2035/// The identifiers that a path expression can resolve.
2036#[derive(Clone, Copy)]
2037enum PathScope<'p> {
2038    /// No identifier resolves.
2039    Bare,
2040    /// A call to a module-level path helper of this program resolves.
2041    Program(&'p Program<'p>),
2042    /// Inside a helper body, the parameter `name` holds the literal `value`.
2043    Param { name: &'p str, value: &'p str },
2044}
2045
2046/// Convert an expression to a path-like string if it's statically recoverable.
2047pub(crate) fn expression_to_path_string(expr: &Expression) -> Option<String> {
2048    path_string_in(expr, PathScope::Bare)
2049}
2050
2051fn path_string_in(expr: &Expression, scope: PathScope<'_>) -> Option<String> {
2052    match expr {
2053        Expression::ParenthesizedExpression(paren) => path_string_in(&paren.expression, scope),
2054        Expression::TSAsExpression(ts_as) => path_string_in(&ts_as.expression, scope),
2055        Expression::TSSatisfiesExpression(ts_sat) => path_string_in(&ts_sat.expression, scope),
2056        Expression::StaticMemberExpression(member) if member.property.name == "pathname" => {
2057            path_string_in(&member.object, scope)
2058        }
2059        Expression::CallExpression(call) => call_expression_to_path_string(call, scope),
2060        Expression::NewExpression(new_expr) => new_expression_to_path_string(new_expr, scope),
2061        _ => scoped_string(expr, scope),
2062    }
2063}
2064
2065/// A string literal, or the helper parameter that stands for one.
2066fn scoped_string(expr: &Expression, scope: PathScope<'_>) -> Option<String> {
2067    match (expr, scope) {
2068        (Expression::Identifier(id), PathScope::Param { name, value }) if id.name == name => {
2069            Some(value.to_string())
2070        }
2071        _ => expression_to_string(expr),
2072    }
2073}
2074
2075fn call_expression_to_path_string(call: &CallExpression, scope: PathScope<'_>) -> Option<String> {
2076    if let PathScope::Program(program) = scope
2077        && let Expression::Identifier(id) = &call.callee
2078        && let Some(path) = local_helper_call_path(program, &id.name, call)
2079    {
2080        return Some(path);
2081    }
2082
2083    if matches!(&call.callee, Expression::Identifier(id) if id.name == "fileURLToPath") {
2084        return call
2085            .arguments
2086            .first()
2087            .and_then(Argument::as_expression)
2088            .and_then(|arg| path_string_in(arg, scope));
2089    }
2090
2091    let callee_name = match &call.callee {
2092        Expression::Identifier(id) => Some(id.name.as_str()),
2093        Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
2094        _ => None,
2095    }?;
2096
2097    if !matches!(callee_name, "resolve" | "join") {
2098        return None;
2099    }
2100
2101    let mut segments = Vec::new();
2102    for (index, arg) in call.arguments.iter().enumerate() {
2103        let expr = arg.as_expression()?;
2104
2105        if is_dirname_anchor(expr) {
2106            if index == 0 {
2107                continue;
2108            }
2109            return None;
2110        }
2111
2112        segments.push(scoped_string(expr, scope)?);
2113    }
2114
2115    (!segments.is_empty()).then(|| join_path_segments(&segments))
2116}
2117
2118/// Evaluate a call to a module-level path helper with one literal argument.
2119///
2120/// Configs often declare a small helper such as
2121/// `const p = (rel) => fileURLToPath(new URL(rel, import.meta.url))` and call
2122/// it as `p("./src/main.ts")`. The helper body is evaluated with its parameter
2123/// bound to the literal argument. The body can not call another helper.
2124fn local_helper_call_path(program: &Program, name: &str, call: &CallExpression) -> Option<String> {
2125    let [argument] = call.arguments.as_slice() else {
2126        return None;
2127    };
2128    let value = expression_to_string(argument.as_expression()?)?;
2129    let (param, body) = find_local_path_helper(program, name)?;
2130    path_string_in(
2131        body,
2132        PathScope::Param {
2133            name: param,
2134            value: &value,
2135        },
2136    )
2137}
2138
2139/// Find a module-level function `name` with one simple parameter and a body
2140/// that only returns one expression. Return the parameter name and that
2141/// expression.
2142fn find_local_path_helper<'a>(
2143    program: &'a Program<'a>,
2144    name: &str,
2145) -> Option<(&'a str, &'a Expression<'a>)> {
2146    let declared = program.body.iter().find_map(|stmt| {
2147        let func = match stmt {
2148            Statement::FunctionDeclaration(func) => func,
2149            Statement::ExportDeclaration(export) => match &export.declaration {
2150                Declaration::FunctionDeclaration(func) => func,
2151                _ => return None,
2152            },
2153            _ => return None,
2154        };
2155        func.id
2156            .as_ref()
2157            .is_some_and(|id| id.name == name)
2158            .then_some(&**func)
2159    });
2160    if let Some(func) = declared {
2161        return function_helper_body(func);
2162    }
2163    match find_variable_init_expression(program, name)?.without_parentheses() {
2164        Expression::ArrowFunctionExpression(arrow) => {
2165            let param = single_simple_param(&arrow.params)?;
2166            let body = match &arrow.body {
2167                ArrowFunctionBody::FunctionBody(body) => single_returned_expression(body)?,
2168                body => body.as_expression()?,
2169            };
2170            Some((param, body))
2171        }
2172        Expression::FunctionExpression(func) => function_helper_body(func),
2173        _ => None,
2174    }
2175}
2176
2177fn function_helper_body<'a>(func: &'a Function<'a>) -> Option<(&'a str, &'a Expression<'a>)> {
2178    let param = single_simple_param(&func.params)?;
2179    let body = single_returned_expression(func.body.as_ref()?)?;
2180    Some((param, body))
2181}
2182
2183fn single_simple_param<'a>(params: &'a FormalParameters<'a>) -> Option<&'a str> {
2184    let [param] = params.items.as_slice() else {
2185        return None;
2186    };
2187    if params.rest.is_some() || param.initializer.is_some() {
2188        return None;
2189    }
2190    match &param.pattern {
2191        BindingPattern::BindingIdentifier(id) => Some(id.name.as_str()),
2192        _ => None,
2193    }
2194}
2195
2196fn single_returned_expression<'a>(body: &'a FunctionBody<'a>) -> Option<&'a Expression<'a>> {
2197    match body.statements.as_slice() {
2198        [Statement::ReturnStatement(ret)] => ret.argument.as_ref(),
2199        _ => None,
2200    }
2201}
2202
2203/// True when an expression is a "current directory" anchor: the `__dirname`
2204/// CommonJS global or its ESM equivalent `import.meta.dirname` (Node 20.11+).
2205/// As the leading argument of `resolve(...)` / `join(...)` it is dropped so the
2206/// remaining literal segments yield a config-directory-relative path.
2207pub(crate) fn is_dirname_anchor(expr: &Expression) -> bool {
2208    match expr {
2209        Expression::Identifier(id) => id.name == "__dirname",
2210        Expression::StaticMemberExpression(member) => {
2211            member.property.name == "dirname" && is_import_meta_expression(&member.object)
2212        }
2213        _ => false,
2214    }
2215}
2216
2217/// True for the `import.meta` meta-property, distinct from `new.target`.
2218fn is_import_meta_expression(expr: &Expression) -> bool {
2219    matches!(expr, Expression::ImportMeta(_))
2220}
2221
2222fn new_expression_to_path_string(new_expr: &NewExpression, scope: PathScope<'_>) -> Option<String> {
2223    if !matches!(&new_expr.callee, Expression::Identifier(id) if id.name == "URL") {
2224        return None;
2225    }
2226
2227    let source = new_expr
2228        .arguments
2229        .first()
2230        .and_then(Argument::as_expression)
2231        .and_then(|arg| scoped_string(arg, scope))?;
2232
2233    let base = new_expr
2234        .arguments
2235        .get(1)
2236        .and_then(Argument::as_expression)?;
2237    is_import_meta_url_expression(base).then_some(source)
2238}
2239
2240fn is_import_meta_url_expression(expr: &Expression) -> bool {
2241    if let Expression::StaticMemberExpression(member) = expr {
2242        member.property.name == "url"
2243            && matches!(
2244                member.object,
2245                Expression::ImportMeta(_) | Expression::NewTarget(_)
2246            )
2247    } else {
2248        false
2249    }
2250}
2251
2252fn join_path_segments(segments: &[String]) -> String {
2253    let mut joined = PathBuf::new();
2254    for segment in segments {
2255        joined.push(segment);
2256    }
2257    joined.to_string_lossy().replace('\\', "/")
2258}
2259
2260/// Extract an alias replacement string plus whether it was written as a plain
2261/// bare string literal. A bare string literal (not starting with `./`/`../`/`/`)
2262/// signals a potential package-to-package alias; a path expression
2263/// (`path.resolve(...)`, `path.join(...)`, `fileURLToPath(...)`, `new URL(...)`)
2264/// or a `./`-prefixed string is always a filesystem path. This is the
2265/// filesystem-free discriminator the package-to-package gate relies on.
2266fn alias_replacement_kinded(expr: &Expression, scope: PathScope<'_>) -> Option<(String, bool)> {
2267    match expr {
2268        Expression::ParenthesizedExpression(paren) => {
2269            alias_replacement_kinded(&paren.expression, scope)
2270        }
2271        Expression::TSAsExpression(ts_as) => alias_replacement_kinded(&ts_as.expression, scope),
2272        Expression::TSSatisfiesExpression(ts_sat) => {
2273            alias_replacement_kinded(&ts_sat.expression, scope)
2274        }
2275        Expression::StringLiteral(s) => {
2276            let value = s.value.text().into_owned();
2277            let is_bare =
2278                !value.starts_with("./") && !value.starts_with("../") && !value.starts_with('/');
2279            Some((value, is_bare))
2280        }
2281        // tsconfig `compilerOptions.paths` maps each key to an ARRAY of targets
2282        // (`{ "@/*": ["./src/*"] }`); take the first entry, matching the prior
2283        // non-kinded `expression_to_path_values().next()` behavior.
2284        Expression::ArrayExpression(arr) => arr
2285            .elements
2286            .iter()
2287            .find_map(ArrayExpressionElement::as_expression)
2288            .and_then(|element| alias_replacement_kinded(element, scope)),
2289        Expression::Identifier(id) => alias_constant::constant_replacement(id.name.as_str(), scope),
2290        _ => alias_entry::path_value(expr, scope).map(|value| (value, false)),
2291    }
2292}
2293
2294/// Maximum identifier-indirection hops the alias resolver follows before giving
2295/// up. Each local-variable or imported-binding resolution counts one hop. The
2296/// per-file `visited` set is the real cycle guard; this bound additionally
2297/// terminates pathological local self-references (`const a = a`). Real configs
2298/// rarely exceed one or two hops (`alias: importedAliases`).
2299const MAX_ALIAS_RESOLVE_DEPTH: usize = 8;
2300
2301/// Sibling-file extensions probed when an alias identifier is imported from a
2302/// relative specifier. Mirrors the JS/TS config extensions Vite/Vitest configs
2303/// and their shared alias modules use. `.js` first matches the common
2304/// JS-project case; the direct-as-written read happens before any probing. JSON
2305/// is intentionally excluded: it parses as a bare expression with no `export`,
2306/// so `find_exported_init` could never recover an alias literal from it.
2307const ALIAS_SIBLING_EXTS: [&str; 6] = ["js", "mjs", "cjs", "ts", "mts", "cts"];
2308
2309/// Resolve an alias expression into `(find, replacement, is_bare)` tuples,
2310/// following identifiers and expanding spreads.
2311///
2312/// Beyond the inline object (`{ '@': './src' }`) and array
2313/// (`[{ find, replacement }]`) forms, this handles the indirection shapes from
2314/// issue #811:
2315/// - an identifier bound to a local `const NAME = [...] | {...}`,
2316/// - an identifier imported from a relative sibling file
2317///   (`import { sharedAliases } from "./vite.shared.js"`), read one hop and
2318///   parsed for `export const NAME` / `export default` / `export { NAME }`,
2319/// - array spread elements (`[...a, ...b]`) and object spread properties
2320///   (`{ ...a, '@': './src' }`), each resolved recursively.
2321///
2322/// `config_path` is the file `expr` lives in (used to resolve relative sibling
2323/// imports). `visited` holds already-read sibling paths to break import cycles;
2324/// `depth` bounds identifier indirection via [`MAX_ALIAS_RESOLVE_DEPTH`].
2325fn resolve_alias_pairs_kinded(
2326    program: &Program,
2327    config_path: &Path,
2328    expr: &Expression,
2329    visited: &mut FxHashSet<PathBuf>,
2330    depth: usize,
2331) -> Vec<(String, String, bool)> {
2332    match expr {
2333        Expression::ParenthesizedExpression(paren) => {
2334            resolve_alias_pairs_kinded(program, config_path, &paren.expression, visited, depth)
2335        }
2336        Expression::TSAsExpression(ts_as) => {
2337            resolve_alias_pairs_kinded(program, config_path, &ts_as.expression, visited, depth)
2338        }
2339        Expression::TSSatisfiesExpression(ts_sat) => {
2340            resolve_alias_pairs_kinded(program, config_path, &ts_sat.expression, visited, depth)
2341        }
2342        Expression::ObjectExpression(obj) => {
2343            resolve_object_alias_pairs_kinded(program, config_path, obj, visited, depth)
2344        }
2345        Expression::ArrayExpression(arr) => {
2346            resolve_array_alias_pairs_kinded(program, config_path, arr, visited, depth)
2347        }
2348        Expression::Identifier(id) => {
2349            resolve_identifier_alias_pairs(program, config_path, id.name.as_str(), visited, depth)
2350        }
2351        _ => Vec::new(),
2352    }
2353}
2354
2355/// Resolve object-form alias pairs (`{ '@': './src', ...spread }`), expanding
2356/// spread properties recursively.
2357fn resolve_object_alias_pairs_kinded(
2358    program: &Program,
2359    config_path: &Path,
2360    obj: &ObjectExpression,
2361    visited: &mut FxHashSet<PathBuf>,
2362    depth: usize,
2363) -> Vec<(String, String, bool)> {
2364    let mut pairs = Vec::new();
2365    for prop in &obj.properties {
2366        match prop {
2367            ObjectPropertyKind::ObjectProperty(prop) => {
2368                if let Some(find) = property_key_to_string(&prop.key)
2369                    && let Some((replacement, is_bare)) =
2370                        alias_replacement_kinded(&prop.value, PathScope::Program(program))
2371                {
2372                    pairs.push((find, replacement, is_bare));
2373                }
2374            }
2375            // `{ ...sharedAliases, '@': './src' }`
2376            ObjectPropertyKind::SpreadProperty(spread) => {
2377                pairs.extend(resolve_alias_pairs_kinded(
2378                    program,
2379                    config_path,
2380                    &spread.argument,
2381                    visited,
2382                    depth,
2383                ));
2384            }
2385        }
2386    }
2387    pairs
2388}
2389
2390/// Resolve array-form alias pairs (`[{ find, replacement }, ...spread]`),
2391/// expanding spread elements recursively.
2392fn resolve_array_alias_pairs_kinded(
2393    program: &Program,
2394    config_path: &Path,
2395    arr: &ArrayExpression,
2396    visited: &mut FxHashSet<PathBuf>,
2397    depth: usize,
2398) -> Vec<(String, String, bool)> {
2399    let mut pairs = Vec::new();
2400    for element in &arr.elements {
2401        match element {
2402            // `[...sharedAliases, { find, replacement }]`
2403            ArrayExpressionElement::SpreadElement(spread) => {
2404                pairs.extend(resolve_alias_pairs_kinded(
2405                    program,
2406                    config_path,
2407                    &spread.argument,
2408                    visited,
2409                    depth,
2410                ));
2411            }
2412            _ => {
2413                if let Some(Expression::ObjectExpression(obj)) = element.as_expression()
2414                    && let Some(pair) =
2415                        alias_entry::object_alias_pair(obj, PathScope::Program(program))
2416                {
2417                    pairs.push(pair);
2418                }
2419            }
2420        }
2421    }
2422    pairs
2423}
2424
2425/// Resolve an identifier used as an alias value to its literal pairs, first by
2426/// local `const`/`let`/`var` binding, then by a one-hop relative import.
2427fn resolve_identifier_alias_pairs(
2428    program: &Program,
2429    config_path: &Path,
2430    name: &str,
2431    visited: &mut FxHashSet<PathBuf>,
2432    depth: usize,
2433) -> Vec<(String, String, bool)> {
2434    if depth >= MAX_ALIAS_RESOLVE_DEPTH {
2435        return Vec::new();
2436    }
2437    // Local `const NAME = [...] | {...}` (or `const NAME = otherIdentifier`).
2438    if let Some(init) = find_variable_init_expression(program, name) {
2439        return resolve_alias_pairs_kinded(program, config_path, init, visited, depth + 1);
2440    }
2441    // `import { NAME } from "./sibling"` / `import NAME from "./sibling"`.
2442    let Some((specifier, imported_name)) = find_relative_import_binding(program, name) else {
2443        return Vec::new();
2444    };
2445    resolve_imported_alias_pairs(
2446        config_path,
2447        &specifier,
2448        imported_name.as_deref(),
2449        visited,
2450        depth + 1,
2451    )
2452}
2453
2454/// Read a relative sibling file and resolve the alias literal it exports under
2455/// `imported_name` (`None` = default export).
2456fn resolve_imported_alias_pairs(
2457    config_path: &Path,
2458    specifier: &str,
2459    imported_name: Option<&str>,
2460    visited: &mut FxHashSet<PathBuf>,
2461    depth: usize,
2462) -> Vec<(String, String, bool)> {
2463    let Some((sibling_path, sibling_source)) = resolve_sibling_module(config_path, specifier)
2464    else {
2465        return Vec::new();
2466    };
2467    if !visited.insert(sibling_path.clone()) {
2468        return Vec::new();
2469    }
2470    extract_from_source(&sibling_source, &sibling_path, |program| {
2471        let init = find_exported_init(program, imported_name)?;
2472        let pairs = resolve_alias_pairs_kinded(program, &sibling_path, init, visited, depth);
2473        (!pairs.is_empty()).then_some(pairs)
2474    })
2475    .unwrap_or_default()
2476}
2477
2478/// Find a top-level variable declaration by name and return its init expression
2479/// (array, object, or another identifier). Covers bare `const NAME = ...` and
2480/// `export const NAME = ...`. Generalizes [`find_variable_init_object`] to any
2481/// init shape so the alias resolver can recurse on array/identifier inits.
2482fn find_variable_init_expression<'a>(
2483    program: &'a Program<'a>,
2484    name: &str,
2485) -> Option<&'a Expression<'a>> {
2486    for decl in top_level_variable_declarations(program) {
2487        for declarator in &decl.declarations {
2488            if let BindingPattern::BindingIdentifier(id) = &declarator.id
2489                && id.name == name
2490                && let Some(init) = &declarator.init
2491            {
2492                return Some(init);
2493            }
2494        }
2495    }
2496    None
2497}
2498
2499/// The expression a module exports as a whole: the right side of
2500/// `module.exports = ...`, or the expression of `export default ...`.
2501pub(crate) fn find_module_export_expression<'a>(
2502    program: &'a Program<'a>,
2503) -> Option<&'a Expression<'a>> {
2504    program.body.iter().find_map(|stmt| match stmt {
2505        Statement::ExportDefaultDeclaration(decl) => decl.declaration.as_expression(),
2506        Statement::ExpressionStatement(expr_stmt) => match &expr_stmt.expression {
2507            Expression::AssignmentExpression(assign) if is_module_exports_target(&assign.left) => {
2508                Some(&assign.right)
2509            }
2510            _ => None,
2511        },
2512        _ => None,
2513    })
2514}
2515
2516/// Find the init expression a sibling module exports under `name`
2517/// (`None` = default export). For named exports this covers both
2518/// `export const NAME = ...` and a local `const NAME = ...` later re-exported
2519/// via `export { NAME }` (both surface through [`find_variable_init_expression`]).
2520pub(crate) fn find_exported_init<'a>(
2521    program: &'a Program<'a>,
2522    name: Option<&str>,
2523) -> Option<&'a Expression<'a>> {
2524    match name {
2525        Some(name) => find_variable_init_expression(program, name),
2526        None => program.body.iter().find_map(|stmt| {
2527            if let Statement::ExportDefaultDeclaration(decl) = stmt {
2528                decl.declaration.as_expression()
2529            } else {
2530                None
2531            }
2532        }),
2533    }
2534}
2535
2536/// Find the import that binds local `name` to a RELATIVE module, returning the
2537/// specifier and the imported name (`None` for a default import). Bare-package
2538/// imports are intentionally skipped: reading a literal alias table out of
2539/// `node_modules` is not a real-world config shape.
2540pub(crate) fn find_relative_import_binding(
2541    program: &Program,
2542    name: &str,
2543) -> Option<(String, Option<String>)> {
2544    for stmt in &program.body {
2545        let Statement::ImportDeclaration(decl) = stmt else {
2546            continue;
2547        };
2548        let specifier = &*decl.source.value.text();
2549        if !is_relative_specifier(specifier) {
2550            continue;
2551        }
2552        let Some(specifiers) = &decl.specifiers else {
2553            continue;
2554        };
2555        for spec in specifiers {
2556            match spec {
2557                ImportDeclarationSpecifier::ImportSpecifier(spec) if spec.local.name == name => {
2558                    return Some((
2559                        specifier.to_string(),
2560                        Some(spec.imported.name().to_string()),
2561                    ));
2562                }
2563                ImportDeclarationSpecifier::ImportDefaultSpecifier(spec)
2564                    if spec.local.name == name =>
2565                {
2566                    return Some((specifier.to_string(), None));
2567                }
2568                _ => {}
2569            }
2570        }
2571    }
2572    None
2573}
2574
2575/// True for a relative/absolute module specifier (`./x`, `../x`, `/x`), the
2576/// shapes that point at a sibling file rather than an npm package.
2577pub(crate) fn is_relative_specifier(specifier: &str) -> bool {
2578    specifier.starts_with("./") || specifier.starts_with("../") || specifier.starts_with('/')
2579}
2580
2581/// Resolve a relative specifier against `config_path`'s directory to a sibling
2582/// file in the read scope of the project root (`config_project_root`), with its
2583/// source. Tries the path as written, then each known config extension (also
2584/// for dotted basenames that `Path::extension` misreads), then `index.*`.
2585pub(crate) fn resolve_sibling_module(
2586    config_path: &Path,
2587    specifier: &str,
2588) -> Option<(PathBuf, String)> {
2589    let parent = config_path.parent().unwrap_or(config_path);
2590    let (root, read) = (config_project_root(parent), read_project_file);
2591    let direct = parent.join(specifier);
2592    if let Some(source) = read(&root, &direct) {
2593        return Some((direct, source));
2594    }
2595    for ext in ALIAS_SIBLING_EXTS {
2596        let candidate = parent.join(format!("{specifier}.{ext}"));
2597        if let Some(source) = read(&root, &candidate) {
2598            return Some((candidate, source));
2599        }
2600    }
2601    for ext in ALIAS_SIBLING_EXTS {
2602        let candidate = direct.join(format!("index.{ext}"));
2603        if let Some(source) = read(&root, &candidate) {
2604            return Some((candidate, source));
2605        }
2606    }
2607    None
2608}
2609
2610pub(crate) fn lexical_normalize(path: &Path) -> PathBuf {
2611    let mut normalized = PathBuf::new();
2612    for component in path.components() {
2613        match component {
2614            std::path::Component::CurDir => {}
2615            std::path::Component::ParentDir => {
2616                normalized.pop();
2617            }
2618            _ => normalized.push(component.as_os_str()),
2619        }
2620    }
2621
2622    normalized
2623}
2624
2625/// Whether an existing `path` resolves inside `root`.
2626///
2627/// The check resolves `..` segments and symlinks, so a glob match such as
2628/// `packages/a/../../x` or a symlink to a directory above the project does not
2629/// pass. A path that does not exist does not pass.
2630pub(crate) fn is_inside_root(path: &Path, root: &Path) -> bool {
2631    let Ok(resolved) = std::fs::canonicalize(path) else {
2632        return false;
2633    };
2634    let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
2635    resolved.starts_with(root)
2636}
2637
2638/// Whether the literal base of a glob `pattern`, resolved against `dir`, is
2639/// inside `root`. The base is the part before the first glob character. An
2640/// absolute `pattern` replaces `dir`.
2641///
2642/// Check this before the glob runs, so a pattern such as `../**` never walks
2643/// the file system above the project. The base check is lexical. Filter each
2644/// match with [`is_inside_root`] too, because a glob segment can match `..`
2645/// or a symlink.
2646pub(crate) fn glob_base_is_inside_root(dir: &Path, pattern: &str, root: &Path) -> bool {
2647    let literal = &pattern[..pattern.find(['*', '?', '[', '{']).unwrap_or(pattern.len())];
2648    lexical_normalize(&dir.join(path_from_config_string(literal))).starts_with(root)
2649}
2650
2651/// Whether `specifier` is a bare package specifier: not empty, not relative or
2652/// absolute, not protocol-prefixed, and free of characters that are invalid in
2653/// an npm package name (backslashes, whitespace).
2654pub(crate) fn is_package_specifier(specifier: &str) -> bool {
2655    !specifier.is_empty()
2656        && specifier != "."
2657        && specifier != ".."
2658        && !specifier.starts_with("./")
2659        && !specifier.starts_with("../")
2660        && !specifier.starts_with('/')
2661        && !specifier.contains(':')
2662        && !specifier.contains('\\')
2663        && !specifier.chars().any(char::is_whitespace)
2664}
2665
2666/// Convert an expression to a string array if it's an array of string literals.
2667fn expression_to_string_array(expr: &Expression) -> Vec<String> {
2668    match expr {
2669        Expression::ArrayExpression(arr) => arr
2670            .elements
2671            .iter()
2672            .filter_map(|el| match el {
2673                ArrayExpressionElement::SpreadElement(_) => None,
2674                _ => el.as_expression().and_then(expression_to_string),
2675            })
2676            .collect(),
2677        _ => vec![],
2678    }
2679}
2680
2681/// Collect only top-level string values from an expression.
2682///
2683/// For arrays, extracts direct string elements and the first string element of sub-arrays
2684/// (to handle `["pkg-name", { options }]` tuples). Does NOT recurse into objects.
2685pub(crate) fn collect_shallow_string_values(expr: &Expression) -> Vec<String> {
2686    let mut values = Vec::new();
2687    match expr {
2688        Expression::StringLiteral(s) => {
2689            values.push(s.value.text().into_owned());
2690        }
2691        Expression::ArrayExpression(arr) => collect_shallow_array_values(arr, &mut values),
2692        Expression::ObjectExpression(obj) => {
2693            for prop in &obj.properties {
2694                if let ObjectPropertyKind::ObjectProperty(p) = prop {
2695                    match &p.value {
2696                        Expression::StringLiteral(s) => {
2697                            values.push(s.value.text().into_owned());
2698                        }
2699                        Expression::ArrayExpression(sub_arr) => {
2700                            if let Some(first) = sub_arr.elements.first()
2701                                && let Some(first_expr) = first.as_expression()
2702                                && let Some(s) = expression_to_string(first_expr)
2703                            {
2704                                values.push(s);
2705                            }
2706                        }
2707                        _ => {}
2708                    }
2709                }
2710            }
2711        }
2712        _ => {}
2713    }
2714    values
2715}
2716
2717/// Collect the strings and the first string of each tuple in an array. A
2718/// spread of an array literal, also behind a condition such as
2719/// `...(isCI ? ['a'] : [])`, adds the values of each branch.
2720fn collect_shallow_array_values(arr: &ArrayExpression<'_>, values: &mut Vec<String>) {
2721    for element in &arr.elements {
2722        let inner = match element {
2723            ArrayExpressionElement::SpreadElement(spread) => {
2724                collect_spread_array_values(&spread.argument, values);
2725                continue;
2726            }
2727            element => match element.as_expression() {
2728                Some(expr) => expr.get_inner_expression(),
2729                None => continue,
2730            },
2731        };
2732        match inner {
2733            Expression::StringLiteral(s) => values.push(s.value.text().into_owned()),
2734            Expression::ArrayExpression(sub_arr) => {
2735                if let Some(first) = sub_arr.elements.first()
2736                    && let Some(first_expr) = first.as_expression()
2737                    && let Some(s) = expression_to_string(first_expr)
2738                {
2739                    values.push(s);
2740                }
2741            }
2742            _ => {}
2743        }
2744    }
2745}
2746
2747/// Collect the values of a spread argument that is an array literal or a
2748/// condition with array literal branches.
2749fn collect_spread_array_values(expr: &Expression<'_>, values: &mut Vec<String>) {
2750    match expr.get_inner_expression() {
2751        Expression::ArrayExpression(arr) => collect_shallow_array_values(arr, values),
2752        Expression::ConditionalExpression(conditional) => {
2753            collect_spread_array_values(&conditional.consequent, values);
2754            collect_spread_array_values(&conditional.alternate, values);
2755        }
2756        Expression::LogicalExpression(logical) => {
2757            collect_spread_array_values(&logical.right, values);
2758        }
2759        _ => {}
2760    }
2761}
2762
2763/// Collect top-level string values, plus a named string property from object entries.
2764pub(crate) fn collect_shallow_string_or_object_property_values(
2765    expr: &Expression,
2766    object_property: &str,
2767) -> Vec<String> {
2768    match expr {
2769        Expression::ArrayExpression(arr) => arr
2770            .elements
2771            .iter()
2772            .filter_map(|element| {
2773                element
2774                    .as_expression()
2775                    .and_then(|expr| shallow_string_or_object_property(expr, object_property))
2776            })
2777            .collect(),
2778        _ => shallow_string_or_object_property(expr, object_property)
2779            .into_iter()
2780            .collect(),
2781    }
2782}
2783
2784fn shallow_string_or_object_property(expr: &Expression, object_property: &str) -> Option<String> {
2785    match expr {
2786        Expression::ParenthesizedExpression(paren) => {
2787            shallow_string_or_object_property(&paren.expression, object_property)
2788        }
2789        Expression::TSSatisfiesExpression(ts_sat) => {
2790            shallow_string_or_object_property(&ts_sat.expression, object_property)
2791        }
2792        Expression::TSAsExpression(ts_as) => {
2793            shallow_string_or_object_property(&ts_as.expression, object_property)
2794        }
2795        Expression::ArrayExpression(sub_arr) => sub_arr
2796            .elements
2797            .first()
2798            .and_then(ArrayExpressionElement::as_expression)
2799            .and_then(expression_to_string),
2800        Expression::ObjectExpression(obj) => {
2801            find_property(obj, object_property).and_then(|prop| expression_to_string(&prop.value))
2802        }
2803        _ => expression_to_string(expr),
2804    }
2805}
2806
2807/// Recursively collect all string literal values from an expression tree.
2808fn collect_all_string_values(expr: &Expression, values: &mut Vec<String>) {
2809    match expr {
2810        Expression::StringLiteral(s) => {
2811            values.push(s.value.text().into_owned());
2812        }
2813        Expression::ArrayExpression(arr) => {
2814            for el in &arr.elements {
2815                if let Some(expr) = el.as_expression() {
2816                    collect_all_string_values(expr, values);
2817                }
2818            }
2819        }
2820        Expression::ObjectExpression(obj) => {
2821            for prop in &obj.properties {
2822                if let ObjectPropertyKind::ObjectProperty(p) = prop {
2823                    collect_all_string_values(&p.value, values);
2824                }
2825            }
2826        }
2827        _ => {}
2828    }
2829}
2830
2831/// Convert a `PropertyKey` to a `String`.
2832pub(crate) fn property_key_to_string(key: &PropertyKey) -> Option<String> {
2833    match key {
2834        PropertyKey::StaticIdentifier(id) => Some(id.name.to_string()),
2835        PropertyKey::StringLiteral(s) => Some(s.value.text().into_owned()),
2836        _ => None,
2837    }
2838}
2839
2840/// Extract keys of an object at a nested property path.
2841fn get_nested_object_keys(obj: &ObjectExpression, path: &[&str]) -> Option<Vec<String>> {
2842    if path.is_empty() {
2843        return None;
2844    }
2845    let prop = find_property(obj, path[0])?;
2846    if path.len() == 1 {
2847        if let Expression::ObjectExpression(nested) = &prop.value {
2848            let keys = nested
2849                .properties
2850                .iter()
2851                .filter_map(|p| {
2852                    if let ObjectPropertyKind::ObjectProperty(p) = p {
2853                        property_key_to_string(&p.key)
2854                    } else {
2855                        None
2856                    }
2857                })
2858                .collect();
2859            return Some(keys);
2860        }
2861        return None;
2862    }
2863    if let Expression::ObjectExpression(nested) = &prop.value {
2864        get_nested_object_keys(nested, &path[1..])
2865    } else {
2866        None
2867    }
2868}
2869
2870/// Navigate a nested property path and return the raw expression at the end.
2871fn get_nested_expression<'a>(
2872    obj: &'a ObjectExpression<'a>,
2873    path: &[&str],
2874) -> Option<&'a Expression<'a>> {
2875    if path.is_empty() {
2876        return None;
2877    }
2878    let prop = find_property(obj, path[0])?;
2879    if path.len() == 1 {
2880        return Some(&prop.value);
2881    }
2882    if let Expression::ObjectExpression(nested) = &prop.value {
2883        get_nested_expression(nested, &path[1..])
2884    } else {
2885        None
2886    }
2887}
2888
2889/// Navigate a nested path and extract a string, string array, or object string/array values.
2890fn get_nested_string_or_array(
2891    obj: &ObjectExpression,
2892    path: &[&str],
2893    scope: PathScope<'_>,
2894) -> Option<Vec<String>> {
2895    if path.is_empty() {
2896        return None;
2897    }
2898    if path.len() == 1 {
2899        let prop = find_property(obj, path[0])?;
2900        return Some(string_or_array_in(&prop.value, scope));
2901    }
2902    let prop = find_property(obj, path[0])?;
2903    if let Expression::ObjectExpression(nested) = &prop.value {
2904        get_nested_string_or_array(nested, &path[1..], scope)
2905    } else {
2906        None
2907    }
2908}
2909
2910/// Convert an expression to a `Vec<String>`, handling string, array, object-with-string/array values,
2911/// and Webpack 5 entry descriptors (`{ import: "..." }`).
2912///
2913/// Array elements that are object literals are inspected for an `input` property
2914/// (Angular CLI schema for `styles`/`scripts`/`polyfills`:
2915/// `{ "input": "src/x.scss", "bundleName": "x", "inject": false }`). Extracting
2916/// `input` prevents object-form entries from being silently dropped. See #126.
2917pub(crate) fn expression_to_string_or_array(expr: &Expression) -> Vec<String> {
2918    string_or_array_in(expr, PathScope::Bare)
2919}
2920
2921/// Collect `require('...')` argument strings from an expression.
2922fn collect_require_sources(expr: &Expression) -> Vec<String> {
2923    let mut sources = Vec::new();
2924    match expr {
2925        Expression::CallExpression(call) if is_require_call(call) => {
2926            if let Some(s) = get_require_source(call) {
2927                sources.push(s);
2928            }
2929        }
2930        Expression::ArrayExpression(arr) => {
2931            for el in &arr.elements {
2932                if let Some(inner) = el.as_expression() {
2933                    match inner {
2934                        Expression::CallExpression(call) if is_require_call(call) => {
2935                            if let Some(s) = get_require_source(call) {
2936                                sources.push(s);
2937                            }
2938                        }
2939                        Expression::ArrayExpression(sub_arr) => {
2940                            if let Some(first) = sub_arr.elements.first()
2941                                && let Some(Expression::CallExpression(call)) =
2942                                    first.as_expression()
2943                                && is_require_call(call)
2944                                && let Some(s) = get_require_source(call)
2945                            {
2946                                sources.push(s);
2947                            }
2948                        }
2949                        _ => {}
2950                    }
2951                }
2952            }
2953        }
2954        _ => {}
2955    }
2956    sources
2957}
2958
2959/// Check if a call expression is `require(...)`.
2960pub(crate) fn is_require_call(call: &CallExpression) -> bool {
2961    matches!(&call.callee, Expression::Identifier(id) if id.name == "require")
2962}
2963
2964/// Get the first string argument of a `require()` call.
2965pub(crate) fn get_require_source(call: &CallExpression) -> Option<String> {
2966    call.arguments.first().and_then(|arg| {
2967        if let Argument::StringLiteral(s) = arg {
2968            Some(s.value.text().into_owned())
2969        } else {
2970            None
2971        }
2972    })
2973}
2974
2975#[cfg(test)]
2976mod tests {
2977    use super::*;
2978    use std::path::PathBuf;
2979
2980    fn js_path() -> PathBuf {
2981        PathBuf::from("config.js")
2982    }
2983
2984    fn ts_path() -> PathBuf {
2985        PathBuf::from("config.ts")
2986    }
2987
2988    #[test]
2989    fn extract_config_array_tuple_heads_reads_first_string_of_each_tuple() {
2990        let source = r#"
2991            export default defineNuxtConfig({
2992                modules: ["@nuxt/image", ["@nuxt/content", { watch: false }], [someModule, {}], []]
2993            });
2994        "#;
2995        assert_eq!(
2996            extract_config_array_tuple_heads(source, &ts_path(), &["modules"]),
2997            vec!["@nuxt/content".to_string()]
2998        );
2999    }
3000
3001    #[test]
3002    fn extract_lazy_imports_bare_arrows() {
3003        let source = r"
3004            import { defineConfig } from '@adonisjs/core/app'
3005            export default defineConfig({
3006                preloads: [
3007                    () => import('#start/routes'),
3008                    () => import('#start/kernel'),
3009                ],
3010            })
3011        ";
3012        let specs = extract_lazy_imports_in_array(source, &ts_path(), &["preloads"]);
3013        assert_eq!(specs, vec!["#start/routes", "#start/kernel"]);
3014    }
3015
3016    #[test]
3017    fn extract_lazy_imports_object_form_with_file_key() {
3018        let source = r"
3019            export default defineConfig({
3020                providers: [
3021                    () => import('@adonisjs/core/providers/app_provider'),
3022                    {
3023                        file: () => import('@adonisjs/core/providers/repl_provider'),
3024                        environment: ['repl', 'test'],
3025                    },
3026                ],
3027            })
3028        ";
3029        let specs = extract_lazy_imports_in_array(source, &ts_path(), &["providers"]);
3030        assert_eq!(
3031            specs,
3032            vec![
3033                "@adonisjs/core/providers/app_provider",
3034                "@adonisjs/core/providers/repl_provider",
3035            ]
3036        );
3037    }
3038
3039    #[test]
3040    fn extract_lazy_imports_block_body_with_return() {
3041        let source = r"
3042            export default defineConfig({
3043                commands: [
3044                    () => { return import('@adonisjs/core/commands') },
3045                ],
3046            })
3047        ";
3048        let specs = extract_lazy_imports_in_array(source, &ts_path(), &["commands"]);
3049        assert_eq!(specs, vec!["@adonisjs/core/commands"]);
3050    }
3051
3052    #[test]
3053    fn extract_lazy_imports_skips_unknown_element_shapes() {
3054        let source = r"
3055            export default defineConfig({
3056                commands: [
3057                    'string-entry',
3058                    42,
3059                    { other: 'value' },
3060                    () => import('@adonisjs/lucid/commands'),
3061                ],
3062            })
3063        ";
3064        let specs = extract_lazy_imports_in_array(source, &ts_path(), &["commands"]);
3065        assert_eq!(specs, vec!["@adonisjs/lucid/commands"]);
3066    }
3067
3068    #[test]
3069    fn extract_lazy_imports_missing_property_returns_empty() {
3070        let source = r"
3071            export default defineConfig({
3072                preloads: [() => import('#start/routes')],
3073            })
3074        ";
3075        let specs = extract_lazy_imports_in_array(source, &ts_path(), &["providers"]);
3076        assert!(specs.is_empty());
3077    }
3078
3079    #[test]
3080    fn extract_imports_basic() {
3081        let source = r"
3082            import foo from 'foo-pkg';
3083            import { bar } from '@scope/bar';
3084            export default {};
3085        ";
3086        let imports = extract_imports(source, &js_path());
3087        assert_eq!(imports, vec!["foo-pkg", "@scope/bar"]);
3088    }
3089
3090    #[test]
3091    fn extract_default_export_object_property() {
3092        let source = r#"export default { testDir: "./tests" };"#;
3093        let val = extract_config_string(source, &js_path(), &["testDir"]);
3094        assert_eq!(val, Some("./tests".to_string()));
3095    }
3096
3097    #[test]
3098    fn extract_define_config_property() {
3099        let source = r#"
3100            import { defineConfig } from 'vitest/config';
3101            export default defineConfig({
3102                test: {
3103                    include: ["**/*.test.ts", "**/*.spec.ts"],
3104                    setupFiles: ["./test/setup.ts"]
3105                }
3106            });
3107        "#;
3108        let include = extract_config_string_array(source, &ts_path(), &["test", "include"]);
3109        assert_eq!(include, vec!["**/*.test.ts", "**/*.spec.ts"]);
3110
3111        let setup = extract_config_string_array(source, &ts_path(), &["test", "setupFiles"]);
3112        assert_eq!(setup, vec!["./test/setup.ts"]);
3113    }
3114
3115    #[test]
3116    fn extract_module_exports_property() {
3117        let source = r#"module.exports = { testEnvironment: "jsdom" };"#;
3118        let val = extract_config_string(source, &js_path(), &["testEnvironment"]);
3119        assert_eq!(val, Some("jsdom".to_string()));
3120    }
3121
3122    #[test]
3123    fn extract_nested_string_array() {
3124        let source = r#"
3125            export default {
3126                resolve: {
3127                    alias: {
3128                        "@": "./src"
3129                    }
3130                },
3131                test: {
3132                    include: ["src/**/*.test.ts"]
3133                }
3134            };
3135        "#;
3136        let include = extract_config_string_array(source, &js_path(), &["test", "include"]);
3137        assert_eq!(include, vec!["src/**/*.test.ts"]);
3138    }
3139
3140    #[test]
3141    fn extract_addons_array() {
3142        let source = r#"
3143            export default {
3144                addons: [
3145                    "@storybook/addon-a11y",
3146                    "@storybook/addon-docs",
3147                    "@storybook/addon-links"
3148                ]
3149            };
3150        "#;
3151        let addons = extract_config_property_strings(source, &ts_path(), "addons");
3152        assert_eq!(
3153            addons,
3154            vec![
3155                "@storybook/addon-a11y",
3156                "@storybook/addon-docs",
3157                "@storybook/addon-links"
3158            ]
3159        );
3160    }
3161
3162    #[test]
3163    fn handle_empty_config() {
3164        let source = "";
3165        let result = extract_config_string(source, &js_path(), &["key"]);
3166        assert_eq!(result, None);
3167    }
3168
3169    #[test]
3170    fn object_keys_postcss_plugins() {
3171        let source = r"
3172            module.exports = {
3173                plugins: {
3174                    autoprefixer: {},
3175                    tailwindcss: {},
3176                    'postcss-import': {}
3177                }
3178            };
3179        ";
3180        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
3181        assert_eq!(keys, vec!["autoprefixer", "tailwindcss", "postcss-import"]);
3182    }
3183
3184    #[test]
3185    fn object_keys_nested_path() {
3186        let source = r"
3187            export default {
3188                build: {
3189                    plugins: {
3190                        minify: {},
3191                        compress: {}
3192                    }
3193                }
3194            };
3195        ";
3196        let keys = extract_config_object_keys(source, &js_path(), &["build", "plugins"]);
3197        assert_eq!(keys, vec!["minify", "compress"]);
3198    }
3199
3200    #[test]
3201    fn object_keys_empty_object() {
3202        let source = r"export default { plugins: {} };";
3203        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
3204        assert!(keys.is_empty());
3205    }
3206
3207    #[test]
3208    fn object_keys_non_object_returns_empty() {
3209        let source = r#"export default { plugins: ["a", "b"] };"#;
3210        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
3211        assert!(keys.is_empty());
3212    }
3213
3214    #[test]
3215    fn string_or_array_single_string() {
3216        let source = r#"export default { entry: "./src/index.js" };"#;
3217        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
3218        assert_eq!(result, vec!["./src/index.js"]);
3219    }
3220
3221    #[test]
3222    fn string_or_array_array() {
3223        let source = r#"export default { entry: ["./src/a.js", "./src/b.js"] };"#;
3224        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
3225        assert_eq!(result, vec!["./src/a.js", "./src/b.js"]);
3226    }
3227
3228    #[test]
3229    fn string_or_array_object_values() {
3230        let source =
3231            r#"export default { entry: { main: "./src/main.js", vendor: "./src/vendor.js" } };"#;
3232        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
3233        assert_eq!(result, vec!["./src/main.js", "./src/vendor.js"]);
3234    }
3235
3236    #[test]
3237    fn array_or_object_string_or_array_reads_each_array_element() {
3238        let source = r#"
3239            const shared = { format: ["esm"] };
3240            export default defineConfig([
3241                { entry: "./src/a.ts" },
3242                ({ ...shared, entry: { b: "./src/b.ts" } }),
3243                { entry: ["./src/c.ts"] } satisfies Options,
3244                { format: ["cjs"] },
3245                shared,
3246            ] as Options[]);
3247        "#;
3248        let result = extract_config_array_or_object_string_or_array(source, &ts_path(), &["entry"]);
3249        assert_eq!(result, vec!["./src/a.ts", "./src/b.ts", "./src/c.ts"]);
3250    }
3251
3252    #[test]
3253    fn array_or_object_string_or_array_falls_back_to_config_object() {
3254        let source = r#"export default defineConfig({ entry: { main: "./src/main.ts" } });"#;
3255        let result = extract_config_array_or_object_string_or_array(source, &ts_path(), &["entry"]);
3256        assert_eq!(result, vec!["./src/main.ts"]);
3257    }
3258
3259    #[test]
3260    fn string_or_array_object_array_values() {
3261        let source = r#"export default { entry: { app: ["./src/polyfill.js", "./src/app.js"] } };"#;
3262        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
3263        assert_eq!(result, vec!["./src/polyfill.js", "./src/app.js"]);
3264    }
3265
3266    #[test]
3267    fn string_or_array_webpack_entry_descriptors() {
3268        let source = r#"
3269            export default {
3270                entry: {
3271                    app: {
3272                        import: "./src/app.js",
3273                        filename: "pages/app.js",
3274                        dependOn: "shared",
3275                    },
3276                    admin: {
3277                        import: ["./src/admin-polyfill.js", "./src/admin.js"],
3278                        runtime: "runtime",
3279                    },
3280                    shared: ["react", "react-dom"],
3281                },
3282            };
3283        "#;
3284        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
3285        assert_eq!(
3286            result,
3287            vec![
3288                "./src/app.js",
3289                "./src/admin-polyfill.js",
3290                "./src/admin.js",
3291                "react",
3292                "react-dom"
3293            ]
3294        );
3295    }
3296
3297    #[test]
3298    fn string_or_array_nested_path() {
3299        let source = r#"
3300            export default {
3301                build: {
3302                    rollupOptions: {
3303                        input: ["./index.html", "./about.html"]
3304                    }
3305                }
3306            };
3307        "#;
3308        let result = extract_config_string_or_array(
3309            source,
3310            &js_path(),
3311            &["build", "rollupOptions", "input"],
3312        );
3313        assert_eq!(result, vec!["./index.html", "./about.html"]);
3314    }
3315
3316    #[test]
3317    fn string_or_array_template_literal() {
3318        let source = r"export default { entry: `./src/index.js` };";
3319        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
3320        assert_eq!(result, vec!["./src/index.js"]);
3321    }
3322
3323    #[test]
3324    fn string_or_array_object_path_helper_values() {
3325        let source = r#"
3326            import { resolve, join } from "node:path";
3327            import path from "node:path";
3328            export default {
3329                build: {
3330                    rollupOptions: {
3331                        input: {
3332                            app: resolve(__dirname, "src/app.ts"),
3333                            modal: path.resolve(__dirname, "src/modal.ts"),
3334                            tabs: join(__dirname, "src/tabs.ts"),
3335                            styles: resolve(__dirname, "src/index.css"),
3336                        },
3337                    },
3338                },
3339            };
3340        "#;
3341        let result = extract_config_string_or_array(
3342            source,
3343            &js_path(),
3344            &["build", "rollupOptions", "input"],
3345        );
3346        assert_eq!(
3347            result,
3348            vec!["src/app.ts", "src/modal.ts", "src/tabs.ts", "src/index.css"]
3349        );
3350    }
3351
3352    #[test]
3353    fn string_or_array_array_path_helper_values() {
3354        let source = r#"
3355            import { resolve } from "node:path";
3356            export default {
3357                build: {
3358                    rollupOptions: {
3359                        input: [resolve(__dirname, "src/a.ts"), "./src/b.ts"],
3360                    },
3361                },
3362            };
3363        "#;
3364        let result = extract_config_string_or_array(
3365            source,
3366            &js_path(),
3367            &["build", "rollupOptions", "input"],
3368        );
3369        assert_eq!(result, vec!["src/a.ts", "./src/b.ts"]);
3370    }
3371
3372    #[test]
3373    fn string_or_array_top_level_path_helper_call() {
3374        let source = r#"
3375            import { resolve } from "node:path";
3376            export default { build: { lib: { entry: resolve(__dirname, "src/index.ts") } } };
3377        "#;
3378        let result = extract_config_string_or_array(source, &js_path(), &["build", "lib", "entry"]);
3379        assert_eq!(result, vec!["src/index.ts"]);
3380    }
3381
3382    #[test]
3383    fn string_or_array_import_meta_dirname_anchor() {
3384        let source = r#"
3385            import { resolve } from "node:path";
3386            export default {
3387                build: { lib: { entry: resolve(import.meta.dirname, "src/index.ts") } },
3388            };
3389        "#;
3390        let result = extract_config_string_or_array(source, &ts_path(), &["build", "lib", "entry"]);
3391        assert_eq!(result, vec!["src/index.ts"]);
3392    }
3393
3394    #[test]
3395    fn string_or_array_non_literal_path_helper_args_dropped() {
3396        let source = r#"
3397            import { resolve } from "node:path";
3398            export default { build: { lib: { entry: resolve(baseDir, "src/index.ts") } } };
3399        "#;
3400        let result = extract_config_string_or_array(source, &js_path(), &["build", "lib", "entry"]);
3401        assert!(
3402            result.is_empty(),
3403            "non-literal path-helper args must be dropped: {result:?}"
3404        );
3405    }
3406
3407    #[test]
3408    fn require_strings_array() {
3409        let source = r"
3410            module.exports = {
3411                plugins: [
3412                    require('autoprefixer'),
3413                    require('postcss-import')
3414                ]
3415            };
3416        ";
3417        let deps = extract_config_require_strings(source, &js_path(), "plugins");
3418        assert_eq!(deps, vec!["autoprefixer", "postcss-import"]);
3419    }
3420
3421    #[test]
3422    fn require_strings_with_tuples() {
3423        let source = r"
3424            module.exports = {
3425                plugins: [
3426                    require('autoprefixer'),
3427                    [require('postcss-preset-env'), { stage: 3 }]
3428                ]
3429            };
3430        ";
3431        let deps = extract_config_require_strings(source, &js_path(), "plugins");
3432        assert_eq!(deps, vec!["autoprefixer", "postcss-preset-env"]);
3433    }
3434
3435    #[test]
3436    fn require_strings_empty_array() {
3437        let source = r"module.exports = { plugins: [] };";
3438        let deps = extract_config_require_strings(source, &js_path(), "plugins");
3439        assert!(deps.is_empty());
3440    }
3441
3442    #[test]
3443    fn require_strings_no_require_calls() {
3444        let source = r#"module.exports = { plugins: ["a", "b"] };"#;
3445        let deps = extract_config_require_strings(source, &js_path(), "plugins");
3446        assert!(deps.is_empty());
3447    }
3448
3449    #[test]
3450    fn extract_aliases_from_object_with_file_url_to_path() {
3451        let source = r#"
3452            import { defineConfig } from 'vite';
3453            import { fileURLToPath, URL } from 'node:url';
3454
3455            export default defineConfig({
3456                resolve: {
3457                    alias: {
3458                        "@": fileURLToPath(new URL("./src", import.meta.url))
3459                    }
3460                }
3461            });
3462        "#;
3463
3464        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
3465        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string())]);
3466    }
3467
3468    #[test]
3469    fn extract_aliases_from_array_form() {
3470        let source = r#"
3471            export default {
3472                resolve: {
3473                    alias: [
3474                        { find: "@", replacement: "./src" },
3475                        { find: "$utils", replacement: "src/lib/utils" }
3476                    ]
3477                }
3478            };
3479        "#;
3480
3481        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
3482        assert_eq!(
3483            aliases,
3484            vec![
3485                ("@".to_string(), "./src".to_string()),
3486                ("$utils".to_string(), "src/lib/utils".to_string())
3487            ]
3488        );
3489    }
3490
3491    #[test]
3492    fn extract_aliases_from_object_with_array_values() {
3493        let source = r#"
3494            ({
3495                compilerOptions: {
3496                    paths: {
3497                        "@/*": ["./src/*"],
3498                        "@shared/*": ["./shared/*", "./fallback/*"]
3499                    }
3500                }
3501            })
3502        "#;
3503
3504        let aliases = extract_config_aliases(source, &js_path(), &["compilerOptions", "paths"]);
3505        assert_eq!(
3506            aliases,
3507            vec![
3508                ("@/*".to_string(), "./src/*".to_string()),
3509                ("@shared/*".to_string(), "./shared/*".to_string())
3510            ]
3511        );
3512    }
3513
3514    #[test]
3515    fn extract_array_object_strings_mixed_forms() {
3516        let source = r#"
3517            export default {
3518                components: [
3519                    "~/components",
3520                    { path: "@/feature-components" }
3521                ]
3522            };
3523        "#;
3524
3525        let values =
3526            extract_config_array_object_strings(source, &ts_path(), &["components"], "path");
3527        assert_eq!(
3528            values,
3529            vec![
3530                "~/components".to_string(),
3531                "@/feature-components".to_string()
3532            ]
3533        );
3534    }
3535
3536    #[test]
3537    fn extract_config_plugin_option_string_from_json() {
3538        let source = r#"{
3539            "expo": {
3540                "plugins": [
3541                    ["expo-router", { "root": "src/app" }]
3542                ]
3543            }
3544        }"#;
3545
3546        let value = extract_config_plugin_option_string(
3547            source,
3548            &json_path(),
3549            &["expo", "plugins"],
3550            "expo-router",
3551            "root",
3552        );
3553
3554        assert_eq!(value, Some("src/app".to_string()));
3555    }
3556
3557    #[test]
3558    fn extract_config_plugin_option_string_from_top_level_plugins() {
3559        let source = r#"{
3560            "plugins": [
3561                ["expo-router", { "root": "./src/routes" }]
3562            ]
3563        }"#;
3564
3565        let value = extract_config_plugin_option_string_from_paths(
3566            source,
3567            &json_path(),
3568            &[&["plugins"], &["expo", "plugins"]],
3569            "expo-router",
3570            "root",
3571        );
3572
3573        assert_eq!(value, Some("./src/routes".to_string()));
3574    }
3575
3576    #[test]
3577    fn extract_config_plugin_option_string_from_ts_config() {
3578        let source = r"
3579            export default {
3580                expo: {
3581                    plugins: [
3582                        ['expo-router', { root: './src/app' }]
3583                    ]
3584                }
3585            };
3586        ";
3587
3588        let value = extract_config_plugin_option_string(
3589            source,
3590            &ts_path(),
3591            &["expo", "plugins"],
3592            "expo-router",
3593            "root",
3594        );
3595
3596        assert_eq!(value, Some("./src/app".to_string()));
3597    }
3598
3599    #[test]
3600    fn extract_config_plugin_option_string_returns_none_when_plugin_missing() {
3601        let source = r#"{
3602            "expo": {
3603                "plugins": [
3604                    ["expo-font", {}]
3605                ]
3606            }
3607        }"#;
3608
3609        let value = extract_config_plugin_option_string(
3610            source,
3611            &json_path(),
3612            &["expo", "plugins"],
3613            "expo-router",
3614            "root",
3615        );
3616
3617        assert_eq!(value, None);
3618    }
3619
3620    #[test]
3621    fn vite_react_babel_dependencies_extract_plain_tuple_and_prefixed_entries() {
3622        let source = r#"
3623            import react from "@vitejs/plugin-react";
3624
3625            export default defineConfig({
3626                plugins: [
3627                    react({
3628                        babel: {
3629                            plugins: [
3630                                "babel-plugin-plain",
3631                                ["module:@preact/signals-react-transform", { mode: "auto" }],
3632                            ],
3633                            presets: [["@babel/preset-react", { runtime: "automatic" }]],
3634                        },
3635                    }),
3636                ],
3637            });
3638        "#;
3639
3640        let deps = extract_vite_plugin_option_dependencies(source, &ts_path());
3641
3642        assert_eq!(
3643            deps,
3644            vec![
3645                "babel-plugin-plain".to_string(),
3646                "@preact/signals-react-transform".to_string(),
3647                "@babel/preset-react".to_string(),
3648            ]
3649        );
3650    }
3651
3652    #[test]
3653    fn vite_react_babel_dependencies_support_default_alias_import() {
3654        let source = r#"
3655            import { default as viteReact } from "@vitejs/plugin-react";
3656
3657            export default {
3658                plugins: [
3659                    viteReact({
3660                        babel: {
3661                            plugins: [["module:@scope/pkg/plugin", {}]],
3662                        },
3663                    }),
3664                ],
3665            };
3666        "#;
3667
3668        let deps = extract_vite_plugin_option_dependencies(source, &ts_path());
3669
3670        assert_eq!(deps, vec!["@scope/pkg".to_string()]);
3671    }
3672
3673    #[test]
3674    fn vite_react_babel_dependencies_ignore_unrelated_plugin_calls() {
3675        let source = r#"
3676            import vue from "@vitejs/plugin-vue";
3677
3678            export default {
3679                plugins: [
3680                    vue({
3681                        babel: {
3682                            plugins: ["@preact/signals-react-transform"],
3683                        },
3684                    }),
3685                ],
3686            };
3687        "#;
3688
3689        let deps = extract_vite_plugin_option_dependencies(source, &ts_path());
3690
3691        assert!(deps.is_empty());
3692    }
3693
3694    #[test]
3695    fn vite_react_babel_dependencies_skip_relative_and_protocol_entries() {
3696        let source = r#"
3697            import react from "@vitejs/plugin-react";
3698
3699            export default {
3700                plugins: [
3701                    react({
3702                        babel: {
3703                            plugins: ["./local-plugin", "module:./local-prefixed", "http://example.com/plugin"],
3704                        },
3705                    }),
3706                ],
3707            };
3708        "#;
3709
3710        let deps = extract_vite_plugin_option_dependencies(source, &ts_path());
3711
3712        assert!(deps.is_empty());
3713    }
3714
3715    #[test]
3716    fn normalize_config_path_relative_to_root() {
3717        let config_path = PathBuf::from("/project/vite.config.ts");
3718        let root = PathBuf::from("/project");
3719
3720        assert_eq!(
3721            normalize_config_path("./src/lib", &config_path, &root),
3722            Some("src/lib".to_string())
3723        );
3724        assert_eq!(
3725            normalize_config_path("/src/lib", &config_path, &root),
3726            Some("src/lib".to_string())
3727        );
3728    }
3729
3730    #[test]
3731    fn normalize_config_path_mixed_separators_and_parent_dirs() {
3732        let config_path = PathBuf::from("/project/config/vite.config.ts");
3733        let root = PathBuf::from("/project");
3734
3735        assert_eq!(
3736            normalize_config_path(".\\src\\..\\app\\lib", &config_path, &root),
3737            Some("config/app/lib".to_string())
3738        );
3739    }
3740
3741    /// Issue #2806: a literal absolute path under the project root is read as
3742    /// absolute, not joined onto the root a second time.
3743    #[test]
3744    fn normalize_config_path_reads_an_absolute_path_under_root_as_absolute() {
3745        let root = std::env::temp_dir().join("fallow-2806-project");
3746        let config_path = root.join("vite.config.ts");
3747        let absolute = path_to_config_string(&root.join("src").join("lib"));
3748
3749        assert_eq!(
3750            normalize_config_path(&absolute, &config_path, &root),
3751            Some("src/lib".to_string())
3752        );
3753        assert_eq!(
3754            normalize_filesystem_config_path(&absolute, &config_path, &root),
3755            Some("src/lib".to_string())
3756        );
3757    }
3758
3759    /// Vite reads a leading `/` as relative to the root when the value is the
3760    /// root itself, or when `<root>/<root>` is a directory (its `rootInRoot`
3761    /// rule). A project checked out at `/src` with a `src/` folder and the
3762    /// alias `'@': '/src'` resolves to `/src/src`.
3763    #[cfg(unix)]
3764    #[test]
3765    fn normalize_config_path_keeps_the_vite_root_in_root_reading() {
3766        let temp = tempfile::tempdir().expect("temp dir");
3767        let root = temp.path().join("src");
3768        std::fs::create_dir_all(&root).expect("root dir");
3769        let config_path = root.join("vite.config.ts");
3770        let root_string = path_to_config_string(&root);
3771        let nested = root_string.trim_start_matches('/').to_string();
3772        let under = format!("{root_string}/lib");
3773
3774        assert_eq!(
3775            normalize_config_path(&root_string, &config_path, &root),
3776            Some(nested.clone())
3777        );
3778        assert_eq!(
3779            normalize_config_path(&under, &config_path, &root),
3780            Some("lib".to_string())
3781        );
3782
3783        std::fs::create_dir_all(root.join(&nested)).expect("root-in-root dir");
3784        assert_eq!(
3785            normalize_config_path(&under, &config_path, &root),
3786            Some(format!("{nested}/lib"))
3787        );
3788        assert_eq!(
3789            normalize_filesystem_config_path(&under, &config_path, &root),
3790            Some("lib".to_string())
3791        );
3792    }
3793
3794    /// Issue #2806: a reader with filesystem semantics reads a leading `/` as
3795    /// an absolute path, so a path outside the project root resolves to nothing.
3796    #[test]
3797    fn normalize_filesystem_config_path_does_not_read_a_leading_slash_as_root_relative() {
3798        let config_path = PathBuf::from("/project/config/webpack.config.js");
3799        let root = PathBuf::from("/project");
3800
3801        assert_eq!(
3802            normalize_filesystem_config_path("/src/lib", &config_path, &root),
3803            None
3804        );
3805        assert_eq!(
3806            normalize_filesystem_config_path("./src/lib", &config_path, &root),
3807            Some("config/src/lib".to_string())
3808        );
3809        assert_eq!(
3810            normalize_config_path("/src/lib", &config_path, &root),
3811            Some("src/lib".to_string())
3812        );
3813    }
3814
3815    #[test]
3816    fn normalize_config_path_leading_slash_stays_project_relative() {
3817        let config_path = PathBuf::from("/project/vite.config.ts");
3818        let root = PathBuf::from("/project");
3819
3820        assert_eq!(
3821            normalize_config_path("/src\\lib", &config_path, &root),
3822            Some("src/lib".to_string())
3823        );
3824    }
3825
3826    #[test]
3827    fn json_wrapped_in_parens_string() {
3828        let source = r#"({"extends": "@tsconfig/node18/tsconfig.json"})"#;
3829        let val = extract_config_string(source, &js_path(), &["extends"]);
3830        assert_eq!(val, Some("@tsconfig/node18/tsconfig.json".to_string()));
3831    }
3832
3833    #[test]
3834    fn json_wrapped_in_parens_nested_array() {
3835        let source =
3836            r#"({"compilerOptions": {"types": ["node", "jest"]}, "include": ["src/**/*"]})"#;
3837        let types = extract_config_string_array(source, &js_path(), &["compilerOptions", "types"]);
3838        assert_eq!(types, vec!["node", "jest"]);
3839
3840        let include = extract_config_string_array(source, &js_path(), &["include"]);
3841        assert_eq!(include, vec!["src/**/*"]);
3842    }
3843
3844    #[test]
3845    fn json_wrapped_in_parens_object_keys() {
3846        let source = r#"({"plugins": {"autoprefixer": {}, "tailwindcss": {}}})"#;
3847        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
3848        assert_eq!(keys, vec!["autoprefixer", "tailwindcss"]);
3849    }
3850
3851    fn json_path() -> PathBuf {
3852        PathBuf::from("config.json")
3853    }
3854
3855    #[test]
3856    fn json_file_parsed_correctly() {
3857        let source = r#"{"key": "value", "list": ["a", "b"]}"#;
3858        let val = extract_config_string(source, &json_path(), &["key"]);
3859        assert_eq!(val, Some("value".to_string()));
3860
3861        let list = extract_config_string_array(source, &json_path(), &["list"]);
3862        assert_eq!(list, vec!["a", "b"]);
3863    }
3864
3865    #[test]
3866    fn jsonc_file_parsed_correctly() {
3867        let source = r#"{"key": "value"}"#;
3868        let path = PathBuf::from("tsconfig.jsonc");
3869        let val = extract_config_string(source, &path, &["key"]);
3870        assert_eq!(val, Some("value".to_string()));
3871    }
3872
3873    #[test]
3874    fn jsonc_file_ending_in_line_comment_parsed_correctly() {
3875        let source = "{\"key\": \"value\"}\n// trailing comment, no final newline";
3876        let path = PathBuf::from(".oxlintrc.jsonc");
3877        let val = extract_config_string(source, &path, &["key"]);
3878        assert_eq!(val, Some("value".to_string()));
3879    }
3880
3881    #[test]
3882    fn extract_define_config_arrow_function() {
3883        let source = r#"
3884            import { defineConfig } from 'vite';
3885            export default defineConfig(() => ({
3886                test: {
3887                    include: ["**/*.test.ts"]
3888                }
3889            }));
3890        "#;
3891        let include = extract_config_string_array(source, &ts_path(), &["test", "include"]);
3892        assert_eq!(include, vec!["**/*.test.ts"]);
3893    }
3894
3895    /// A block-bodied callback is the common shape for configs that branch on
3896    /// the build mode. A parser that traverses only the concise arrow extracts
3897    /// nothing at all from such a config (issue #2005).
3898    #[test]
3899    fn extract_define_config_block_body_arrow_function() {
3900        let source = r#"
3901            import { defineConfig } from 'vite';
3902            export default defineConfig(({ mode }) => {
3903                const isProduction = mode === 'production';
3904                return {
3905                    test: {
3906                        environment: "jsdom",
3907                        setupFiles: "./tests/setup.ts"
3908                    },
3909                    base: isProduction ? '/app/' : '/'
3910                };
3911            });
3912        "#;
3913        assert_eq!(
3914            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
3915            Some("jsdom")
3916        );
3917        assert_eq!(
3918            extract_config_string(source, &ts_path(), &["test", "setupFiles"]).as_deref(),
3919            Some("./tests/setup.ts")
3920        );
3921    }
3922
3923    #[test]
3924    fn extract_define_config_function_expression() {
3925        let source = r#"
3926            import { defineConfig } from 'vite';
3927            export default defineConfig(function () {
3928                return { test: { environment: "happy-dom" } };
3929            });
3930        "#;
3931        assert_eq!(
3932            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
3933            Some("happy-dom")
3934        );
3935    }
3936
3937    /// A wrapper takes the config first and its own options after it. Scanning
3938    /// the argument list for the first object literal read the options object
3939    /// instead, which is the exact shape the @sentry/nextjs wizard emits.
3940    #[test]
3941    fn wrapper_options_object_does_not_shadow_named_config_arg() {
3942        let source = r#"
3943            const nextConfig = { pageExtensions: ["page.tsx"] };
3944            module.exports = withSentryConfig(nextConfig, { org: "o", project: "p", silent: true });
3945        "#;
3946        assert_eq!(
3947            extract_config_string_array(source, &js_path(), &["pageExtensions"]),
3948            vec!["page.tsx"]
3949        );
3950    }
3951
3952    #[test]
3953    fn wrapper_options_object_does_not_shadow_named_config_arg_esm() {
3954        let source = r#"
3955            const nextConfig = { pageExtensions: ["page.tsx"] };
3956            export default withSentryConfig(nextConfig, { org: "o", project: "p" });
3957        "#;
3958        assert_eq!(
3959            extract_config_string_array(source, &ts_path(), &["pageExtensions"]),
3960            vec!["page.tsx"]
3961        );
3962    }
3963
3964    /// Guards against "prefer an identifier-resolved const over any object
3965    /// literal", which would change which object every plain config reads.
3966    #[test]
3967    fn inline_object_at_argument_zero_still_wins() {
3968        let source = r#"
3969            const unrelated = { pageExtensions: ["wrong.tsx"] };
3970            module.exports = withSentryConfig({ pageExtensions: ["right.tsx"] }, { org: "o" });
3971        "#;
3972        assert_eq!(
3973            extract_config_string_array(source, &js_path(), &["pageExtensions"]),
3974            vec!["right.tsx"]
3975        );
3976    }
3977
3978    /// Vite's documented shape for switching config by command: every branch
3979    /// returns and the callback has no return of its own, so extraction has to
3980    /// descend to find anything at all.
3981    #[test]
3982    fn conditional_config_callback_extracts_branch_return() {
3983        let source = r#"
3984            import { defineConfig } from 'vite';
3985            export default defineConfig(({ command }) => {
3986                if (command === "serve") {
3987                    return { test: { environment: "jsdom" } };
3988                } else {
3989                    return { test: { environment: "node" } };
3990                }
3991            });
3992        "#;
3993        assert_eq!(
3994            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
3995            Some("jsdom"),
3996            "with no top-level return, the first branch in source order wins"
3997        );
3998    }
3999
4000    #[test]
4001    fn try_block_return_is_extracted() {
4002        let source = r#"
4003            export default (() => {
4004                try {
4005                    return { test: { environment: "jsdom" } };
4006                } catch (e) {
4007                    return { test: { environment: "node" } };
4008                }
4009            });
4010        "#;
4011        assert_eq!(
4012            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
4013            Some("jsdom")
4014        );
4015    }
4016
4017    #[test]
4018    fn switch_case_return_is_extracted() {
4019        let source = r#"
4020            import { defineConfig } from 'vite';
4021            export default defineConfig(({ mode }) => {
4022                switch (mode) {
4023                    case "test":
4024                        return { test: { environment: "jsdom" } };
4025                    default:
4026                        return { test: { environment: "node" } };
4027                }
4028            });
4029        "#;
4030        assert_eq!(
4031            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
4032            Some("jsdom")
4033        );
4034    }
4035
4036    /// A guard clause followed by the real return must resolve to the trailing
4037    /// return. Descending into branches before checking this level regressed it:
4038    /// the guard's early return shadowed the actual config.
4039    #[test]
4040    fn guard_clause_does_not_shadow_the_top_level_return() {
4041        let source = r#"
4042            import { defineConfig } from 'vite';
4043            export default defineConfig(({ mode }) => {
4044                if (!mode) {
4045                    return {};
4046                }
4047                return { test: { environment: "jsdom" } };
4048            });
4049        "#;
4050        assert_eq!(
4051            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
4052            Some("jsdom"),
4053            "a return at the callback's own level is the main config"
4054        );
4055    }
4056
4057    /// The same precedence with an else-if chain, where every branch returns and
4058    /// the trailing return is the default config.
4059    #[test]
4060    fn else_if_chain_does_not_shadow_the_top_level_return() {
4061        let source = r#"
4062            import { defineConfig } from 'vite';
4063            export default defineConfig(({ mode }) => {
4064                if (mode === "a") {
4065                    return { base: "/a/" };
4066                } else if (mode === "b") {
4067                    return { base: "/b/" };
4068                }
4069                return { test: { environment: "jsdom" } };
4070            });
4071        "#;
4072        assert_eq!(
4073            extract_config_string(source, &ts_path(), &["test", "environment"]).as_deref(),
4074            Some("jsdom")
4075        );
4076    }
4077
4078    #[test]
4079    fn extract_config_from_default_export_function_declaration() {
4080        let source = r#"
4081            export default function createConfig() {
4082                return {
4083                    clientModules: ["./src/client/global.js"]
4084                };
4085            }
4086        "#;
4087
4088        let client_modules = extract_config_string_array(source, &ts_path(), &["clientModules"]);
4089        assert_eq!(client_modules, vec!["./src/client/global.js"]);
4090    }
4091
4092    #[test]
4093    fn extract_config_from_default_export_async_function_declaration() {
4094        let source = r#"
4095            export default async function createConfigAsync() {
4096                return {
4097                    docs: {
4098                        path: "knowledge"
4099                    }
4100                };
4101            }
4102        "#;
4103
4104        let docs_path = extract_config_string(source, &ts_path(), &["docs", "path"]);
4105        assert_eq!(docs_path, Some("knowledge".to_string()));
4106    }
4107
4108    #[test]
4109    fn extract_config_from_exported_arrow_function_identifier() {
4110        let source = r#"
4111            const config = async () => {
4112                return {
4113                    themes: ["classic"]
4114                };
4115            };
4116
4117            export default config;
4118        "#;
4119
4120        let themes = extract_config_shallow_strings(source, &ts_path(), "themes");
4121        assert_eq!(themes, vec!["classic"]);
4122    }
4123
4124    #[test]
4125    fn module_exports_nested_string() {
4126        let source = r#"
4127            module.exports = {
4128                resolve: {
4129                    alias: {
4130                        "@": "./src"
4131                    }
4132                }
4133            };
4134        "#;
4135        let val = extract_config_string(source, &js_path(), &["resolve", "alias", "@"]);
4136        assert_eq!(val, Some("./src".to_string()));
4137    }
4138
4139    #[test]
4140    fn property_strings_nested_objects() {
4141        let source = r#"
4142            export default {
4143                plugins: {
4144                    group1: { a: "val-a" },
4145                    group2: { b: "val-b" }
4146                }
4147            };
4148        "#;
4149        let values = extract_config_property_strings(source, &js_path(), "plugins");
4150        assert!(values.contains(&"val-a".to_string()));
4151        assert!(values.contains(&"val-b".to_string()));
4152    }
4153
4154    #[test]
4155    fn property_strings_missing_key_returns_empty() {
4156        let source = r#"export default { other: "value" };"#;
4157        let values = extract_config_property_strings(source, &js_path(), "missing");
4158        assert!(values.is_empty());
4159    }
4160
4161    #[test]
4162    fn shallow_strings_tuple_array() {
4163        let source = r#"
4164            module.exports = {
4165                reporters: ["default", ["jest-junit", { outputDirectory: "reports" }]]
4166            };
4167        "#;
4168        let values = extract_config_shallow_strings(source, &js_path(), "reporters");
4169        assert_eq!(values, vec!["default", "jest-junit"]);
4170        assert!(!values.contains(&"reports".to_string()));
4171    }
4172
4173    #[test]
4174    fn shallow_strings_single_string() {
4175        let source = r#"export default { preset: "ts-jest" };"#;
4176        let values = extract_config_shallow_strings(source, &js_path(), "preset");
4177        assert_eq!(values, vec!["ts-jest"]);
4178    }
4179
4180    #[test]
4181    fn shallow_strings_missing_key() {
4182        let source = r#"export default { other: "val" };"#;
4183        let values = extract_config_shallow_strings(source, &js_path(), "missing");
4184        assert!(values.is_empty());
4185    }
4186
4187    #[test]
4188    fn shallow_strings_or_object_property_alias_objects() {
4189        let source = r#"
4190            export default {
4191                jsPlugins: [
4192                    "eslint-plugin-playwright",
4193                    ["eslint-plugin-regexp", { rules: {} }],
4194                    { name: "short", specifier: "eslint-plugin-with-long-name" }
4195                ]
4196            };
4197        "#;
4198        let values = extract_config_shallow_strings_or_object_property(
4199            source,
4200            &ts_path(),
4201            "jsPlugins",
4202            "specifier",
4203        );
4204        assert_eq!(
4205            values,
4206            vec![
4207                "eslint-plugin-playwright",
4208                "eslint-plugin-regexp",
4209                "eslint-plugin-with-long-name"
4210            ]
4211        );
4212    }
4213
4214    #[test]
4215    fn nested_shallow_strings_vitest_reporters() {
4216        let source = r#"
4217            export default {
4218                test: {
4219                    reporters: ["default", "vitest-sonar-reporter"]
4220                }
4221            };
4222        "#;
4223        let values =
4224            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
4225        assert_eq!(values, vec!["default", "vitest-sonar-reporter"]);
4226    }
4227
4228    #[test]
4229    fn nested_shallow_strings_tuple_format() {
4230        let source = r#"
4231            export default {
4232                test: {
4233                    reporters: ["default", ["vitest-sonar-reporter", { outputFile: "report.xml" }]]
4234                }
4235            };
4236        "#;
4237        let values =
4238            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
4239        assert_eq!(values, vec!["default", "vitest-sonar-reporter"]);
4240    }
4241
4242    #[test]
4243    fn nested_shallow_strings_missing_outer() {
4244        let source = r"export default { other: {} };";
4245        let values =
4246            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
4247        assert!(values.is_empty());
4248    }
4249
4250    #[test]
4251    fn nested_shallow_strings_missing_inner() {
4252        let source = r#"export default { test: { include: ["**/*.test.ts"] } };"#;
4253        let values =
4254            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
4255        assert!(values.is_empty());
4256    }
4257
4258    #[test]
4259    fn string_or_array_missing_path() {
4260        let source = r"export default {};";
4261        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
4262        assert!(result.is_empty());
4263    }
4264
4265    #[test]
4266    fn string_or_array_non_string_values() {
4267        let source = r"export default { entry: [42, true] };";
4268        let result = extract_config_string_or_array(source, &js_path(), &["entry"]);
4269        assert!(result.is_empty());
4270    }
4271
4272    #[test]
4273    fn array_nested_extraction() {
4274        let source = r#"
4275            export default defineConfig({
4276                test: {
4277                    projects: [
4278                        {
4279                            test: {
4280                                setupFiles: ["./test/setup-a.ts"]
4281                            }
4282                        },
4283                        {
4284                            test: {
4285                                setupFiles: "./test/setup-b.ts"
4286                            }
4287                        }
4288                    ]
4289                }
4290            });
4291        "#;
4292        let results = extract_config_array_nested_string_or_array(
4293            source,
4294            &ts_path(),
4295            &["test", "projects"],
4296            &["test", "setupFiles"],
4297        );
4298        assert!(results.contains(&"./test/setup-a.ts".to_string()));
4299        assert!(results.contains(&"./test/setup-b.ts".to_string()));
4300    }
4301
4302    #[test]
4303    fn array_nested_empty_when_no_array() {
4304        let source = r#"export default { test: { projects: "not-an-array" } };"#;
4305        let results = extract_config_array_nested_string_or_array(
4306            source,
4307            &js_path(),
4308            &["test", "projects"],
4309            &["test", "setupFiles"],
4310        );
4311        assert!(results.is_empty());
4312    }
4313
4314    #[test]
4315    fn object_nested_extraction() {
4316        let source = r#"{
4317            "projects": {
4318                "app-one": {
4319                    "architect": {
4320                        "build": {
4321                            "options": {
4322                                "styles": ["src/styles.css"]
4323                            }
4324                        }
4325                    }
4326                }
4327            }
4328        }"#;
4329        let results = extract_config_object_nested_string_or_array(
4330            source,
4331            &json_path(),
4332            &["projects"],
4333            &["architect", "build", "options", "styles"],
4334        );
4335        assert_eq!(results, vec!["src/styles.css"]);
4336    }
4337
4338    #[test]
4339    fn array_with_object_input_form_extracted() {
4340        let source = r#"{
4341            "projects": {
4342                "app": {
4343                    "architect": {
4344                        "build": {
4345                            "options": {
4346                                "styles": [
4347                                    "src/styles.scss",
4348                                    { "input": "src/theme.scss", "bundleName": "theme", "inject": false },
4349                                    { "bundleName": "lazy-only" }
4350                                ]
4351                            }
4352                        }
4353                    }
4354                }
4355            }
4356        }"#;
4357        let results = extract_config_object_nested_string_or_array(
4358            source,
4359            &json_path(),
4360            &["projects"],
4361            &["architect", "build", "options", "styles"],
4362        );
4363        assert!(
4364            results.contains(&"src/styles.scss".to_string()),
4365            "string form must still work: {results:?}"
4366        );
4367        assert!(
4368            results.contains(&"src/theme.scss".to_string()),
4369            "object form with `input` must be extracted: {results:?}"
4370        );
4371        assert!(
4372            !results.contains(&"lazy-only".to_string()),
4373            "bundleName must not be misinterpreted as a path: {results:?}"
4374        );
4375        assert!(
4376            !results.contains(&"theme".to_string()),
4377            "bundleName from full object must not leak: {results:?}"
4378        );
4379    }
4380
4381    #[test]
4382    fn object_nested_strings_extraction() {
4383        let source = r#"{
4384            "targets": {
4385                "build": {
4386                    "executor": "@angular/build:application"
4387                },
4388                "test": {
4389                    "executor": "@nx/vite:test"
4390                }
4391            }
4392        }"#;
4393        let results =
4394            extract_config_object_nested_strings(source, &json_path(), &["targets"], &["executor"]);
4395        assert!(results.contains(&"@angular/build:application".to_string()));
4396        assert!(results.contains(&"@nx/vite:test".to_string()));
4397    }
4398
4399    #[test]
4400    fn require_strings_direct_call() {
4401        let source = r"module.exports = { adapter: require('@sveltejs/adapter-node') };";
4402        let deps = extract_config_require_strings(source, &js_path(), "adapter");
4403        assert_eq!(deps, vec!["@sveltejs/adapter-node"]);
4404    }
4405
4406    #[test]
4407    fn require_strings_no_matching_key() {
4408        let source = r"module.exports = { other: require('something') };";
4409        let deps = extract_config_require_strings(source, &js_path(), "plugins");
4410        assert!(deps.is_empty());
4411    }
4412
4413    #[test]
4414    fn extract_imports_no_imports() {
4415        let source = r"export default {};";
4416        let imports = extract_imports(source, &js_path());
4417        assert!(imports.is_empty());
4418    }
4419
4420    #[test]
4421    fn extract_imports_side_effect_import() {
4422        let source = r"
4423            import 'polyfill';
4424            import './local-setup';
4425            export default {};
4426        ";
4427        let imports = extract_imports(source, &js_path());
4428        assert_eq!(imports, vec!["polyfill", "./local-setup"]);
4429    }
4430
4431    #[test]
4432    fn extract_imports_mixed_specifiers() {
4433        let source = r"
4434            import defaultExport from 'module-a';
4435            import { named } from 'module-b';
4436            import * as ns from 'module-c';
4437            export default {};
4438        ";
4439        let imports = extract_imports(source, &js_path());
4440        assert_eq!(imports, vec!["module-a", "module-b", "module-c"]);
4441    }
4442
4443    #[test]
4444    fn template_literal_in_string_or_array() {
4445        let source = r"export default { entry: `./src/index.ts` };";
4446        let result = extract_config_string_or_array(source, &ts_path(), &["entry"]);
4447        assert_eq!(result, vec!["./src/index.ts"]);
4448    }
4449
4450    #[test]
4451    fn template_literal_in_config_string() {
4452        let source = r"export default { testDir: `./tests` };";
4453        let val = extract_config_string(source, &js_path(), &["testDir"]);
4454        assert_eq!(val, Some("./tests".to_string()));
4455    }
4456
4457    #[test]
4458    fn template_literal_command_recovers_static_command_tokens() {
4459        let source = r"
4460            const PORT = 3000;
4461            export default {
4462                webServer: {
4463                    command: `pnpm exec srvx --port ${PORT} --hostname 127.0.0.1`
4464                }
4465            };
4466        ";
4467        let val = extract_config_command(source, &ts_path(), &["webServer", "command"]);
4468        assert_eq!(
4469            val,
4470            Some("pnpm exec srvx --port   --hostname 127.0.0.1".to_string())
4471        );
4472    }
4473
4474    #[test]
4475    fn template_literal_command_skips_dynamic_prefix() {
4476        let source = r"
4477            export default {
4478                webServer: { command: `${serverCommand} && pnpm exec srvx` }
4479            };
4480        ";
4481        let val = extract_config_command(source, &ts_path(), &["webServer", "command"]);
4482        assert!(val.is_none());
4483    }
4484
4485    #[test]
4486    fn template_literal_command_skips_split_static_token() {
4487        let source = r"
4488            export default {
4489                webServer: { command: `pnpm exec sr${part}vx --port 3000` }
4490            };
4491        ";
4492        let val = extract_config_command(source, &ts_path(), &["webServer", "command"]);
4493        assert!(val.is_none());
4494    }
4495
4496    #[test]
4497    fn array_object_command_pairs_recover_template_command() {
4498        let source = r"
4499            const PORT = 3000;
4500            export default {
4501                webServer: [
4502                    {
4503                        command: `pnpm exec srvx --port ${PORT}`,
4504                        cwd: 'apps/web'
4505                    }
4506                ]
4507            };
4508        ";
4509        let pairs = extract_config_array_object_command_pairs(
4510            source,
4511            &ts_path(),
4512            &["webServer"],
4513            "command",
4514            "cwd",
4515        );
4516        assert_eq!(
4517            pairs,
4518            vec![(
4519                "pnpm exec srvx --port  ".to_string(),
4520                Some("apps/web".to_string())
4521            )]
4522        );
4523    }
4524
4525    #[test]
4526    fn nested_string_array_empty_path() {
4527        let source = r#"export default { items: ["a", "b"] };"#;
4528        let result = extract_config_string_array(source, &js_path(), &[]);
4529        assert!(result.is_empty());
4530    }
4531
4532    #[test]
4533    fn nested_string_empty_path() {
4534        let source = r#"export default { key: "val" };"#;
4535        let result = extract_config_string(source, &js_path(), &[]);
4536        assert!(result.is_none());
4537    }
4538
4539    #[test]
4540    fn object_keys_empty_path() {
4541        let source = r"export default { plugins: {} };";
4542        let result = extract_config_object_keys(source, &js_path(), &[]);
4543        assert!(result.is_empty());
4544    }
4545
4546    #[test]
4547    fn no_config_object_returns_empty() {
4548        let source = r"const x = 42;";
4549        let result = extract_config_string(source, &js_path(), &["key"]);
4550        assert!(result.is_none());
4551
4552        let arr = extract_config_string_array(source, &js_path(), &["items"]);
4553        assert!(arr.is_empty());
4554
4555        let keys = extract_config_object_keys(source, &js_path(), &["plugins"]);
4556        assert!(keys.is_empty());
4557    }
4558
4559    #[test]
4560    fn property_with_string_key() {
4561        let source = r#"export default { "string-key": "value" };"#;
4562        let val = extract_config_string(source, &js_path(), &["string-key"]);
4563        assert_eq!(val, Some("value".to_string()));
4564    }
4565
4566    #[test]
4567    fn nested_navigation_through_non_object() {
4568        let source = r#"export default { level1: "not-an-object" };"#;
4569        let val = extract_config_string(source, &js_path(), &["level1", "level2"]);
4570        assert!(val.is_none());
4571    }
4572
4573    #[test]
4574    fn variable_reference_untyped() {
4575        let source = r#"
4576            const config = {
4577                testDir: "./tests"
4578            };
4579            export default config;
4580        "#;
4581        let val = extract_config_string(source, &js_path(), &["testDir"]);
4582        assert_eq!(val, Some("./tests".to_string()));
4583    }
4584
4585    #[test]
4586    fn variable_reference_to_an_exported_const() {
4587        for source in [
4588            r#"
4589            export const config = { testDir: "./tests" };
4590            export default config;
4591            "#,
4592            r#"
4593            export const config = { testDir: "./tests" };
4594            module.exports = config;
4595            "#,
4596        ] {
4597            let val = extract_config_string(source, &js_path(), &["testDir"]);
4598            assert_eq!(val, Some("./tests".to_string()), "source: {source}");
4599        }
4600    }
4601
4602    #[test]
4603    fn variable_reference_with_type_annotation() {
4604        let source = r#"
4605            import type { StorybookConfig } from '@storybook/react-vite';
4606            const config: StorybookConfig = {
4607                addons: ["@storybook/addon-a11y", "@storybook/addon-docs"],
4608                framework: "@storybook/react-vite"
4609            };
4610            export default config;
4611        "#;
4612        let addons = extract_config_shallow_strings(source, &ts_path(), "addons");
4613        assert_eq!(
4614            addons,
4615            vec!["@storybook/addon-a11y", "@storybook/addon-docs"]
4616        );
4617
4618        let framework = extract_config_string(source, &ts_path(), &["framework"]);
4619        assert_eq!(framework, Some("@storybook/react-vite".to_string()));
4620    }
4621
4622    #[test]
4623    fn variable_reference_with_define_config() {
4624        let source = r#"
4625            import { defineConfig } from 'vitest/config';
4626            const config = defineConfig({
4627                test: {
4628                    include: ["**/*.test.ts"]
4629                }
4630            });
4631            export default config;
4632        "#;
4633        let include = extract_config_string_array(source, &ts_path(), &["test", "include"]);
4634        assert_eq!(include, vec!["**/*.test.ts"]);
4635    }
4636
4637    #[test]
4638    fn ts_satisfies_direct_export() {
4639        let source = r#"
4640            export default {
4641                testDir: "./tests"
4642            } satisfies PlaywrightTestConfig;
4643        "#;
4644        let val = extract_config_string(source, &ts_path(), &["testDir"]);
4645        assert_eq!(val, Some("./tests".to_string()));
4646    }
4647
4648    #[test]
4649    fn ts_as_direct_export() {
4650        let source = r#"
4651            export default {
4652                testDir: "./tests"
4653            } as const;
4654        "#;
4655        let val = extract_config_string(source, &ts_path(), &["testDir"]);
4656        assert_eq!(val, Some("./tests".to_string()));
4657    }
4658
4659    // --- issue #811: resolve.alias as imported identifier / spread ---
4660
4661    fn aliases(source: &str) -> Vec<(String, String)> {
4662        extract_config_aliases(source, &js_path(), &["resolve", "alias"])
4663    }
4664
4665    #[test]
4666    fn aliases_inline_object_still_extracted() {
4667        // Regression: the resolver must not change inline-object behavior.
4668        let source = r#"
4669            export default defineConfig({
4670                resolve: { alias: { "@": "./src", utils: "../../utils" } }
4671            });
4672        "#;
4673        let mut got = aliases(source);
4674        got.sort();
4675        assert_eq!(
4676            got,
4677            vec![
4678                ("@".to_string(), "./src".to_string()),
4679                ("utils".to_string(), "../../utils".to_string()),
4680            ]
4681        );
4682    }
4683
4684    #[test]
4685    fn aliases_inline_array_still_extracted() {
4686        let source = r#"
4687            export default defineConfig({
4688                resolve: { alias: [{ find: "@", replacement: "./src" }] }
4689            });
4690        "#;
4691        assert_eq!(
4692            aliases(source),
4693            vec![("@".to_string(), "./src".to_string())]
4694        );
4695    }
4696
4697    #[test]
4698    fn aliases_local_const_array_identifier() {
4699        let source = r#"
4700            const sharedAliases = [{ find: "@", replacement: "./src" }];
4701            export default defineConfig({ resolve: { alias: sharedAliases } });
4702        "#;
4703        assert_eq!(
4704            aliases(source),
4705            vec![("@".to_string(), "./src".to_string())]
4706        );
4707    }
4708
4709    #[test]
4710    fn aliases_local_const_object_identifier() {
4711        let source = r#"
4712            const sharedAliases = { "@": "./src" };
4713            export default defineConfig({ resolve: { alias: sharedAliases } });
4714        "#;
4715        assert_eq!(
4716            aliases(source),
4717            vec![("@".to_string(), "./src".to_string())]
4718        );
4719    }
4720
4721    #[test]
4722    fn aliases_array_spread_of_identifiers_and_inline() {
4723        let source = r##"
4724            const a = [{ find: "@", replacement: "./src" }];
4725            const b = [{ find: "~", replacement: "./lib" }];
4726            export default defineConfig({
4727                resolve: { alias: [...a, ...b, { find: "#", replacement: "./test" }] }
4728            });
4729        "##;
4730        let mut got = aliases(source);
4731        got.sort();
4732        assert_eq!(
4733            got,
4734            vec![
4735                ("#".to_string(), "./test".to_string()),
4736                ("@".to_string(), "./src".to_string()),
4737                ("~".to_string(), "./lib".to_string()),
4738            ]
4739        );
4740    }
4741
4742    #[test]
4743    fn aliases_object_spread_of_identifier_and_inline() {
4744        let source = r#"
4745            const base = { "@": "./src" };
4746            export default defineConfig({
4747                resolve: { alias: { ...base, "~": "./lib" } }
4748            });
4749        "#;
4750        let mut got = aliases(source);
4751        got.sort();
4752        assert_eq!(
4753            got,
4754            vec![
4755                ("@".to_string(), "./src".to_string()),
4756                ("~".to_string(), "./lib".to_string()),
4757            ]
4758        );
4759    }
4760
4761    #[test]
4762    fn aliases_local_const_chained_identifier() {
4763        // `const a = b` indirection resolves through the chain.
4764        let source = r#"
4765            const real = [{ find: "@", replacement: "./src" }];
4766            const alias2 = real;
4767            export default defineConfig({ resolve: { alias: alias2 } });
4768        "#;
4769        assert_eq!(
4770            aliases(source),
4771            vec![("@".to_string(), "./src".to_string())]
4772        );
4773    }
4774
4775    #[test]
4776    fn aliases_imported_named_identifier_from_sibling() {
4777        let dir = tempfile::tempdir().unwrap();
4778        std::fs::write(
4779            dir.path().join("vite.shared.js"),
4780            r#"export const sharedAliases = [
4781                { find: "@", replacement: new URL("./src", import.meta.url).pathname },
4782            ];"#,
4783        )
4784        .unwrap();
4785        let config = dir.path().join("vite.config.js");
4786        let source = r#"
4787            import { defineConfig } from "vite";
4788            import { sharedAliases } from "./vite.shared.js";
4789            export default defineConfig({ resolve: { alias: sharedAliases } });
4790        "#;
4791        let got = extract_config_aliases(source, &config, &["resolve", "alias"]);
4792        assert_eq!(got, vec![("@".to_string(), "./src".to_string())]);
4793    }
4794
4795    #[test]
4796    fn aliases_imported_extensionless_specifier_probed() {
4797        let dir = tempfile::tempdir().unwrap();
4798        std::fs::write(
4799            dir.path().join("aliases.mjs"),
4800            r#"export const sharedAliases = { "@": "./src" };"#,
4801        )
4802        .unwrap();
4803        let config = dir.path().join("vite.config.ts");
4804        let source = r#"
4805            import { sharedAliases } from "./aliases";
4806            export default defineConfig({ resolve: { alias: sharedAliases } });
4807        "#;
4808        let got = extract_config_aliases(source, &config, &["resolve", "alias"]);
4809        assert_eq!(got, vec![("@".to_string(), "./src".to_string())]);
4810    }
4811
4812    #[test]
4813    fn aliases_imported_default_export_from_sibling() {
4814        let dir = tempfile::tempdir().unwrap();
4815        std::fs::write(
4816            dir.path().join("aliases.js"),
4817            r#"export default [{ find: "@", replacement: "./src" }];"#,
4818        )
4819        .unwrap();
4820        let config = dir.path().join("vite.config.js");
4821        let source = r#"
4822            import sharedAliases from "./aliases.js";
4823            export default defineConfig({ resolve: { alias: sharedAliases } });
4824        "#;
4825        let got = extract_config_aliases(source, &config, &["resolve", "alias"]);
4826        assert_eq!(got, vec![("@".to_string(), "./src".to_string())]);
4827    }
4828
4829    #[test]
4830    fn aliases_imported_spread_from_two_siblings() {
4831        let dir = tempfile::tempdir().unwrap();
4832        std::fs::write(
4833            dir.path().join("a.js"),
4834            r#"export const a = [{ find: "@", replacement: "./src" }];"#,
4835        )
4836        .unwrap();
4837        std::fs::write(
4838            dir.path().join("b.js"),
4839            r#"export const b = [{ find: "~", replacement: "./lib" }];"#,
4840        )
4841        .unwrap();
4842        let config = dir.path().join("vite.config.js");
4843        let source = r#"
4844            import { a } from "./a.js";
4845            import { b } from "./b.js";
4846            export default defineConfig({ resolve: { alias: [...a, ...b] } });
4847        "#;
4848        let mut got = extract_config_aliases(source, &config, &["resolve", "alias"]);
4849        got.sort();
4850        assert_eq!(
4851            got,
4852            vec![
4853                ("@".to_string(), "./src".to_string()),
4854                ("~".to_string(), "./lib".to_string()),
4855            ]
4856        );
4857    }
4858
4859    #[test]
4860    fn aliases_import_cycle_terminates() {
4861        // a.js imports from b.js and vice versa; resolution must not hang and
4862        // should still recover the literal pairs present.
4863        let dir = tempfile::tempdir().unwrap();
4864        std::fs::write(
4865            dir.path().join("a.js"),
4866            r#"import { b } from "./b.js";
4867               export const a = [{ find: "@", replacement: "./src" }, ...b];"#,
4868        )
4869        .unwrap();
4870        std::fs::write(
4871            dir.path().join("b.js"),
4872            r#"import { a } from "./a.js";
4873               export const b = [...a];"#,
4874        )
4875        .unwrap();
4876        let config = dir.path().join("vite.config.js");
4877        let source = r#"
4878            import { a } from "./a.js";
4879            export default defineConfig({ resolve: { alias: a } });
4880        "#;
4881        let got = extract_config_aliases(source, &config, &["resolve", "alias"]);
4882        assert_eq!(got, vec![("@".to_string(), "./src".to_string())]);
4883    }
4884
4885    #[test]
4886    fn aliases_non_relative_import_not_followed() {
4887        // A bare-package import is intentionally out of scope: no node_modules
4888        // read for an alias literal.
4889        let source = r#"
4890            import { sharedAliases } from "some-pkg";
4891            export default defineConfig({ resolve: { alias: sharedAliases } });
4892        "#;
4893        let dir = tempfile::tempdir().unwrap();
4894        let config = dir.path().join("vite.config.js");
4895        assert!(extract_config_aliases(source, &config, &["resolve", "alias"]).is_empty());
4896    }
4897
4898    #[test]
4899    fn aliases_object_array_value_takes_first_entry() {
4900        // tsconfig `compilerOptions.paths` maps each key to an ARRAY of targets;
4901        // the resolver must take the first, matching the long-standing non-kinded
4902        // behavior the TypeScript plugin depends on. Regression guard for the
4903        // array-value case that the kinded unification briefly dropped.
4904        let source = r#"
4905            export default {
4906                compilerOptions: { paths: { "@/*": ["./src/*"], "~/*": ["./lib/*", "./vendor/*"] } }
4907            };
4908        "#;
4909        let mut got = extract_config_aliases(source, &js_path(), &["compilerOptions", "paths"]);
4910        got.sort();
4911        assert_eq!(
4912            got,
4913            vec![
4914                ("@/*".to_string(), "./src/*".to_string()),
4915                ("~/*".to_string(), "./lib/*".to_string()),
4916            ]
4917        );
4918    }
4919
4920    #[test]
4921    fn aliases_kinded_preserves_is_bare_through_resolution() {
4922        // The bare-string vs path discriminator must survive identifier + spread
4923        // resolution (the test.alias package-to-package gate depends on it).
4924        let source = r#"
4925            const a = [{ find: "lodash-es", replacement: "lodash" }];
4926            export default defineConfig({
4927                resolve: { alias: [...a, { find: "@", replacement: "./src" }] }
4928            });
4929        "#;
4930        let mut got = extract_config_aliases_kinded(source, &js_path(), &["resolve", "alias"]);
4931        got.sort();
4932        assert_eq!(
4933            got,
4934            vec![
4935                ("@".to_string(), "./src".to_string(), false),
4936                ("lodash-es".to_string(), "lodash".to_string(), true),
4937            ]
4938        );
4939    }
4940
4941    #[test]
4942    fn aliases_kinded_preserves_is_bare_through_imported_spread() {
4943        let dir = tempfile::tempdir().unwrap();
4944        std::fs::write(
4945            dir.path().join("aliases.js"),
4946            r#"export const packageAliases = [{ find: "lodash-es", replacement: "lodash" }];"#,
4947        )
4948        .unwrap();
4949        let config = dir.path().join("vite.config.js");
4950        let source = r#"
4951            import { packageAliases } from "./aliases.js";
4952            export default defineConfig({
4953                resolve: { alias: [...packageAliases, { find: "@", replacement: "./src" }] }
4954            });
4955        "#;
4956        let mut got = extract_config_aliases_kinded(source, &config, &["resolve", "alias"]);
4957        got.sort();
4958        assert_eq!(
4959            got,
4960            vec![
4961                ("@".to_string(), "./src".to_string(), false),
4962                ("lodash-es".to_string(), "lodash".to_string(), true),
4963            ]
4964        );
4965    }
4966
4967    // --- extract_config_command ---
4968
4969    #[test]
4970    fn extract_command_string_literal() {
4971        let source = r#"export default { start: "node server.js" };"#;
4972        let val = extract_config_command(source, &js_path(), &["start"]);
4973        assert_eq!(val, Some("node server.js".to_string()));
4974    }
4975
4976    #[test]
4977    fn extract_command_nested_path() {
4978        let source = r#"
4979            export default {
4980                scripts: {
4981                    dev: "vite dev"
4982                }
4983            };
4984        "#;
4985        let val = extract_config_command(source, &js_path(), &["scripts", "dev"]);
4986        assert_eq!(val, Some("vite dev".to_string()));
4987    }
4988
4989    #[test]
4990    fn extract_command_missing_key_returns_none() {
4991        let source = r#"export default { other: "val" };"#;
4992        let val = extract_config_command(source, &js_path(), &["start"]);
4993        assert!(val.is_none());
4994    }
4995
4996    #[test]
4997    fn extract_command_ts_as_expression() {
4998        let source = r#"export default { start: "node server.js" as string };"#;
4999        let val = extract_config_command(source, &ts_path(), &["start"]);
5000        assert_eq!(val, Some("node server.js".to_string()));
5001    }
5002
5003    #[test]
5004    fn extract_command_ts_satisfies_expression() {
5005        let source = r#"export default { start: "node server.js" satisfies string };"#;
5006        let val = extract_config_command(source, &ts_path(), &["start"]);
5007        assert_eq!(val, Some("node server.js".to_string()));
5008    }
5009
5010    #[test]
5011    fn extract_command_parenthesized_expression() {
5012        let source = r#"export default { start: ("node server.js") };"#;
5013        let val = extract_config_command(source, &js_path(), &["start"]);
5014        assert_eq!(val, Some("node server.js".to_string()));
5015    }
5016
5017    #[test]
5018    fn extract_command_empty_path_returns_none() {
5019        let source = r#"export default { start: "node server.js" };"#;
5020        let val = extract_config_command(source, &js_path(), &[]);
5021        assert!(val.is_none());
5022    }
5023
5024    // --- is_disabled_expression and extract_config_truthy_bool_or_object ---
5025
5026    #[test]
5027    fn truthy_bool_or_object_with_true_value() {
5028        let source = r"export default { typescript: true };";
5029        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5030        assert!(result);
5031    }
5032
5033    #[test]
5034    fn truthy_bool_or_object_with_false_value() {
5035        let source = r"export default { typescript: false };";
5036        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5037        assert!(!result);
5038    }
5039
5040    #[test]
5041    fn truthy_bool_or_object_with_object_value() {
5042        let source = r#"export default { typescript: { reactDocgen: "react-docgen" } };"#;
5043        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5044        assert!(result);
5045    }
5046
5047    #[test]
5048    fn truthy_bool_or_object_missing_key_returns_false() {
5049        let source = r"export default { other: true };";
5050        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5051        assert!(!result);
5052    }
5053
5054    #[test]
5055    fn truthy_bool_or_object_with_string_value_returns_false() {
5056        // A string is neither bool true nor object, so the else arm returns false.
5057        let source = r#"export default { typescript: "yes" };"#;
5058        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5059        assert!(!result);
5060    }
5061
5062    #[test]
5063    fn truthy_bool_or_object_ts_satisfies_wrapper() {
5064        let source = r"export default { typescript: (true satisfies boolean) };";
5065        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5066        assert!(result);
5067    }
5068
5069    #[test]
5070    fn truthy_bool_or_object_ts_as_wrapper() {
5071        let source = r"export default { typescript: (true as boolean) };";
5072        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5073        assert!(result);
5074    }
5075
5076    #[test]
5077    fn truthy_bool_or_object_parenthesized_wrapper() {
5078        let source = r"export default { typescript: (true) };";
5079        let result = extract_config_truthy_bool_or_object(source, &ts_path(), &["typescript"]);
5080        assert!(result);
5081    }
5082
5083    // --- object_expression helper: exercises via static dir entries property_string ---
5084    // property_object calls object_expression; it is also exercised through
5085    // extract_object_from_expression, which handles TS wrappers at the top-export level.
5086    // The ts_satisfies_direct_export / ts_as_direct_export tests already cover those arms.
5087
5088    #[test]
5089    fn static_dir_entries_object_form_exercises_property_string() {
5090        // property_string (which calls property_expr then expression_to_string) is used
5091        // for the `from` and `to` keys in extract_config_static_dir_entries.
5092        let source = r#"
5093            export default {
5094                staticDirs: [
5095                    { from: "./media", to: "/assets" }
5096                ]
5097            };
5098        "#;
5099        let entries = extract_config_static_dir_entries(source, &ts_path(), &["staticDirs"]);
5100        assert_eq!(
5101            entries,
5102            vec![("./media".to_string(), Some("/assets".to_string()))]
5103        );
5104    }
5105
5106    // --- expression_to_path_values (array form) ---
5107
5108    #[test]
5109    fn expression_to_path_values_array_form_via_config_path() {
5110        // The extract_config_path helper uses expression_to_path; path_values
5111        // is exercised when the value is an array via extract_config_string_or_array.
5112        let source = r#"export default { entries: ["./src/a.ts", "./src/b.ts"] };"#;
5113        let result = extract_config_string_or_array(source, &js_path(), &["entries"]);
5114        assert_eq!(result, vec!["./src/a.ts", "./src/b.ts"]);
5115    }
5116
5117    // --- extract_config_array_nested_aliases_kinded ---
5118
5119    #[test]
5120    fn array_nested_aliases_object_form() {
5121        let source = r#"
5122            export default {
5123                test: {
5124                    projects: [
5125                        {
5126                            resolve: {
5127                                alias: { "@": "./src" }
5128                            }
5129                        }
5130                    ]
5131                }
5132            };
5133        "#;
5134        let aliases = extract_config_array_nested_aliases_kinded(
5135            source,
5136            &ts_path(),
5137            &["test", "projects"],
5138            &["resolve", "alias"],
5139        );
5140        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string(), false)]);
5141    }
5142
5143    #[test]
5144    fn array_nested_aliases_empty_when_path_is_not_array() {
5145        let source = r#"export default { test: { projects: "not-an-array" } };"#;
5146        let aliases = extract_config_array_nested_aliases_kinded(
5147            source,
5148            &ts_path(),
5149            &["test", "projects"],
5150            &["resolve", "alias"],
5151        );
5152        assert!(aliases.is_empty());
5153    }
5154
5155    #[test]
5156    fn array_nested_aliases_kinded_tracks_is_bare() {
5157        let source = r#"
5158            export default {
5159                projects: [
5160                    {
5161                        resolve: {
5162                            alias: [
5163                                { find: "lodash-es", replacement: "lodash" },
5164                                { find: "@", replacement: "./src" }
5165                            ]
5166                        }
5167                    }
5168                ]
5169            };
5170        "#;
5171        let mut aliases = extract_config_array_nested_aliases_kinded(
5172            source,
5173            &ts_path(),
5174            &["projects"],
5175            &["resolve", "alias"],
5176        );
5177        aliases.sort();
5178        assert_eq!(
5179            aliases,
5180            vec![
5181                ("@".to_string(), "./src".to_string(), false),
5182                ("lodash-es".to_string(), "lodash".to_string(), true),
5183            ]
5184        );
5185    }
5186
5187    // --- extract_default_export_array_aliases_kinded ---
5188
5189    #[test]
5190    fn default_export_array_aliases_kinded_extracts_from_workspace_config() {
5191        let source = r#"
5192            export default [
5193                {
5194                    resolve: {
5195                        alias: { "@": "./src" }
5196                    }
5197                },
5198                {
5199                    resolve: {
5200                        alias: [{ find: "~", replacement: "./lib" }]
5201                    }
5202                }
5203            ];
5204        "#;
5205        let mut aliases =
5206            extract_default_export_array_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5207        aliases.sort();
5208        assert_eq!(
5209            aliases,
5210            vec![
5211                ("@".to_string(), "./src".to_string(), false),
5212                ("~".to_string(), "./lib".to_string(), false),
5213            ]
5214        );
5215    }
5216
5217    #[test]
5218    fn default_export_array_aliases_kinded_define_workspace_wrapper() {
5219        let source = r#"
5220            export default defineWorkspace([
5221                {
5222                    resolve: { alias: { "@": "./src" } }
5223                }
5224            ]);
5225        "#;
5226        let aliases =
5227            extract_default_export_array_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5228        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string(), false)]);
5229    }
5230
5231    #[test]
5232    fn default_export_array_aliases_kinded_empty_when_no_alias_path() {
5233        let source = r#"
5234            export default [
5235                { test: { include: ["**/*.test.ts"] } }
5236            ];
5237        "#;
5238        let aliases =
5239            extract_default_export_array_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5240        assert!(aliases.is_empty());
5241    }
5242
5243    // --- config_default_export_unreachable ---
5244
5245    #[test]
5246    fn config_default_export_unreachable_when_no_export() {
5247        let source = r"const x = 42;";
5248        assert!(config_default_export_unreachable(source, &js_path()));
5249    }
5250
5251    #[test]
5252    fn config_default_export_unreachable_false_for_object_export() {
5253        let source = r#"export default { key: "value" };"#;
5254        assert!(!config_default_export_unreachable(source, &js_path()));
5255    }
5256
5257    #[test]
5258    fn config_default_export_unreachable_false_for_array_export() {
5259        let source = r#"export default ["a", "b"];"#;
5260        assert!(!config_default_export_unreachable(source, &js_path()));
5261    }
5262
5263    #[test]
5264    fn config_default_export_unreachable_true_for_function_without_return_object() {
5265        // A function that returns a number is unreachable.
5266        let source = r"export default function config() { return 42; }";
5267        assert!(config_default_export_unreachable(source, &js_path()));
5268    }
5269
5270    // --- extract_config_static_dir_entries ---
5271
5272    #[test]
5273    fn static_dir_entries_string_and_object_form() {
5274        let source = r#"
5275            export default {
5276                staticDirs: [
5277                    "./public",
5278                    { from: "../assets", to: "/static" }
5279                ]
5280            };
5281        "#;
5282        let entries = extract_config_static_dir_entries(source, &ts_path(), &["staticDirs"]);
5283        assert_eq!(
5284            entries,
5285            vec![
5286                ("./public".to_string(), None),
5287                ("../assets".to_string(), Some("/static".to_string())),
5288            ]
5289        );
5290    }
5291
5292    #[test]
5293    fn static_dir_entries_object_without_to() {
5294        let source = r#"
5295            export default {
5296                staticDirs: [
5297                    { from: "./media" }
5298                ]
5299            };
5300        "#;
5301        let entries = extract_config_static_dir_entries(source, &ts_path(), &["staticDirs"]);
5302        assert_eq!(entries, vec![("./media".to_string(), None)]);
5303    }
5304
5305    #[test]
5306    fn static_dir_entries_object_missing_from_skipped() {
5307        // Objects without a `from` key are silently skipped.
5308        let source = r#"
5309            export default {
5310                staticDirs: [
5311                    { to: "/target" },
5312                    "./public"
5313                ]
5314            };
5315        "#;
5316        let entries = extract_config_static_dir_entries(source, &ts_path(), &["staticDirs"]);
5317        assert_eq!(entries, vec![("./public".to_string(), None)]);
5318    }
5319
5320    #[test]
5321    fn static_dir_entries_empty_when_not_array() {
5322        let source = r#"export default { staticDirs: "./public" };"#;
5323        let entries = extract_config_static_dir_entries(source, &ts_path(), &["staticDirs"]);
5324        assert!(entries.is_empty());
5325    }
5326
5327    // --- alias object and array forms ---
5328
5329    #[test]
5330    fn aliases_array_form_missing_find_or_replacement_skipped() {
5331        // An element missing "find" or "replacement" is silently skipped.
5332        let source = r#"
5333            export default {
5334                resolve: {
5335                    alias: [
5336                        { replacement: "./src" },
5337                        { find: "@" },
5338                        { find: "~", replacement: "./lib" }
5339                    ]
5340                }
5341            };
5342        "#;
5343        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
5344        assert_eq!(aliases, vec![("~".to_string(), "./lib".to_string())]);
5345    }
5346
5347    #[test]
5348    fn aliases_object_form_computed_key_skipped() {
5349        // Computed keys (expression keys) are not statically recoverable.
5350        let source = r#"
5351            const k = "@";
5352            export default {
5353                resolve: {
5354                    alias: {
5355                        [k]: "./src",
5356                        "~": "./lib"
5357                    }
5358                }
5359            };
5360        "#;
5361        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
5362        // Only the literal key "~" survives; computed [k] is dropped.
5363        assert_eq!(aliases, vec![("~".to_string(), "./lib".to_string())]);
5364    }
5365
5366    #[test]
5367    fn aliases_kinded_array_form_path_replacement_is_not_bare() {
5368        let source = r#"
5369            export default {
5370                resolve: {
5371                    alias: [{ find: "@", replacement: "./src" }]
5372                }
5373            };
5374        "#;
5375        let aliases = extract_config_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5376        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string(), false)]);
5377    }
5378
5379    #[test]
5380    fn aliases_kinded_object_form_bare_and_path_discrimination() {
5381        let source = r#"
5382            export default {
5383                resolve: {
5384                    alias: {
5385                        "lodash-es": "lodash",
5386                        "@": "./src"
5387                    }
5388                }
5389            };
5390        "#;
5391        let mut aliases = extract_config_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5392        aliases.sort();
5393        assert_eq!(
5394            aliases,
5395            vec![
5396                ("@".to_string(), "./src".to_string(), false),
5397                ("lodash-es".to_string(), "lodash".to_string(), true),
5398            ]
5399        );
5400    }
5401
5402    #[test]
5403    fn aliases_kinded_parent_relative_replacement_is_not_bare() {
5404        let source = r#"
5405            export default {
5406                resolve: { alias: { "@": "../shared/src" } }
5407            };
5408        "#;
5409        let aliases = extract_config_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5410        assert_eq!(
5411            aliases,
5412            vec![("@".to_string(), "../shared/src".to_string(), false)]
5413        );
5414    }
5415
5416    #[test]
5417    fn aliases_kinded_absolute_replacement_is_not_bare() {
5418        let source = r#"
5419            export default {
5420                resolve: { alias: { "@": "/absolute/path" } }
5421            };
5422        "#;
5423        let aliases = extract_config_aliases_kinded(source, &ts_path(), &["resolve", "alias"]);
5424        assert_eq!(
5425            aliases,
5426            vec![("@".to_string(), "/absolute/path".to_string(), false)]
5427        );
5428    }
5429
5430    // --- find_default_export_array / array_from_expression wrappers ---
5431
5432    #[test]
5433    fn default_export_array_ts_as_wrapper() {
5434        // array_from_expression must unwrap TSAsExpression.
5435        let source = r"export default [] as string[];";
5436        assert!(!config_default_export_unreachable(source, &js_path()));
5437    }
5438
5439    #[test]
5440    fn default_export_array_ts_satisfies_wrapper() {
5441        let source = r"export default [] satisfies string[];";
5442        assert!(!config_default_export_unreachable(source, &ts_path()));
5443    }
5444
5445    #[test]
5446    fn default_export_array_define_config_call_wrapper() {
5447        let source = r#"export default defineConfig(["**/*.test.ts"]);"#;
5448        assert!(!config_default_export_unreachable(source, &ts_path()));
5449    }
5450
5451    // --- collect_shallow_string_values: object-property branches ---
5452
5453    #[test]
5454    fn shallow_strings_object_with_string_values() {
5455        // The ObjectExpression arm of collect_shallow_string_values emits string values.
5456        let source = r#"
5457            export default {
5458                plugins: {
5459                    autoprefixer: "autoprefixer",
5460                    tailwindcss: "tailwindcss"
5461                }
5462            };
5463        "#;
5464        let vals = extract_config_shallow_strings(source, &js_path(), "plugins");
5465        assert!(vals.contains(&"autoprefixer".to_string()));
5466        assert!(vals.contains(&"tailwindcss".to_string()));
5467    }
5468
5469    #[test]
5470    fn shallow_strings_object_with_sub_array_first_element() {
5471        // An object property whose value is an array emits the first string element.
5472        let source = r#"
5473            export default {
5474                reporters: {
5475                    main: ["jest-junit", { outputFile: "report.xml" }],
5476                    alt: ["html-reporter"]
5477                }
5478            };
5479        "#;
5480        let vals = extract_config_shallow_strings(source, &js_path(), "reporters");
5481        assert!(vals.contains(&"jest-junit".to_string()));
5482        assert!(vals.contains(&"html-reporter".to_string()));
5483    }
5484
5485    // --- collect_shallow_string_or_object_property_values ---
5486
5487    #[test]
5488    fn shallow_strings_or_object_property_non_array_single_string() {
5489        // When the top-level value is a plain string (not an array), it is returned directly.
5490        let source = r#"export default { jsPlugins: "eslint-plugin-foo" };"#;
5491        let vals = extract_config_shallow_strings_or_object_property(
5492            source,
5493            &ts_path(),
5494            "jsPlugins",
5495            "specifier",
5496        );
5497        assert_eq!(vals, vec!["eslint-plugin-foo"]);
5498    }
5499
5500    #[test]
5501    fn shallow_strings_or_object_property_ts_satisfies_array_element() {
5502        // shallow_string_or_object_property unwraps TSSatisfiesExpression.
5503        let source = r#"
5504            export default {
5505                jsPlugins: [
5506                    ("eslint-plugin-a" satisfies string)
5507                ]
5508            };
5509        "#;
5510        let vals = extract_config_shallow_strings_or_object_property(
5511            source,
5512            &ts_path(),
5513            "jsPlugins",
5514            "specifier",
5515        );
5516        assert_eq!(vals, vec!["eslint-plugin-a"]);
5517    }
5518
5519    #[test]
5520    fn shallow_strings_or_object_property_ts_as_array_element() {
5521        let source = r#"
5522            export default {
5523                jsPlugins: [
5524                    ("eslint-plugin-b" as string)
5525                ]
5526            };
5527        "#;
5528        let vals = extract_config_shallow_strings_or_object_property(
5529            source,
5530            &ts_path(),
5531            "jsPlugins",
5532            "specifier",
5533        );
5534        assert_eq!(vals, vec!["eslint-plugin-b"]);
5535    }
5536
5537    #[test]
5538    fn shallow_strings_or_object_property_sub_array_first_element_string() {
5539        // A sub-array in jsPlugins returns the first string element.
5540        let source = r#"
5541            export default {
5542                jsPlugins: [
5543                    ["eslint-plugin-tuple-pkg", { options: true }]
5544                ]
5545            };
5546        "#;
5547        let vals = extract_config_shallow_strings_or_object_property(
5548            source,
5549            &ts_path(),
5550            "jsPlugins",
5551            "specifier",
5552        );
5553        assert_eq!(vals, vec!["eslint-plugin-tuple-pkg"]);
5554    }
5555
5556    // --- extract_config_array_object_command_pairs ---
5557
5558    #[test]
5559    fn array_object_command_pairs_basic() {
5560        let source = r#"
5561            export default {
5562                webServer: [
5563                    { command: "node server.js", cwd: "packages/api" },
5564                    { command: "vite dev" }
5565                ]
5566            };
5567        "#;
5568        let pairs = extract_config_array_object_command_pairs(
5569            source,
5570            &ts_path(),
5571            &["webServer"],
5572            "command",
5573            "cwd",
5574        );
5575        assert_eq!(
5576            pairs,
5577            vec![
5578                (
5579                    "node server.js".to_string(),
5580                    Some("packages/api".to_string())
5581                ),
5582                ("vite dev".to_string(), None),
5583            ]
5584        );
5585    }
5586
5587    #[test]
5588    fn array_object_command_pairs_skips_missing_command() {
5589        let source = r#"
5590            export default {
5591                webServer: [
5592                    { cwd: "packages/api" },
5593                    { command: "vite dev", cwd: "apps/web" }
5594                ]
5595            };
5596        "#;
5597        let pairs = extract_config_array_object_command_pairs(
5598            source,
5599            &ts_path(),
5600            &["webServer"],
5601            "command",
5602            "cwd",
5603        );
5604        assert_eq!(
5605            pairs,
5606            vec![("vite dev".to_string(), Some("apps/web".to_string()))]
5607        );
5608    }
5609
5610    #[test]
5611    fn array_object_command_pairs_empty_when_not_array() {
5612        let source = r#"export default { webServer: { command: "vite dev" } };"#;
5613        let pairs = extract_config_array_object_command_pairs(
5614            source,
5615            &ts_path(),
5616            &["webServer"],
5617            "command",
5618            "cwd",
5619        );
5620        assert!(pairs.is_empty());
5621    }
5622
5623    // --- normalize_config_path edge cases ---
5624
5625    #[test]
5626    fn normalize_config_path_empty_string_returns_none() {
5627        let config_path = PathBuf::from("/project/vite.config.ts");
5628        let root = PathBuf::from("/project");
5629        assert_eq!(normalize_config_path("", &config_path, &root), None);
5630    }
5631
5632    #[test]
5633    fn normalize_config_path_escapes_to_above_root_returns_none() {
5634        let config_path = PathBuf::from("/project/vite.config.ts");
5635        let root = PathBuf::from("/project");
5636        // "../../etc" normalizes to the parent of root, which fails the strip_prefix.
5637        assert_eq!(
5638            normalize_config_path("../../etc", &config_path, &root),
5639            None
5640        );
5641    }
5642
5643    #[test]
5644    fn normalize_config_path_dot_slash_resolves_relative_to_config_dir() {
5645        let config_path = PathBuf::from("/project/packages/app/vite.config.ts");
5646        let root = PathBuf::from("/project");
5647        assert_eq!(
5648            normalize_config_path("./src", &config_path, &root),
5649            Some("packages/app/src".to_string())
5650        );
5651    }
5652
5653    // --- JSON config parsing edge cases ---
5654
5655    #[test]
5656    fn json_config_array_of_arrays_via_shallow_strings() {
5657        // JSON with nested plugin tuples is parsed via the parenthesis-wrap path.
5658        let source = r#"{"reporters": ["default", ["jest-junit", {}]]}"#;
5659        let vals = extract_config_shallow_strings(source, &json_path(), "reporters");
5660        assert_eq!(vals, vec!["default", "jest-junit"]);
5661    }
5662
5663    // --- extract_config_path ---
5664
5665    #[test]
5666    fn extract_config_path_string_literal() {
5667        let source = r#"export default { outDir: "./dist" };"#;
5668        let path = extract_config_path(source, &js_path(), &["outDir"]);
5669        assert_eq!(
5670            path.map(|p| p.to_string_lossy().replace('\\', "/")),
5671            Some("./dist".to_string())
5672        );
5673    }
5674
5675    #[test]
5676    fn extract_config_path_with_resolve_call() {
5677        let source = r#"
5678            import { resolve } from "node:path";
5679            export default { outDir: resolve(__dirname, "dist") };
5680        "#;
5681        let path = extract_config_path(source, &js_path(), &["outDir"]);
5682        assert_eq!(
5683            path.map(|p| p.to_string_lossy().replace('\\', "/")),
5684            Some("dist".to_string())
5685        );
5686    }
5687
5688    #[test]
5689    fn extract_config_path_missing_key_returns_none() {
5690        let source = r#"export default { other: "val" };"#;
5691        let path = extract_config_path(source, &js_path(), &["outDir"]);
5692        assert!(path.is_none());
5693    }
5694
5695    // --- extract_imports_and_requires ---
5696
5697    #[test]
5698    fn extract_imports_and_requires_both_forms() {
5699        let source = r"
5700            import foo from 'foo-pkg';
5701            require('bar-pkg');
5702            export default {};
5703        ";
5704        let sources = extract_imports_and_requires(source, &js_path());
5705        assert!(sources.contains(&"foo-pkg".to_string()));
5706        assert!(sources.contains(&"bar-pkg".to_string()));
5707    }
5708
5709    #[test]
5710    fn extract_imports_and_requires_skips_non_require_calls() {
5711        let source = r"
5712            import foo from 'foo-pkg';
5713            someOtherCall('bar-pkg');
5714            export default {};
5715        ";
5716        let sources = extract_imports_and_requires(source, &js_path());
5717        assert_eq!(sources, vec!["foo-pkg"]);
5718    }
5719
5720    // --- extract_config_nested_shallow_strings: non-object nested value ---
5721
5722    #[test]
5723    fn nested_shallow_strings_non_object_nested_returns_empty() {
5724        // When the outer path points to a non-object, it returns empty.
5725        let source = r#"export default { test: "not-an-object" };"#;
5726        let vals =
5727            extract_config_nested_shallow_strings(source, &js_path(), &["test"], "reporters");
5728        assert!(vals.is_empty());
5729    }
5730
5731    // --- vite_react_babel_dependencies with namespace import ---
5732
5733    #[test]
5734    fn vite_react_babel_dependencies_namespace_import() {
5735        let source = r#"
5736            import * as react from "@vitejs/plugin-react";
5737
5738            export default defineConfig({
5739                plugins: [
5740                    react.default({
5741                        babel: {
5742                            plugins: ["babel-plugin-ns"],
5743                        },
5744                    }),
5745                ],
5746            });
5747        "#;
5748        let deps = extract_vite_plugin_option_dependencies(source, &ts_path());
5749        assert_eq!(deps, vec!["babel-plugin-ns".to_string()]);
5750    }
5751
5752    // --- collect_all_string_values nested object and array recursion ---
5753
5754    #[test]
5755    fn property_strings_deeply_nested_object_values() {
5756        // collect_all_string_values recurses into nested objects and arrays.
5757        let source = r#"
5758            export default {
5759                settings: {
5760                    a: "val-a",
5761                    b: {
5762                        c: "val-c",
5763                        d: ["val-d1", "val-d2"]
5764                    }
5765                }
5766            };
5767        "#;
5768        let values = extract_config_property_strings(source, &js_path(), "settings");
5769        assert!(values.contains(&"val-a".to_string()));
5770        assert!(values.contains(&"val-c".to_string()));
5771        assert!(values.contains(&"val-d1".to_string()));
5772        assert!(values.contains(&"val-d2".to_string()));
5773    }
5774
5775    // --- find_variable_init_expression: export const form ---
5776
5777    #[test]
5778    fn aliases_exported_const_form_resolves() {
5779        // find_variable_init_expression must handle `export const NAME = ...`.
5780        let source = r#"
5781            export const sharedAliases = { "@": "./src" };
5782            export default defineConfig({ resolve: { alias: sharedAliases } });
5783        "#;
5784        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
5785        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string())]);
5786    }
5787
5788    // --- resolve_sibling_module: index file probe ---
5789
5790    #[test]
5791    fn aliases_imported_from_sibling_directory_index_file() {
5792        // resolve_sibling_module probes <specifier>/index.<ext> when direct
5793        // path and extension-suffixed paths do not exist.
5794        let dir = tempfile::tempdir().unwrap();
5795        let aliases_dir = dir.path().join("aliases");
5796        std::fs::create_dir_all(&aliases_dir).unwrap();
5797        std::fs::write(
5798            aliases_dir.join("index.js"),
5799            r#"export const aliases = [{ find: "@", replacement: "./src" }];"#,
5800        )
5801        .unwrap();
5802        let config = dir.path().join("vite.config.js");
5803        let source = r#"
5804            import { aliases } from "./aliases";
5805            export default defineConfig({ resolve: { alias: aliases } });
5806        "#;
5807        let got = extract_config_aliases(source, &config, &["resolve", "alias"]);
5808        assert_eq!(got, vec![("@".to_string(), "./src".to_string())]);
5809    }
5810
5811    // --- aliases max depth guard ---
5812
5813    #[test]
5814    fn aliases_depth_limit_terminates_deep_chain() {
5815        // A chain of more than MAX_ALIAS_RESOLVE_DEPTH identifiers terminates
5816        // without panic or infinite loop. We verify it does not crash.
5817        let source = r#"
5818            const a9 = [{ find: "@", replacement: "./src" }];
5819            const a8 = a9;
5820            const a7 = a8;
5821            const a6 = a7;
5822            const a5 = a6;
5823            const a4 = a5;
5824            const a3 = a4;
5825            const a2 = a3;
5826            const a1 = a2;
5827            export default defineConfig({ resolve: { alias: a1 } });
5828        "#;
5829        // At MAX_ALIAS_RESOLVE_DEPTH (8), resolution stops before reaching the literal.
5830        let got = extract_config_aliases(source, &js_path(), &["resolve", "alias"]);
5831        let _ = got; // empty or non-empty; both are valid, no panic is the assertion.
5832    }
5833
5834    // --- expression_to_path_string: new URL / fileURLToPath ---
5835
5836    #[test]
5837    fn extract_aliases_file_url_to_path_new_url() {
5838        // expression_to_path_string resolves new URL("./src", import.meta.url).
5839        let source = r#"
5840            import { fileURLToPath, URL } from 'node:url';
5841            export default {
5842                resolve: {
5843                    alias: {
5844                        "@": fileURLToPath(new URL("./src", import.meta.url))
5845                    }
5846                }
5847            };
5848        "#;
5849        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
5850        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string())]);
5851    }
5852
5853    #[test]
5854    fn extract_path_via_new_url_pathname_member() {
5855        // The .pathname member of new URL(...) is a path-string form.
5856        let source = r#"
5857            export default {
5858                resolve: {
5859                    alias: {
5860                        "@": new URL("./src", import.meta.url).pathname
5861                    }
5862                }
5863            };
5864        "#;
5865        let aliases = extract_config_aliases(source, &ts_path(), &["resolve", "alias"]);
5866        assert_eq!(aliases, vec![("@".to_string(), "./src".to_string())]);
5867    }
5868
5869    // --- is_disabled_expression: null literal ---
5870
5871    #[test]
5872    fn truthy_bool_or_object_null_literal_returns_false() {
5873        // null is a disabled expression and therefore not truthy.
5874        let source = r"export default { typescript: null };";
5875        let result = extract_config_truthy_bool_or_object(source, &js_path(), &["typescript"]);
5876        assert!(!result);
5877    }
5878
5879    // --- expression_to_string_array: non-array form returns empty ---
5880
5881    #[test]
5882    fn string_array_non_array_value_returns_empty() {
5883        let source = r#"export default { items: "not-an-array" };"#;
5884        let result = extract_config_string_array(source, &js_path(), &["items"]);
5885        assert!(result.is_empty());
5886    }
5887
5888    // --- extract_config_object_nested edge cases ---
5889
5890    #[test]
5891    fn object_nested_empty_when_inner_value_is_not_object() {
5892        // extract_config_object_nested only processes properties whose value is an object.
5893        let source = r#"export default { targets: { build: "not-an-object" } };"#;
5894        let results =
5895            extract_config_object_nested_strings(source, &json_path(), &["targets"], &["executor"]);
5896        assert!(results.is_empty());
5897    }
5898
5899    // --- extract_config_array_nested_string_or_array: missing inner path ---
5900
5901    #[test]
5902    fn array_nested_string_or_array_missing_inner_path_returns_empty() {
5903        let source = r#"
5904            export default {
5905                test: {
5906                    projects: [
5907                        { test: { include: ["**/*.test.ts"] } }
5908                    ]
5909                }
5910            };
5911        "#;
5912        let results = extract_config_array_nested_string_or_array(
5913            source,
5914            &ts_path(),
5915            &["test", "projects"],
5916            &["test", "setupFiles"],
5917        );
5918        assert!(results.is_empty());
5919    }
5920
5921    #[test]
5922    fn wrapped_named_const_default_export_resolves() {
5923        // `export default withMDX(nextConfig)` (official @next/mdx idiom): the
5924        // config is passed as a named const to a wrapper call. Regression #1642.
5925        let source = r#"
5926            import createMDX from "@next/mdx";
5927            const nextConfig = { pageExtensions: ["ts", "tsx", "md", "mdx"] };
5928            const withMDX = createMDX({});
5929            export default withMDX(nextConfig);
5930        "#;
5931        let exts = extract_config_string_array(source, &ts_path(), &["pageExtensions"]);
5932        assert_eq!(exts, vec!["ts", "tsx", "md", "mdx"]);
5933    }
5934
5935    #[test]
5936    fn wrapped_named_const_module_exports_resolves() {
5937        // `module.exports = createJestConfig(customConfig)` (next/jest idiom).
5938        let source = r#"
5939            const nextJest = require("next/jest");
5940            const createJestConfig = nextJest();
5941            const customConfig = { testMatch: ["**/*.test.ts"] };
5942            module.exports = createJestConfig(customConfig);
5943        "#;
5944        let matches = extract_config_string_array(source, &js_path(), &["testMatch"]);
5945        assert_eq!(matches, vec!["**/*.test.ts"]);
5946    }
5947
5948    #[test]
5949    fn wrapped_named_const_nested_and_curried_resolve() {
5950        let nested = r#"
5951            const nextConfig = { pageExtensions: ["mdx"] };
5952            const withMDX = (c) => c;
5953            const withFoo = (c) => c;
5954            export default withMDX(withFoo(nextConfig));
5955        "#;
5956        assert_eq!(
5957            extract_config_string_array(nested, &js_path(), &["pageExtensions"]),
5958            vec!["mdx"]
5959        );
5960
5961        let curried = r#"
5962            const nextConfig = { pageExtensions: ["md"] };
5963            const compose = (..._p) => (c) => c;
5964            export default compose(a, b)(nextConfig);
5965        "#;
5966        assert_eq!(
5967            extract_config_string_array(curried, &js_path(), &["pageExtensions"]),
5968            vec!["md"]
5969        );
5970    }
5971
5972    #[test]
5973    fn wrapped_inline_object_still_resolves() {
5974        // The pre-existing inline-object form must keep working unchanged.
5975        let source = r#"
5976            const withMDX = createMDX({});
5977            export default withMDX({ pageExtensions: ["mdx"] });
5978        "#;
5979        assert_eq!(
5980            extract_config_string_array(source, &js_path(), &["pageExtensions"]),
5981            vec!["mdx"]
5982        );
5983    }
5984}