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 fallow_extract::{JsText, visitor::extract_import_from_callable};
8use oxc_ast::ast::*;
9use oxc_span::SourceType;
10use rustc_hash::FxHashSet;
11
12#[path = "config_parser_const_inline.rs"]
13mod const_inline;
14use const_inline::holds_one_stable_object;
15#[path = "config_parser_local_inline.rs"]
16mod local_inline;
17#[path = "config_parser_merge_config.rs"]
18mod merge_config;
19use merge_config::{read_each_config, read_last_config, read_last_match};
20#[path = "config_parser_multi_config.rs"]
21mod multi_config;
22use multi_config::find_default_export_array;
23#[path = "config_parser_string_values.rs"]
24mod string_values;
25pub(crate) use multi_config::{
26    extract_each_config_entries, extract_each_config_path_aliases,
27    extract_each_config_require_strings, extract_each_config_shallow_strings, find_config_objects,
28};
29use string_values::string_or_array_in;
30#[path = "config_parser_alias_constant.rs"]
31mod alias_constant;
32#[path = "config_parser_alias_entry.rs"]
33pub(super) mod alias_entry;
34#[path = "config_parser_vite_plugin_call.rs"]
35pub(crate) mod vite_plugin_call;
36pub(crate) use vite_plugin_call::extract_vite_plugin_call_option_path;
37use vite_plugin_call::is_plugin_binding_call;
38
39/// Extract all import source specifiers from JS/TS source code.
40#[must_use]
41pub(crate) fn extract_imports(source: &str, path: &Path) -> Vec<String> {
42    extract_from_source(source, path, |program| {
43        let mut sources = Vec::new();
44        for stmt in &program.body {
45            if let Statement::ImportDeclaration(decl) = stmt {
46                sources.push(decl.source.value.text().into_owned());
47            }
48        }
49        Some(sources)
50    })
51    .unwrap_or_default()
52}
53
54/// Extract import sources and top-level `require('...')` statements.
55#[must_use]
56pub(crate) fn extract_imports_and_requires(source: &str, path: &Path) -> Vec<String> {
57    extract_from_source(source, path, |program| {
58        let mut sources = Vec::new();
59        for stmt in &program.body {
60            match stmt {
61                Statement::ImportDeclaration(decl) => {
62                    sources.push(decl.source.value.text().into_owned());
63                }
64                Statement::ExpressionStatement(expr) => {
65                    if let Expression::CallExpression(call) = &expr.expression
66                        && is_require_call(call)
67                        && let Some(s) = get_require_source(call)
68                    {
69                        sources.push(s);
70                    }
71                }
72                _ => {}
73            }
74        }
75        Some(sources)
76    })
77    .unwrap_or_default()
78}
79
80/// Extract string array from a property at a nested path in a config's default export.
81#[must_use]
82pub(crate) fn extract_config_string_array(
83    source: &str,
84    path: &Path,
85    prop_path: &[&str],
86) -> Vec<String> {
87    extract_from_source(source, path, |program| {
88        read_each_config(program, |obj| {
89            get_nested_string_array_from_object(obj, prop_path)
90        })
91    })
92    .unwrap_or_default()
93}
94
95/// Extract a single string from a property at a nested path.
96#[must_use]
97pub(crate) fn extract_config_string(
98    source: &str,
99    path: &Path,
100    prop_path: &[&str],
101) -> Option<String> {
102    extract_from_source(source, path, |program| {
103        read_last_config(program, prop_path, get_nested_string_from_object)
104    })
105}
106
107/// Extract a shell command string from a property at a nested path.
108#[must_use]
109pub(crate) fn extract_config_command(
110    source: &str,
111    path: &Path,
112    prop_path: &[&str],
113) -> Option<String> {
114    extract_from_source(source, path, |program| {
115        read_last_config(program, prop_path, get_nested_command_from_object)
116    })
117}
118
119/// Extract string values from top-level properties of the default export or
120/// `module.exports` object.
121#[must_use]
122pub(crate) fn extract_config_property_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
123    extract_from_source(source, path, |program| {
124        read_each_config(program, |obj| {
125            let mut values = Vec::new();
126            if let Some(prop) = find_property(obj, key) {
127                collect_all_string_values(&prop.value, &mut values);
128            }
129            Some(values)
130        })
131    })
132    .unwrap_or_default()
133}
134
135/// Extract only top-level string values from a property's array.
136#[must_use]
137pub(crate) fn extract_config_shallow_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
138    extract_from_source(source, path, |program| {
139        read_each_config(program, |obj| {
140            let prop = find_property(obj, key)?;
141            Some(collect_shallow_string_values(&prop.value))
142        })
143    })
144    .unwrap_or_default()
145}
146
147/// Extract top-level string values from a config array, including object entries.
148#[must_use]
149pub(crate) fn extract_config_shallow_strings_or_object_property(
150    source: &str,
151    path: &Path,
152    key: &str,
153    object_property: &str,
154) -> Vec<String> {
155    extract_from_source(source, path, |program| {
156        read_each_config(program, |obj| {
157            let prop = find_property(obj, key)?;
158            Some(collect_shallow_string_or_object_property_values(
159                &prop.value,
160                object_property,
161            ))
162        })
163    })
164    .unwrap_or_default()
165}
166
167/// Extract shallow strings from an array property inside a nested object path.
168#[must_use]
169pub(crate) fn extract_config_nested_shallow_strings(
170    source: &str,
171    path: &Path,
172    outer_path: &[&str],
173    key: &str,
174) -> Vec<String> {
175    extract_from_source(source, path, |program| {
176        read_each_config(program, |obj| {
177            let nested = get_nested_expression(obj, outer_path)?;
178            if let Expression::ObjectExpression(nested_obj) = nested {
179                let prop = find_property(nested_obj, key)?;
180                Some(collect_shallow_string_values(&prop.value))
181            } else {
182                None
183            }
184        })
185    })
186    .unwrap_or_default()
187}
188
189/// Get a top-level property expression from an object.
190pub(crate) fn property_expr<'a>(
191    obj: &'a ObjectExpression<'a>,
192    key: &str,
193) -> Option<&'a Expression<'a>> {
194    find_property(obj, key).map(|prop| &prop.value)
195}
196
197/// Get a top-level property object from an object.
198pub(crate) fn property_object<'a>(
199    obj: &'a ObjectExpression<'a>,
200    key: &str,
201) -> Option<&'a ObjectExpression<'a>> {
202    property_expr(obj, key).and_then(object_expression)
203}
204
205/// Get a string-like top-level property value from an object.
206pub(crate) fn property_string(obj: &ObjectExpression<'_>, key: &str) -> Option<String> {
207    property_expr(obj, key).and_then(expression_to_string)
208}
209
210/// Convert an expression to an object expression when it is statically recoverable.
211pub(crate) fn object_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ObjectExpression<'a>> {
212    match expr {
213        Expression::ObjectExpression(obj) => Some(obj),
214        Expression::ParenthesizedExpression(paren) => object_expression(&paren.expression),
215        Expression::TSSatisfiesExpression(ts_sat) => object_expression(&ts_sat.expression),
216        Expression::TSAsExpression(ts_as) => object_expression(&ts_as.expression),
217        _ => None,
218    }
219}
220
221/// Convert an expression to an array expression when it is statically recoverable.
222pub(crate) fn array_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ArrayExpression<'a>> {
223    match expr {
224        Expression::ArrayExpression(arr) => Some(arr),
225        Expression::ParenthesizedExpression(paren) => array_expression(&paren.expression),
226        Expression::TSSatisfiesExpression(ts_sat) => array_expression(&ts_sat.expression),
227        Expression::TSAsExpression(ts_as) => array_expression(&ts_as.expression),
228        _ => None,
229    }
230}
231
232/// Convert a config path string to a `PathBuf` with platform-independent
233/// separator handling.
234pub(crate) fn path_from_config_string(raw: &str) -> PathBuf {
235    PathBuf::from(raw.replace('\\', "/"))
236}
237
238/// Convert a config path to the forward-slash string form used in plugin output.
239pub(crate) fn path_to_config_string(path: &Path) -> String {
240    path.to_string_lossy().replace('\\', "/")
241}
242
243/// Convert a path-like expression to a statically recoverable path.
244pub(crate) fn expression_to_path(expr: &Expression<'_>) -> Option<PathBuf> {
245    expression_to_path_string(expr).map(|path| path_from_config_string(&path))
246}
247
248/// Convert a path-like expression to zero or more statically recoverable paths.
249pub(crate) fn expression_to_path_values(expr: &Expression<'_>) -> Vec<PathBuf> {
250    match expr {
251        Expression::ArrayExpression(arr) => arr
252            .elements
253            .iter()
254            .filter_map(|element| element.as_expression().and_then(expression_to_path))
255            .collect(),
256        _ => expression_to_path(expr).into_iter().collect(),
257    }
258}
259
260/// True when an expression explicitly disables a config section.
261pub(crate) fn is_disabled_expression(expr: &Expression<'_>) -> bool {
262    matches!(expr, Expression::BooleanLiteral(boolean) if !boolean.value)
263        || matches!(expr, Expression::NullLiteral(_))
264}
265
266/// True when a nested config property is a static `true` boolean or object value.
267#[must_use]
268pub(crate) fn extract_config_truthy_bool_or_object(
269    source: &str,
270    path: &Path,
271    prop_path: &[&str],
272) -> bool {
273    extract_from_source(source, path, |program| {
274        read_last_config(program, prop_path, |obj, key_path| {
275            let expr = get_nested_expression(obj, key_path)?;
276            Some(is_truthy_bool_or_object(expr))
277        })
278    })
279    .unwrap_or(false)
280}
281
282fn is_truthy_bool_or_object(expr: &Expression<'_>) -> bool {
283    match expr {
284        Expression::BooleanLiteral(boolean) => boolean.value,
285        Expression::ObjectExpression(_) => true,
286        Expression::ParenthesizedExpression(paren) => is_truthy_bool_or_object(&paren.expression),
287        Expression::TSSatisfiesExpression(ts_sat) => is_truthy_bool_or_object(&ts_sat.expression),
288        Expression::TSAsExpression(ts_as) => is_truthy_bool_or_object(&ts_as.expression),
289        _ => false,
290    }
291}
292
293/// Extract keys of an object property at a nested path.
294#[must_use]
295pub(crate) fn extract_config_object_keys(
296    source: &str,
297    path: &Path,
298    prop_path: &[&str],
299) -> Vec<String> {
300    extract_from_source(source, path, |program| {
301        read_each_config(program, |obj| get_nested_object_keys(obj, prop_path))
302    })
303    .unwrap_or_default()
304}
305
306/// Extract a value that may be a single string, string array, or object with
307/// string/array values.
308#[must_use]
309pub(crate) fn extract_config_string_or_array(
310    source: &str,
311    path: &Path,
312    prop_path: &[&str],
313) -> Vec<String> {
314    extract_from_source(source, path, |program| {
315        read_each_config(program, |obj| {
316            get_nested_string_or_array(obj, prop_path, PathScope::Program(program))
317        })
318    })
319    .unwrap_or_default()
320}
321
322/// Extract a string, array, or object-map value from each config of a
323/// default-exported config array, or from the single config object.
324///
325/// Supports `export default [...]` and `export default defineConfig([...])`.
326/// The function reads `prop_path` from each object element of the array. When
327/// the default export is not an array, it reads the config object.
328#[must_use]
329pub(crate) fn extract_config_array_or_object_string_or_array(
330    source: &str,
331    path: &Path,
332    prop_path: &[&str],
333) -> Vec<String> {
334    extract_from_source(source, path, |program| {
335        let Some(arr) = find_default_export_array(program) else {
336            return read_each_config(program, |obj| {
337                get_nested_string_or_array(obj, prop_path, PathScope::Program(program))
338            });
339        };
340        let values = arr
341            .elements
342            .iter()
343            .filter_map(|element| element.as_expression().and_then(object_expression))
344            .filter_map(|element_obj| {
345                get_nested_string_or_array(element_obj, prop_path, PathScope::Program(program))
346            })
347            .flatten()
348            .collect();
349        Some(values)
350    })
351    .unwrap_or_default()
352}
353
354/// Extract a statically recoverable path-like value from a property path.
355#[must_use]
356pub(crate) fn extract_config_path(
357    source: &str,
358    path: &Path,
359    prop_path: &[&str],
360) -> Option<PathBuf> {
361    extract_from_source(source, path, |program| {
362        read_last_config(program, prop_path, |obj, key_path| {
363            let expr = get_nested_expression(obj, key_path)?;
364            expression_to_path(expr)
365        })
366    })
367}
368
369/// Extract string values from a property path, also searching inside array elements.
370#[must_use]
371pub(crate) fn extract_config_array_nested_string_or_array(
372    source: &str,
373    path: &Path,
374    array_path: &[&str],
375    inner_path: &[&str],
376) -> Vec<String> {
377    extract_from_source(source, path, |program| {
378        read_each_config(program, |obj| {
379            let array_expr = get_nested_expression(obj, array_path)?;
380            let Expression::ArrayExpression(arr) = array_expr else {
381                return None;
382            };
383            let mut results = Vec::new();
384            for element in &arr.elements {
385                if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
386                    && let Some(values) = get_nested_string_or_array(
387                        element_obj,
388                        inner_path,
389                        PathScope::Program(program),
390                    )
391                {
392                    results.extend(values);
393                }
394            }
395            if results.is_empty() {
396                None
397            } else {
398                Some(results)
399            }
400        })
401    })
402    .unwrap_or_default()
403}
404
405/// Extract the string values of each key, one entry per object element of an
406/// array.
407///
408/// Each entry holds one value list per key, in the order of `keys`. A missing
409/// key gives an empty list. Use this function when values of one element must
410/// stay together, for example a `rootDir` and the paths that it anchors.
411#[must_use]
412pub(crate) fn extract_config_array_object_fields(
413    source: &str,
414    path: &Path,
415    array_path: &[&str],
416    keys: &[&str],
417) -> Vec<Vec<Vec<String>>> {
418    extract_from_source(source, path, |program| {
419        read_each_config(program, |obj| {
420            let Expression::ArrayExpression(arr) = get_nested_expression(obj, array_path)? else {
421                return None;
422            };
423            let elements = arr
424                .elements
425                .iter()
426                .filter_map(|element| match element.as_expression() {
427                    Some(Expression::ObjectExpression(element_obj)) => Some(
428                        keys.iter()
429                            .map(|key| {
430                                get_nested_string_or_array(
431                                    element_obj,
432                                    &[key],
433                                    PathScope::Program(program),
434                                )
435                                .unwrap_or_default()
436                            })
437                            .collect(),
438                    ),
439                    _ => None,
440                })
441                .collect();
442            Some(elements)
443        })
444    })
445    .unwrap_or_default()
446}
447
448/// Extract string values from a property path, searching inside all values of an object.
449#[must_use]
450pub(crate) fn extract_config_object_nested_string_or_array(
451    source: &str,
452    path: &Path,
453    object_path: &[&str],
454    inner_path: &[&str],
455) -> Vec<String> {
456    extract_config_object_nested(source, path, object_path, |value_obj| {
457        get_nested_string_or_array(value_obj, inner_path, PathScope::Bare)
458    })
459}
460
461/// Extract a single string value from each object under a property path.
462#[must_use]
463pub(crate) fn extract_config_object_nested_strings(
464    source: &str,
465    path: &Path,
466    object_path: &[&str],
467    inner_path: &[&str],
468) -> Vec<String> {
469    extract_config_object_nested(source, path, object_path, |value_obj| {
470        get_nested_string_from_object(value_obj, inner_path).map(|s| vec![s])
471    })
472}
473
474/// Shared helper for object-nested extraction.
475fn extract_config_object_nested(
476    source: &str,
477    path: &Path,
478    object_path: &[&str],
479    extract_fn: impl Fn(&ObjectExpression<'_>) -> Option<Vec<String>> + Sync,
480) -> Vec<String> {
481    extract_from_source(source, path, |program| {
482        read_each_config(program, |obj| {
483            let obj_expr = get_nested_expression(obj, object_path)?;
484            let Expression::ObjectExpression(target_obj) = obj_expr else {
485                return None;
486            };
487            let mut results = Vec::new();
488            for prop in &target_obj.properties {
489                if let ObjectPropertyKind::ObjectProperty(p) = prop
490                    && let Expression::ObjectExpression(value_obj) = &p.value
491                    && let Some(values) = extract_fn(value_obj)
492                {
493                    results.extend(values);
494                }
495            }
496            if results.is_empty() {
497                None
498            } else {
499                Some(results)
500            }
501        })
502    })
503    .unwrap_or_default()
504}
505
506/// Extract `require('...')` call argument strings from a property's value.
507#[must_use]
508pub(crate) fn extract_config_require_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
509    extract_from_source(source, path, |program| {
510        read_each_config(program, |obj| {
511            let prop = find_property(obj, key)?;
512            Some(collect_require_sources(&prop.value))
513        })
514    })
515    .unwrap_or_default()
516}
517
518/// Extract alias mappings from an object or array-based alias config.
519#[must_use]
520pub(crate) fn extract_config_aliases(
521    source: &str,
522    path: &Path,
523    prop_path: &[&str],
524) -> Vec<(String, String)> {
525    extract_config_aliases_kinded(source, path, prop_path)
526        .into_iter()
527        .map(|(find, replacement, _is_bare)| (find, replacement))
528        .collect()
529}
530
531/// Extract alias mappings where the replacement is a filesystem path value.
532#[must_use]
533pub(crate) fn extract_config_path_aliases(
534    source: &str,
535    path: &Path,
536    prop_path: &[&str],
537) -> Vec<(String, PathBuf)> {
538    extract_config_aliases_kinded(source, path, prop_path)
539        .into_iter()
540        .map(|(find, replacement, _is_bare)| (find, path_from_config_string(&replacement)))
541        .collect()
542}
543
544/// Like [`extract_config_aliases`] but each tuple carries a bare-string flag.
545#[must_use]
546pub(crate) fn extract_config_aliases_kinded(
547    source: &str,
548    path: &Path,
549    prop_path: &[&str],
550) -> Vec<(String, String, bool)> {
551    extract_from_source(source, path, |program| {
552        read_each_config(program, |obj| {
553            let expr = get_nested_expression(obj, prop_path)?;
554            let mut visited = FxHashSet::default();
555            let aliases = resolve_alias_pairs_kinded(program, path, expr, &mut visited, 0);
556            (!aliases.is_empty()).then_some(aliases)
557        })
558    })
559    .unwrap_or_default()
560}
561
562/// Extract kinded alias mappings nested inside an array of config objects.
563///
564/// Each tuple has the same shape as in [`extract_config_aliases_kinded`].
565#[must_use]
566pub(crate) fn extract_config_array_nested_aliases_kinded(
567    source: &str,
568    path: &Path,
569    array_path: &[&str],
570    alias_path: &[&str],
571) -> Vec<(String, String, bool)> {
572    extract_from_source(source, path, |program| {
573        read_each_config(program, |obj| {
574            let array_expr = get_nested_expression(obj, array_path)?;
575            let Expression::ArrayExpression(arr) = array_expr else {
576                return None;
577            };
578            let mut results = Vec::new();
579            for element in &arr.elements {
580                if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
581                    && let Some(alias_expr) = get_nested_expression(element_obj, alias_path)
582                {
583                    results.extend(alias_constant::expression_to_alias_pairs_kinded(
584                        alias_expr,
585                        PathScope::Program(program),
586                    ));
587                }
588            }
589            (!results.is_empty()).then_some(results)
590        })
591    })
592    .unwrap_or_default()
593}
594
595/// Extract kinded aliases from a default-exported ARRAY config.
596#[must_use]
597pub(crate) fn extract_default_export_array_aliases_kinded(
598    source: &str,
599    path: &Path,
600    alias_path: &[&str],
601) -> Vec<(String, String, bool)> {
602    extract_from_source(source, path, |program| {
603        let arr = find_default_export_array(program)?;
604        let mut results = Vec::new();
605        for element in &arr.elements {
606            if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
607                && let Some(alias_expr) = get_nested_expression(element_obj, alias_path)
608            {
609                results.extend(alias_constant::expression_to_alias_pairs_kinded(
610                    alias_expr,
611                    PathScope::Program(program),
612                ));
613            }
614        }
615        (!results.is_empty()).then_some(results)
616    })
617    .unwrap_or_default()
618}
619
620/// True when a parsed config has neither an object nor array default export.
621#[must_use]
622pub(crate) fn config_default_export_unreachable(source: &str, path: &Path) -> bool {
623    extract_from_source(source, path, |program| {
624        let reachable =
625            find_config_object(program).is_some() || find_default_export_array(program).is_some();
626        Some(reachable)
627    })
628    .is_some_and(|reachable| !reachable)
629}
630
631/// Extract string values from a nested array, supporting both string elements and
632/// object elements with a named string/path field.
633///
634/// Useful for configs like:
635/// - `components: ["~/components", { path: "~/feature-components" }]`
636#[must_use]
637pub(crate) fn extract_config_array_object_strings(
638    source: &str,
639    path: &Path,
640    array_path: &[&str],
641    key: &str,
642) -> Vec<String> {
643    extract_from_source(source, path, |program| {
644        read_each_config(program, |obj| {
645            let array_expr = get_nested_expression(obj, array_path)?;
646            let Expression::ArrayExpression(arr) = array_expr else {
647                return None;
648            };
649
650            let mut results = Vec::new();
651            for element in &arr.elements {
652                let Some(expr) = element.as_expression() else {
653                    continue;
654                };
655                match expr {
656                    Expression::ObjectExpression(item) => {
657                        if let Some(prop) = find_property(item, key)
658                            && let Some(value) = expression_to_path_string(&prop.value)
659                        {
660                            results.push(value);
661                        }
662                    }
663                    _ => {
664                        if let Some(value) = expression_to_path_string(expr) {
665                            results.push(value);
666                        }
667                    }
668                }
669            }
670
671            (!results.is_empty()).then_some(results)
672        })
673    })
674    .unwrap_or_default()
675}
676
677/// Extract Storybook-style static directory entries from an array.
678///
679/// Supports string entries and object entries with a string-like `from` plus
680/// optional string-like `to`.
681#[must_use]
682pub(crate) fn extract_config_static_dir_entries(
683    source: &str,
684    path: &Path,
685    array_path: &[&str],
686) -> Vec<(String, Option<String>)> {
687    extract_from_source(source, path, |program| {
688        read_each_config(program, |obj| {
689            let array_expr = get_nested_expression(obj, array_path)?;
690            let Expression::ArrayExpression(arr) = array_expr else {
691                return None;
692            };
693
694            let mut results = Vec::new();
695            for element in &arr.elements {
696                let Some(expr) = element.as_expression() else {
697                    continue;
698                };
699                match expr {
700                    Expression::ObjectExpression(item) => {
701                        if let Some(from) = property_string(item, "from") {
702                            let to = property_string(item, "to");
703                            results.push((from, to));
704                        }
705                    }
706                    _ => {
707                        if let Some(from) = expression_to_path_string(expr) {
708                            results.push((from, None));
709                        }
710                    }
711                }
712            }
713
714            (!results.is_empty()).then_some(results)
715        })
716    })
717    .unwrap_or_default()
718}
719
720/// Extract paired shell command and string values from each object element of an array.
721#[must_use]
722pub(crate) fn extract_config_array_object_command_pairs(
723    source: &str,
724    path: &Path,
725    array_path: &[&str],
726    primary_key: &str,
727    secondary_key: &str,
728) -> Vec<(String, Option<String>)> {
729    extract_from_source(source, path, |program| {
730        read_each_config(program, |obj| {
731            let array_expr = get_nested_expression(obj, array_path)?;
732            let Expression::ArrayExpression(arr) = array_expr else {
733                return None;
734            };
735
736            let mut results = Vec::new();
737            for element in &arr.elements {
738                let Some(Expression::ObjectExpression(item)) = element.as_expression() else {
739                    continue;
740                };
741                let Some(primary) = find_property(item, primary_key)
742                    .and_then(|prop| expression_to_command(&prop.value))
743                else {
744                    continue;
745                };
746                let secondary = find_property(item, secondary_key)
747                    .and_then(|prop| expression_to_path_string(&prop.value));
748                results.push((primary, secondary));
749            }
750
751            (!results.is_empty()).then_some(results)
752        })
753    })
754    .unwrap_or_default()
755}
756
757/// Extract static specifiers from thunk-wrapped dynamic imports inside an
758/// array property.
759///
760/// Captures the `SPEC` argument from each `() => import('SPEC')` element of
761/// an array nested under `prop_path` in the config's default-exported object.
762///
763/// # The pattern
764///
765/// Configs and registries that need to defer module evaluation commonly hold
766/// arrays of *thunks* — zero-argument arrow functions whose body is a single
767/// dynamic import:
768///
769/// ```ts
770/// export default defineConfig({
771///     modules: [
772///         () => import('./feature-a'),
773///         { file: () => import('./feature-b'), enabled: true },
774///     ],
775/// })
776/// ```
777///
778/// `import('SPEC')` is the ECMAScript dynamic-import expression (TC39
779/// dynamic-import proposal, shipped in ES2020): a runtime module loader call
780/// that returns a `Promise<Module>`. Wrapping it in `() => import('SPEC')`
781/// turns "load module X now" into "value that, when invoked, loads module X"
782/// — a thunk the host can call lazily.
783///
784/// The technique predates any single framework. It's the same shape used by
785/// route-level code-splitting (`Vue Router`, `React Router`, `Next.js`),
786/// `React.lazy`, Webpack's documented dynamic-import code-splitting recipes,
787/// and any registry that wants to keep boot cheap, break import cycles, or
788/// let bundlers tree-shake unused branches. Configs that adopt the pattern
789/// can therefore declare large module graphs without forcing eager
790/// evaluation of every entry at config parse time.
791///
792/// # Recognised array element shapes
793///
794/// - Concise arrow: `() => import('SPEC')`
795/// - Block-body arrow with explicit return: `() => { return import('SPEC') }`
796/// - Object form with a `file` property holding the arrow:
797///   `{ file: () => import('SPEC'), /* peer fields */ }`
798///
799/// Non-matching elements (string literals, variables, template-string
800/// specifiers, computed expressions) are silently skipped: callers receive
801/// only the statically-resolvable specifiers, in source order.
802#[must_use]
803pub(crate) fn extract_lazy_imports_in_array(
804    source: &str,
805    path: &Path,
806    prop_path: &[&str],
807) -> Vec<String> {
808    extract_from_source(source, path, |program| {
809        read_each_config(program, |obj| {
810            let array_expr = get_nested_expression(obj, prop_path)?;
811            let Expression::ArrayExpression(arr) = array_expr else {
812                return None;
813            };
814            let mut specs = Vec::new();
815            for element in &arr.elements {
816                let Some(expr) = element.as_expression() else {
817                    continue;
818                };
819                if let Some(spec) = lazy_import_specifier(expr) {
820                    specs.push(spec);
821                }
822            }
823            (!specs.is_empty()).then_some(specs)
824        })
825    })
826    .unwrap_or_default()
827}
828
829/// Read a lazy-import specifier from a single array element expression.
830///
831/// Two outer shapes are accepted at this level (array-element navigation):
832/// - A bare callable: `() => import('SPEC')` or the function-expression
833///   equivalent.
834/// - An object with a `file` property holding the callable:
835///   `{ file: () => import('SPEC'), /* peer fields */ }`.
836///
837/// The actual callable → import peeling is delegated to
838/// [`extract_import_from_callable`], which is shared with the visitor-side
839/// dynamic-import helpers so all three navigation pipelines stay in lockstep
840/// when ECMAScript adds new wrapper shapes.
841fn lazy_import_specifier(expr: &Expression<'_>) -> Option<String> {
842    let callable = match expr {
843        Expression::ObjectExpression(obj) => &find_property(obj, "file")?.value,
844        _ => expr,
845    };
846    let import_expr = extract_import_from_callable(callable)?;
847    expression_to_string(&import_expr.source)
848}
849
850/// Extract the first string of each `[name, options]` tuple in an array at a
851/// property path, such as `modules: [["@nuxt/content", { ... }]]`. Plain
852/// string entries are not returned; read them with
853/// [`extract_config_string_array`].
854#[must_use]
855pub(crate) fn extract_config_array_tuple_heads(
856    source: &str,
857    path: &Path,
858    array_path: &[&str],
859) -> Vec<String> {
860    extract_from_source(source, path, |program| {
861        read_each_config(program, |obj| {
862            let Expression::ArrayExpression(entries) = get_nested_expression(obj, array_path)?
863            else {
864                return None;
865            };
866            let heads = entries
867                .elements
868                .iter()
869                .filter_map(|entry| match entry.as_expression() {
870                    Some(Expression::ArrayExpression(tuple)) => tuple
871                        .elements
872                        .first()
873                        .and_then(ArrayExpressionElement::as_expression)
874                        .and_then(expression_to_string),
875                    _ => None,
876                })
877                .collect();
878            Some(heads)
879        })
880    })
881    .unwrap_or_default()
882}
883
884/// Extract a string-like option from a plugin tuple inside a config plugin array.
885///
886/// Supports config shapes like:
887/// - `{ expo: { plugins: [["expo-router", { root: "src/app" }]] } }`
888/// - `export default { expo: { plugins: [["expo-router", { root: "./src/app" }]] } }`
889/// - `{ plugins: [["expo-router", { root: "./src/routes" }]] }`
890#[must_use]
891fn extract_config_plugin_option_string(
892    source: &str,
893    path: &Path,
894    plugins_path: &[&str],
895    plugin_name: &str,
896    option_key: &str,
897) -> Option<String> {
898    extract_from_source(source, path, |program| {
899        read_last_match(program, |obj| {
900            let plugins_expr = get_nested_expression(obj, plugins_path)?;
901            let Expression::ArrayExpression(plugins) = plugins_expr else {
902                return None;
903            };
904
905            for entry in &plugins.elements {
906                let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
907                    continue;
908                };
909                let Some(plugin_expr) = tuple
910                    .elements
911                    .first()
912                    .and_then(ArrayExpressionElement::as_expression)
913                else {
914                    continue;
915                };
916                if expression_to_string(plugin_expr).as_deref() != Some(plugin_name) {
917                    continue;
918                }
919
920                let Some(options_expr) = tuple
921                    .elements
922                    .get(1)
923                    .and_then(ArrayExpressionElement::as_expression)
924                else {
925                    continue;
926                };
927                let Expression::ObjectExpression(options_obj) = options_expr else {
928                    continue;
929                };
930                let option = find_property(options_obj, option_key)?;
931                return expression_to_path_string(&option.value);
932            }
933
934            None
935        })
936    })
937}
938
939/// Extract a string-like option from the first plugin array path that contains it.
940#[must_use]
941pub(crate) fn extract_config_plugin_option_string_from_paths(
942    source: &str,
943    path: &Path,
944    plugin_paths: &[&[&str]],
945    plugin_name: &str,
946    option_key: &str,
947) -> Option<String> {
948    plugin_paths.iter().find_map(|plugins_path| {
949        extract_config_plugin_option_string(source, path, plugins_path, plugin_name, option_key)
950    })
951}
952
953/// A Vite plugin package whose options object names other packages as strings.
954struct VitePluginOptionReader {
955    package: &'static str,
956    read: fn(&ObjectExpression<'_>, &mut Vec<String>),
957}
958
959/// The Vite plugins whose options name packages that the plugin loads at
960/// build time. The list is closed so that an unknown plugin option never
961/// credits a package.
962const VITE_PLUGIN_OPTION_READERS: &[VitePluginOptionReader] = &[
963    VitePluginOptionReader {
964        package: "@vitejs/plugin-react",
965        read: collect_vite_react_babel_dependencies,
966    },
967    VitePluginOptionReader {
968        package: "@vitejs/plugin-react-swc",
969        read: collect_vite_react_swc_dependencies,
970    },
971    VitePluginOptionReader {
972        package: "@wyw-in-js/vite",
973        read: collect_wyw_babel_options_dependencies,
974    },
975];
976
977/// How many wrapper calls, such as `profile(wyw({ ... }))`, the reader looks
978/// through to find a known plugin call in a `plugins` array entry.
979const MAX_VITE_PLUGIN_WRAPPER_DEPTH: usize = 3;
980
981/// Extract package names that known Vite plugins read from their options in a
982/// Vite-style `plugins` array: Babel plugins and presets of
983/// `@vitejs/plugin-react`, SWC plugins of `@vitejs/plugin-react-swc`, and
984/// `babelOptions` of `@wyw-in-js/vite`.
985#[must_use]
986pub(crate) fn extract_vite_plugin_option_dependencies(source: &str, path: &Path) -> Vec<String> {
987    extract_from_source(source, path, |program| {
988        let bindings: Vec<(PluginImportBindings, &VitePluginOptionReader)> =
989            VITE_PLUGIN_OPTION_READERS
990                .iter()
991                .map(|reader| {
992                    (
993                        collect_plugin_import_bindings(program, reader.package),
994                        reader,
995                    )
996                })
997                .filter(|(imports, _)| !imports.is_empty())
998                .collect();
999        if bindings.is_empty() {
1000            return None;
1001        }
1002
1003        read_each_config(program, |obj| {
1004            let plugins = get_nested_expression(obj, &["plugins"])?;
1005            let Expression::ArrayExpression(plugin_array) = plugins else {
1006                return None;
1007            };
1008
1009            let mut deps = Vec::new();
1010            for element in &plugin_array.elements {
1011                if let Some(Expression::CallExpression(call)) = element.as_expression() {
1012                    read_vite_plugin_call(call, &bindings, 0, &mut deps);
1013                }
1014            }
1015
1016            (!deps.is_empty()).then_some(deps)
1017        })
1018    })
1019    .unwrap_or_default()
1020}
1021
1022fn read_vite_plugin_call(
1023    call: &CallExpression<'_>,
1024    bindings: &[(PluginImportBindings, &VitePluginOptionReader)],
1025    depth: usize,
1026    deps: &mut Vec<String>,
1027) {
1028    if let Some((_, reader)) = bindings
1029        .iter()
1030        .find(|(imports, _)| is_plugin_binding_call(call, imports))
1031    {
1032        if let Some(Expression::ObjectExpression(options)) =
1033            call.arguments.first().and_then(Argument::as_expression)
1034        {
1035            (reader.read)(options, deps);
1036        }
1037        return;
1038    }
1039    if depth >= MAX_VITE_PLUGIN_WRAPPER_DEPTH {
1040        return;
1041    }
1042    for argument in &call.arguments {
1043        if let Some(Expression::CallExpression(inner)) = argument.as_expression() {
1044            read_vite_plugin_call(inner, bindings, depth + 1, deps);
1045        }
1046    }
1047}
1048
1049/// The package name that a config string names, such as an SWC plugin in a
1050/// `[name, options]` tuple. A relative or absolute path, a protocol value, or
1051/// an invalid specifier names no package. A subpath maps to its package.
1052#[must_use]
1053pub(crate) fn config_string_package_name(raw: &str) -> Option<String> {
1054    let specifier = raw.trim();
1055    is_package_specifier(specifier).then(|| crate::resolve::extract_package_name(specifier))
1056}
1057
1058/// Extract the package names of SWC plugin tuples, such as
1059/// `swcPlugins: [["@lingui/swc-plugin", {}]]`, at a property path.
1060#[must_use]
1061pub(crate) fn extract_config_swc_plugin_dependencies(
1062    source: &str,
1063    path: &Path,
1064    array_path: &[&str],
1065) -> Vec<String> {
1066    extract_config_array_tuple_heads(source, path, array_path)
1067        .iter()
1068        .filter_map(|raw| config_string_package_name(raw))
1069        .fold(Vec::new(), |mut deps, dep| {
1070            push_unique_string(&mut deps, dep);
1071            deps
1072        })
1073}
1074
1075/// How a config reader reads a path value with a leading `/`.
1076#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1077enum LeadingSlash {
1078    /// Relative to the project root, as Vite reads `/src`.
1079    RootRelative,
1080    /// A filesystem path, as webpack and Node read `/src`.
1081    Filesystem,
1082}
1083
1084/// Normalize a config-relative path to a project-root-relative path.
1085///
1086/// Handles values extracted from config files such as `"./src"`, `"src/lib"`,
1087/// `"/src"`, or absolute filesystem paths under `root`. An absolute path under
1088/// `root` is read as absolute. Any other leading `/` is read as relative to
1089/// `root`, the same as Vite: this includes the root itself and, when
1090/// `<root>/<root>` is a directory, every leading-`/` value. Use [`normalize_filesystem_config_path_buf`] for a reader whose tool
1091/// reads a leading `/` as a filesystem path.
1092#[must_use]
1093pub(crate) fn normalize_config_path_buf(
1094    raw: impl AsRef<Path>,
1095    config_path: &Path,
1096    root: &Path,
1097) -> Option<PathBuf> {
1098    normalize_path_value(raw.as_ref(), config_path, root, LeadingSlash::RootRelative)
1099}
1100
1101/// Normalize a config path value for a reader whose tool reads a leading `/`
1102/// as a filesystem path, such as webpack. A leading-`/` path outside `root`
1103/// resolves to `None` (issue #2806).
1104#[must_use]
1105pub(crate) fn normalize_filesystem_config_path_buf(
1106    raw: impl AsRef<Path>,
1107    config_path: &Path,
1108    root: &Path,
1109) -> Option<PathBuf> {
1110    normalize_path_value(raw.as_ref(), config_path, root, LeadingSlash::Filesystem)
1111}
1112
1113fn normalize_path_value(
1114    raw: &Path,
1115    config_path: &Path,
1116    root: &Path,
1117    leading_slash: LeadingSlash,
1118) -> Option<PathBuf> {
1119    if raw.as_os_str().is_empty() {
1120        return None;
1121    }
1122
1123    let raw_string = path_to_config_string(raw);
1124    let raw_path = Path::new(&raw_string);
1125    let root_relative_slash =
1126        leading_slash == LeadingSlash::RootRelative && raw_string.starts_with('/');
1127    let absolute = raw_path
1128        .is_absolute()
1129        .then(|| lexical_normalize(raw_path))
1130        .filter(|absolute| absolute.starts_with(root))
1131        .filter(|absolute| !(root_relative_slash && (absolute == root || root_in_root(root))));
1132    let candidate = if let Some(absolute) = absolute {
1133        absolute
1134    } else if let Some(stripped) = raw_string.strip_prefix('/') {
1135        match leading_slash {
1136            LeadingSlash::RootRelative => lexical_normalize(&root.join(stripped)),
1137            LeadingSlash::Filesystem => return None,
1138        }
1139    } else if raw_path.is_absolute() {
1140        return None;
1141    } else {
1142        let base = config_path.parent().unwrap_or(root);
1143        lexical_normalize(&base.join(raw_path))
1144    };
1145
1146    let relative = candidate.strip_prefix(root).ok()?;
1147    (!relative.as_os_str().is_empty()).then(|| relative.to_path_buf())
1148}
1149
1150/// Vite's `rootInRoot` rule: when `<root>/<root>` is a directory, Vite reads
1151/// every leading-`/` value as relative to the root, also one that starts with
1152/// the root path.
1153fn root_in_root(root: &Path) -> bool {
1154    let root_string = path_to_config_string(root);
1155    let Some(stripped) = root_string.strip_prefix('/') else {
1156        return false;
1157    };
1158    !stripped.is_empty() && root.join(stripped).is_dir()
1159}
1160
1161/// [`normalize_filesystem_config_path_buf`] as a project-root-relative
1162/// forward-slash string.
1163#[must_use]
1164pub(crate) fn normalize_filesystem_config_path(
1165    raw: impl AsRef<Path>,
1166    config_path: &Path,
1167    root: &Path,
1168) -> Option<String> {
1169    normalize_filesystem_config_path_buf(raw, config_path, root)
1170        .map(|path| path_to_config_string(&path))
1171}
1172
1173/// Normalize a config-relative path to a project-root-relative forward-slash string.
1174#[must_use]
1175pub(crate) fn normalize_config_path(
1176    raw: impl AsRef<Path>,
1177    config_path: &Path,
1178    root: &Path,
1179) -> Option<String> {
1180    normalize_config_path_buf(raw, config_path, root).map(|path| path_to_config_string(&path))
1181}
1182
1183/// A relative config path that climbs out of the plugin root, as a path
1184/// relative to that root with its leading `../` segments. The path is read
1185/// relative to the directory of `config_path`.
1186///
1187/// A workspace package is read with its own directory as the root, so a path
1188/// into a sibling workspace climbs out of it while it stays inside the project.
1189/// The caller registers the result as a parent-relative entry pattern, so the
1190/// workspace prefix resolves the `../` segments later. A path that climbs out
1191/// of the project keeps them and matches no project file.
1192pub(crate) fn parent_relative_config_path(
1193    target: &str,
1194    config_path: &Path,
1195    root: &Path,
1196) -> Option<String> {
1197    if !target.starts_with("../") {
1198        return None;
1199    }
1200    let directory = config_path.parent().unwrap_or(root);
1201    let candidate = lexical_normalize(&directory.join(target));
1202    let root = lexical_normalize(root);
1203    let mut ancestor = root.as_path();
1204    let mut climbs = 0;
1205    while !candidate.starts_with(ancestor) {
1206        ancestor = ancestor.parent()?;
1207        climbs += 1;
1208    }
1209    let rest = candidate.strip_prefix(ancestor).ok()?;
1210    (climbs > 0 && !rest.as_os_str().is_empty())
1211        .then(|| format!("{}{}", "../".repeat(climbs), path_to_config_string(rest)))
1212}
1213
1214/// Parse source and run an extraction function on the AST.
1215///
1216/// JSON files (`.json`, `.jsonc`) are parsed as JavaScript expressions wrapped in
1217/// parentheses to produce an AST compatible with `find_config_object`. The native
1218/// JSON source type in Oxc produces a different AST structure that our helpers
1219/// don't handle.
1220///
1221/// Before the extraction, a JavaScript or TypeScript program gets the literal
1222/// value of each stable same-file constant in the property values and array
1223/// elements that name it, so `projects: [UNIT]` reads like an inline object.
1224/// An object spread of such a constant gets its properties. The values that an
1225/// exported config callback returns also get the literal value of the stable
1226/// locals of that callback, so `return { ...common, entry }` reads the same way.
1227pub(crate) fn extract_from_source<T: Send>(
1228    source: &str,
1229    path: &Path,
1230    extractor: impl FnOnce(&Program) -> Option<T> + Send,
1231) -> Option<T> {
1232    let is_json = path
1233        .extension()
1234        .is_some_and(|ext| ext == "json" || ext == "jsonc");
1235    if is_json {
1236        let wrapped = wrap_json_as_expression(source);
1237        return fallow_extract::parse_bounded_or_default(&wrapped, SourceType::mjs(), |parsed| {
1238            extractor(&parsed.program)
1239        });
1240    }
1241    let source_type = SourceType::from_path(path).unwrap_or_default();
1242    fallow_extract::parse_bounded(source, || {
1243        let allocator = oxc_allocator::Allocator::default();
1244        let mut parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
1245        const_inline::with_inlined_program(&allocator, &mut parsed.program, source.len(), extractor)
1246    })
1247    .flatten()
1248}
1249
1250/// Wrap JSON or JSONC source in parentheses so Oxc parses it as one JavaScript
1251/// expression. The newline ends a trailing `//` comment, so the comment cannot
1252/// hide the closing parenthesis.
1253pub(crate) fn wrap_json_as_expression(source: &str) -> String {
1254    format!("({source}\n)")
1255}
1256
1257/// The local names that `import` declarations bind to the default export of
1258/// one plugin package.
1259#[derive(Default)]
1260struct PluginImportBindings {
1261    callables: Vec<String>,
1262    namespaces: Vec<String>,
1263}
1264
1265impl PluginImportBindings {
1266    fn is_empty(&self) -> bool {
1267        self.callables.is_empty() && self.namespaces.is_empty()
1268    }
1269}
1270
1271fn collect_plugin_import_bindings(program: &Program<'_>, package: &str) -> PluginImportBindings {
1272    let mut imports = PluginImportBindings::default();
1273
1274    for stmt in &program.body {
1275        let Statement::ImportDeclaration(decl) = stmt else {
1276            continue;
1277        };
1278        if decl.source.value != package {
1279            continue;
1280        }
1281        let Some(specifiers) = &decl.specifiers else {
1282            continue;
1283        };
1284        for specifier in specifiers {
1285            match specifier {
1286                ImportDeclarationSpecifier::ImportDefaultSpecifier(specifier) => {
1287                    push_unique_string(&mut imports.callables, specifier.local.name.to_string());
1288                }
1289                ImportDeclarationSpecifier::ImportSpecifier(specifier)
1290                    if specifier.imported.name().as_ref() == "default" =>
1291                {
1292                    push_unique_string(&mut imports.callables, specifier.local.name.to_string());
1293                }
1294                ImportDeclarationSpecifier::ImportNamespaceSpecifier(specifier) => {
1295                    push_unique_string(&mut imports.namespaces, specifier.local.name.to_string());
1296                }
1297                ImportDeclarationSpecifier::ImportSpecifier(_) => {}
1298            }
1299        }
1300    }
1301
1302    imports
1303}
1304
1305fn collect_vite_react_babel_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1306    if let Some(babel) = property_object(options, "babel") {
1307        collect_babel_plugin_and_preset_dependencies(babel, deps);
1308    }
1309}
1310
1311/// `@wyw-in-js/vite` passes `babelOptions` to Babel, which loads each named
1312/// plugin and preset.
1313fn collect_wyw_babel_options_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1314    if let Some(babel) = property_object(options, "babelOptions") {
1315        collect_babel_plugin_and_preset_dependencies(babel, deps);
1316    }
1317}
1318
1319/// `@vitejs/plugin-react-swc` passes `plugins` to SWC, which loads the package
1320/// at the head of each `[name, options]` tuple.
1321fn collect_vite_react_swc_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1322    let Some(prop) = find_property(options, "plugins") else {
1323        return;
1324    };
1325    let Expression::ArrayExpression(plugins) = &prop.value else {
1326        return;
1327    };
1328    for entry in &plugins.elements {
1329        let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
1330            continue;
1331        };
1332        if let Some(dep) = tuple
1333            .elements
1334            .first()
1335            .and_then(ArrayExpressionElement::as_expression)
1336            .and_then(expression_to_string)
1337            .and_then(|raw| config_string_package_name(&raw))
1338        {
1339            push_unique_string(deps, dep);
1340        }
1341    }
1342}
1343
1344fn collect_babel_plugin_and_preset_dependencies(
1345    babel: &ObjectExpression<'_>,
1346    deps: &mut Vec<String>,
1347) {
1348    for key in ["plugins", "presets"] {
1349        let Some(prop) = find_property(babel, key) else {
1350            continue;
1351        };
1352        for raw in collect_shallow_string_values(&prop.value) {
1353            if let Some(dep) = vite_react_babel_dependency_name(&raw) {
1354                push_unique_string(deps, dep);
1355            }
1356        }
1357    }
1358}
1359
1360fn vite_react_babel_dependency_name(raw: &str) -> Option<String> {
1361    let raw = raw.trim();
1362    let specifier = raw.strip_prefix("module:").unwrap_or(raw).trim();
1363    if specifier.is_empty()
1364        || specifier.starts_with('.')
1365        || specifier.starts_with('/')
1366        || specifier.contains(':')
1367        || specifier.contains('\\')
1368    {
1369        return None;
1370    }
1371    Some(crate::resolve::extract_package_name(specifier))
1372}
1373
1374fn push_unique_string(items: &mut Vec<String>, value: String) {
1375    if !items.contains(&value) {
1376        items.push(value);
1377    }
1378}
1379
1380/// Find the "config object": the object expression in the default export or module.exports.
1381///
1382/// Handles these patterns:
1383/// - `export default { ... }`
1384/// - `export default defineConfig({ ... })`
1385/// - `export default defineConfig(async () => ({ ... }))`
1386/// - `export default { ... } satisfies Config` / `export default { ... } as Config`
1387/// - `const config = { ... }; export default config;`
1388/// - `const config: Config = { ... }; export default config;`
1389/// - `module.exports = { ... }`
1390/// - Top-level JSON object (for .json files)
1391pub(crate) fn find_config_object<'a>(program: &'a Program) -> Option<&'a ObjectExpression<'a>> {
1392    for stmt in &program.body {
1393        match stmt {
1394            Statement::ExportDefaultDeclaration(decl) => {
1395                let expr: Option<&Expression> = match &decl.declaration {
1396                    ExportDefaultDeclarationKind::ObjectExpression(obj) => {
1397                        return Some(obj);
1398                    }
1399                    ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
1400                        return extract_object_from_function(func);
1401                    }
1402                    _ => decl.declaration.as_expression(),
1403                };
1404                if let Some(expr) = expr {
1405                    if let Some(obj) =
1406                        resolve_call_config_object(program, expr, MAX_CONFIG_WRAPPER_DEPTH)
1407                    {
1408                        return Some(obj);
1409                    }
1410                    if let Some(obj) = extract_object_from_expression(expr) {
1411                        return Some(obj);
1412                    }
1413                    if let Some(name) = unwrap_to_identifier_name(expr) {
1414                        return find_variable_init_object(program, name);
1415                    }
1416                    if let Some(obj) = resolve_wrapped_config_object(program, expr) {
1417                        return Some(obj);
1418                    }
1419                }
1420            }
1421            Statement::ExpressionStatement(expr_stmt) => {
1422                if let Expression::AssignmentExpression(assign) = &expr_stmt.expression
1423                    && is_module_exports_target(&assign.left)
1424                {
1425                    if let Some(obj) =
1426                        resolve_call_config_object(program, &assign.right, MAX_CONFIG_WRAPPER_DEPTH)
1427                    {
1428                        return Some(obj);
1429                    }
1430                    if let Some(obj) = extract_object_from_expression(&assign.right) {
1431                        return Some(obj);
1432                    }
1433                    if let Some(name) = unwrap_to_identifier_name(&assign.right) {
1434                        return find_variable_init_object(program, name);
1435                    }
1436                    return resolve_wrapped_config_object(program, &assign.right);
1437                }
1438            }
1439            _ => {}
1440        }
1441    }
1442
1443    if program.body.len() == 1
1444        && let Statement::ExpressionStatement(expr_stmt) = &program.body[0]
1445    {
1446        match &expr_stmt.expression {
1447            Expression::ObjectExpression(obj) => return Some(obj),
1448            Expression::ParenthesizedExpression(paren) => {
1449                if let Expression::ObjectExpression(obj) = &paren.expression {
1450                    return Some(obj);
1451                }
1452            }
1453            _ => {}
1454        }
1455    }
1456
1457    None
1458}
1459
1460/// Extract an `ObjectExpression` from an expression, handling wrapper patterns.
1461pub(crate) fn extract_object_from_expression<'a>(
1462    expr: &'a Expression<'a>,
1463) -> Option<&'a ObjectExpression<'a>> {
1464    match expr {
1465        Expression::ObjectExpression(obj) => Some(obj),
1466        Expression::CallExpression(call) => {
1467            for arg in &call.arguments {
1468                match arg {
1469                    Argument::ObjectExpression(obj) => return Some(obj),
1470                    // Both arrow forms reach here: the concise
1471                    // `defineConfig(() => ({ ... }))` and the block body
1472                    // `defineConfig(({ mode }) => { ...; return { ... }; })`.
1473                    // The block form is the common shape for configs that
1474                    // branch on the mode, and handling only the concise one
1475                    // made every such config invisible to extraction.
1476                    Argument::ArrowFunctionExpression(arrow) => {
1477                        if let Some(obj) = extract_object_from_arrow_function(arrow) {
1478                            return Some(obj);
1479                        }
1480                    }
1481                    Argument::FunctionExpression(func) => {
1482                        if let Some(obj) = extract_object_from_function(func) {
1483                            return Some(obj);
1484                        }
1485                    }
1486                    _ => {}
1487                }
1488            }
1489            None
1490        }
1491        Expression::ParenthesizedExpression(paren) => {
1492            extract_object_from_expression(&paren.expression)
1493        }
1494        Expression::TSSatisfiesExpression(ts_sat) => {
1495            extract_object_from_expression(&ts_sat.expression)
1496        }
1497        Expression::TSAsExpression(ts_as) => extract_object_from_expression(&ts_as.expression),
1498        Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
1499        Expression::FunctionExpression(func) => extract_object_from_function(func),
1500        _ => None,
1501    }
1502}
1503
1504fn extract_object_from_arrow_function<'a>(
1505    arrow: &'a ArrowFunctionExpression<'a>,
1506) -> Option<&'a ObjectExpression<'a>> {
1507    match &arrow.body {
1508        ArrowFunctionBody::FunctionBody(body) => extract_object_from_function_body(body),
1509        body => body
1510            .as_expression()
1511            .and_then(extract_object_from_expression),
1512    }
1513}
1514
1515fn extract_object_from_function<'a>(func: &'a Function<'a>) -> Option<&'a ObjectExpression<'a>> {
1516    func.body
1517        .as_ref()
1518        .and_then(|body| extract_object_from_function_body(body))
1519}
1520
1521/// Resolve the object a config callback returns.
1522///
1523/// A return at the body's own level is the callback's main config and always
1524/// wins, which keeps the overwhelmingly common `guard clause; return { ... }`
1525/// shape resolving to the real config rather than to the guard's early return.
1526/// Only a body with no top-level return falls back to searching branches, which
1527/// is the shape Vite documents for switching config by command:
1528/// `if (command === "serve") { return { ... } } else { return { ... } }`.
1529fn extract_object_from_function_body<'a>(
1530    body: &'a FunctionBody<'a>,
1531) -> Option<&'a ObjectExpression<'a>> {
1532    find_top_level_returned_object(&body.statements)
1533        .or_else(|| find_returned_object(&body.statements, MAX_CONFIG_BRANCH_DEPTH))
1534}
1535
1536/// Maximum control-flow nesting searched for a config `return`.
1537const MAX_CONFIG_BRANCH_DEPTH: u8 = 4;
1538
1539/// Find the first object returned by a statement at this exact level.
1540fn find_top_level_returned_object<'a>(
1541    statements: &'a [Statement<'a>],
1542) -> Option<&'a ObjectExpression<'a>> {
1543    statements.iter().find_map(|stmt| match stmt {
1544        Statement::ReturnStatement(ret) => ret
1545            .argument
1546            .as_ref()
1547            .and_then(|argument| extract_object_from_expression(argument)),
1548        _ => None,
1549    })
1550}
1551
1552/// Find the first returned object literal in `statements`, descending into
1553/// control flow.
1554///
1555/// Nested function and arrow bodies are deliberately not searched: their returns
1556/// belong to the inner function, not to the config callback.
1557///
1558/// The first return in source order wins. A config whose branches declare
1559/// different values therefore contributes only the first branch's.
1560fn find_returned_object<'a>(
1561    statements: &'a [Statement<'a>],
1562    depth: u8,
1563) -> Option<&'a ObjectExpression<'a>> {
1564    if depth == 0 {
1565        return None;
1566    }
1567    for stmt in statements {
1568        let found = match stmt {
1569            Statement::ReturnStatement(ret) => ret
1570                .argument
1571                .as_ref()
1572                .and_then(|argument| extract_object_from_expression(argument)),
1573            Statement::BlockStatement(block) => find_returned_object(&block.body, depth - 1),
1574            Statement::IfStatement(if_stmt) => {
1575                find_returned_object_in_statement(&if_stmt.consequent, depth - 1).or_else(|| {
1576                    if_stmt
1577                        .alternate
1578                        .as_ref()
1579                        .and_then(|alt| find_returned_object_in_statement(alt, depth - 1))
1580                })
1581            }
1582            Statement::TryStatement(try_stmt) => {
1583                find_returned_object(&try_stmt.block.body, depth - 1)
1584                    .or_else(|| {
1585                        try_stmt
1586                            .handler
1587                            .as_ref()
1588                            .and_then(|handler| find_returned_object(&handler.body.body, depth - 1))
1589                    })
1590                    .or_else(|| {
1591                        try_stmt
1592                            .finalizer
1593                            .as_ref()
1594                            .and_then(|finalizer| find_returned_object(&finalizer.body, depth - 1))
1595                    })
1596            }
1597            Statement::SwitchStatement(switch) => switch
1598                .cases
1599                .iter()
1600                .find_map(|case| find_returned_object(&case.consequent, depth - 1)),
1601            _ => None,
1602        };
1603        if found.is_some() {
1604            return found;
1605        }
1606    }
1607    None
1608}
1609
1610fn find_returned_object_in_statement<'a>(
1611    stmt: &'a Statement<'a>,
1612    depth: u8,
1613) -> Option<&'a ObjectExpression<'a>> {
1614    match stmt {
1615        Statement::BlockStatement(block) => find_returned_object(&block.body, depth),
1616        other => find_returned_object(std::slice::from_ref(other), depth),
1617    }
1618}
1619
1620/// Check if an assignment target is `module.exports`.
1621fn is_module_exports_target(target: &AssignmentTarget) -> bool {
1622    if let AssignmentTarget::StaticMemberExpression(member) = target
1623        && let Expression::Identifier(obj) = &member.object
1624    {
1625        return obj.name == "module" && member.property.name == "exports";
1626    }
1627    false
1628}
1629
1630/// Unwrap TS annotations and return the identifier name if the expression resolves to one.
1631///
1632/// Handles `config`, `config satisfies Type`, `config as Type`.
1633fn unwrap_to_identifier_name<'a>(expr: &'a Expression<'a>) -> Option<&'a str> {
1634    match expr {
1635        Expression::Identifier(id) => Some(&id.name),
1636        Expression::TSSatisfiesExpression(ts_sat) => unwrap_to_identifier_name(&ts_sat.expression),
1637        Expression::TSAsExpression(ts_as) => unwrap_to_identifier_name(&ts_as.expression),
1638        _ => None,
1639    }
1640}
1641
1642/// Find a top-level variable declaration by name and extract its init as an object expression.
1643///
1644/// Handles `const config = { ... }`, `const config: Type = { ... }`,
1645/// and `const config = defineConfig({ ... })`.
1646fn find_variable_init_object<'a>(
1647    program: &'a Program,
1648    name: &str,
1649) -> Option<&'a ObjectExpression<'a>> {
1650    for decl in top_level_variable_declarations(program) {
1651        for declarator in &decl.declarations {
1652            if let BindingPattern::BindingIdentifier(id) = &declarator.id
1653                && id.name == name
1654                && let Some(init) = &declarator.init
1655            {
1656                return extract_object_from_expression(init);
1657            }
1658        }
1659    }
1660    None
1661}
1662
1663/// The init expression of the first top-level variable declaration of `name`.
1664fn find_variable_init<'a>(program: &'a Program<'a>, name: &str) -> Option<&'a Expression<'a>> {
1665    top_level_variable_declarations(program)
1666        .flat_map(|decl| &decl.declarations)
1667        .find(|declarator| {
1668            matches!(&declarator.id, BindingPattern::BindingIdentifier(id) if id.name == name)
1669        })
1670        .and_then(|declarator| declarator.init.as_ref())
1671}
1672
1673/// The expression that the config file exports with `export default` or
1674/// `module.exports =`.
1675fn exported_config_expression<'a>(program: &'a Program<'a>) -> Option<&'a Expression<'a>> {
1676    program.body.iter().find_map(|stmt| match stmt {
1677        Statement::ExportDefaultDeclaration(decl) => decl.declaration.as_expression(),
1678        Statement::ExpressionStatement(expr_stmt) => match &expr_stmt.expression {
1679            Expression::AssignmentExpression(assign) if is_module_exports_target(&assign.left) => {
1680                Some(&assign.right)
1681            }
1682            _ => None,
1683        },
1684        _ => None,
1685    })
1686}
1687
1688/// The call that `expr` stands for, through parentheses, type assertions and
1689/// one top-level variable binding.
1690fn config_call<'a>(
1691    program: &'a Program<'a>,
1692    expr: &'a Expression<'a>,
1693    follow_binding: bool,
1694) -> Option<&'a CallExpression<'a>> {
1695    match expr {
1696        Expression::CallExpression(call) => Some(call),
1697        Expression::ParenthesizedExpression(paren) => {
1698            config_call(program, &paren.expression, follow_binding)
1699        }
1700        Expression::TSSatisfiesExpression(ts_sat) => {
1701            config_call(program, &ts_sat.expression, follow_binding)
1702        }
1703        Expression::TSAsExpression(ts_as) => {
1704            config_call(program, &ts_as.expression, follow_binding)
1705        }
1706        Expression::Identifier(id) if follow_binding => {
1707            config_call(program, find_variable_init(program, &id.name)?, false)
1708        }
1709        _ => None,
1710    }
1711}
1712
1713/// The arguments of an exported config call with more than one argument, such
1714/// as `defineConfig(base, { ... })`, in source order.
1715///
1716/// Some tools merge every argument into one config. Each argument resolves to
1717/// its object. An argument that does not resolve to one local object is
1718/// `None`, because it can set any key: a spread, an imported binding, or a
1719/// nested call that merges more than one argument. Returns `None` when the
1720/// exported config is not a call with more than one argument.
1721pub(crate) fn find_config_merge_arguments<'a>(
1722    program: &'a Program<'a>,
1723) -> Option<Vec<Option<&'a ObjectExpression<'a>>>> {
1724    let call = config_call(program, exported_config_expression(program)?, true)?;
1725    if call.arguments.len() < 2 {
1726        return None;
1727    }
1728    let resolve = |arg: &'a Argument<'a>| {
1729        let expr = arg.as_expression()?;
1730        if config_call(program, expr, true).is_some_and(|nested| nested.arguments.len() > 1) {
1731            return None;
1732        }
1733        resolve_config_argument(program, expr, MAX_CONFIG_WRAPPER_DEPTH)
1734    };
1735    Some(call.arguments.iter().map(resolve).collect())
1736}
1737
1738/// Every top-level variable declaration, including the one an
1739/// `export const NAME = ...` declaration wraps.
1740fn top_level_variable_declarations<'a>(
1741    program: &'a Program<'a>,
1742) -> impl Iterator<Item = &'a VariableDeclaration<'a>> {
1743    program.body.iter().filter_map(|stmt| match stmt {
1744        Statement::VariableDeclaration(decl) => Some(&**decl),
1745        Statement::ExportDeclaration(export) => match &export.declaration {
1746            Declaration::VariableDeclaration(decl) => Some(&**decl),
1747            _ => None,
1748        },
1749        _ => None,
1750    })
1751}
1752
1753/// The init expression of a top-level `const` or `let` that is the only binding
1754/// of `name` in the program and that no expression writes to.
1755///
1756/// `new ModuleFederationPlugin(mfConfig)` is the common shape for plugin options
1757/// that a config declares above the plugin list, where an inline-only reader fails.
1758///
1759/// The name resolves only when the program holds one binding of that name. A
1760/// second binding, a parameter of the same name, or a write to the binding means
1761/// the expression can name another value than the top-level one, so the
1762/// resolver declines. A caller that reads `push`-style calls itself can allow them.
1763pub(crate) fn find_stable_binding_init<'a>(
1764    program: &'a Program<'a>,
1765    name: &str,
1766    allow_mutating_calls: bool,
1767) -> Option<&'a Expression<'a>> {
1768    if !holds_one_stable_object(program, name, allow_mutating_calls) {
1769        return None;
1770    }
1771    find_variable_init_expression(program, name)
1772}
1773
1774/// Resolve a config object that is passed as a NAMED CONST to a wrapper call:
1775/// `export default withMDX(nextConfig)`, `module.exports = createJestConfig(cfg)`,
1776/// nested `withMDX(withFoo(nextConfig))`, and curried `compose(...)(nextConfig)`.
1777/// This is the call-argument analog of the bare `export default config` identifier
1778/// resolution already done via [`unwrap_to_identifier_name`] +
1779/// [`find_variable_init_object`]; it lets the official `@next/mdx` /
1780/// `withSentry(nextConfig)` / `next-compose-plugins` idioms resolve so their
1781/// `pageExtensions` / plugin config is extracted instead of silently dropped.
1782///
1783/// Returns the first argument (scanning nested wrapper calls) that resolves to a
1784/// local `const NAME = { ... }`. Inline object and callback arguments are handled
1785/// by [`resolve_call_config_object`], which the caller tries first.
1786fn resolve_wrapped_config_object<'a>(
1787    program: &'a Program,
1788    expr: &'a Expression<'a>,
1789) -> Option<&'a ObjectExpression<'a>> {
1790    let call = match expr {
1791        Expression::CallExpression(call) => call,
1792        Expression::ParenthesizedExpression(paren) => {
1793            return resolve_wrapped_config_object(program, &paren.expression);
1794        }
1795        Expression::TSSatisfiesExpression(ts_sat) => {
1796            return resolve_wrapped_config_object(program, &ts_sat.expression);
1797        }
1798        Expression::TSAsExpression(ts_as) => {
1799            return resolve_wrapped_config_object(program, &ts_as.expression);
1800        }
1801        _ => return None,
1802    };
1803    for arg in &call.arguments {
1804        let Some(arg_expr) = arg.as_expression() else {
1805            continue;
1806        };
1807        if let Some(name) = unwrap_to_identifier_name(arg_expr)
1808            && let Some(obj) = find_variable_init_object(program, name)
1809        {
1810            return Some(obj);
1811        }
1812        if let Some(obj) = resolve_wrapped_config_object(program, arg_expr) {
1813            return Some(obj);
1814        }
1815    }
1816    None
1817}
1818
1819/// Maximum wrapper nesting resolved by [`resolve_call_config_object`].
1820///
1821/// Covers the shapes seen in the wild (`defineConfig(mergeConfig(base, defineConfig({..})))`)
1822/// while keeping a hand-written config from driving unbounded recursion.
1823const MAX_CONFIG_WRAPPER_DEPTH: u8 = 3;
1824
1825/// Resolve the config object carried by a wrapper call, giving each argument the
1826/// full resolution chain in source order.
1827///
1828/// Config wrappers take the config first and their own options after it, as in
1829/// `withSentryConfig(nextConfig, { org, project })` or
1830/// `mergeConfig(viteConfig, defineConfig({ test }))`. Scanning the whole argument
1831/// list for the first object literal therefore picks up the wrapper's options
1832/// object whenever the config itself arrives as an identifier or a nested call,
1833/// silently reading the wrong object. Resolving argument by argument, chain-first,
1834/// keeps the config's own position winning.
1835fn resolve_call_config_object<'a>(
1836    program: &'a Program,
1837    expr: &'a Expression<'a>,
1838    depth: u8,
1839) -> Option<&'a ObjectExpression<'a>> {
1840    if depth == 0 {
1841        return None;
1842    }
1843    let call = match expr {
1844        Expression::CallExpression(call) => call,
1845        Expression::ParenthesizedExpression(paren) => {
1846            return resolve_call_config_object(program, &paren.expression, depth);
1847        }
1848        Expression::TSSatisfiesExpression(ts_sat) => {
1849            return resolve_call_config_object(program, &ts_sat.expression, depth);
1850        }
1851        Expression::TSAsExpression(ts_as) => {
1852            return resolve_call_config_object(program, &ts_as.expression, depth);
1853        }
1854        _ => return None,
1855    };
1856
1857    call.arguments
1858        .iter()
1859        .filter_map(oxc_ast::ast::Argument::as_expression)
1860        .find_map(|arg| resolve_config_argument(program, arg, depth))
1861}
1862
1863/// Resolve one wrapper argument to the object it stands for.
1864fn resolve_config_argument<'a>(
1865    program: &'a Program,
1866    expr: &'a Expression<'a>,
1867    depth: u8,
1868) -> Option<&'a ObjectExpression<'a>> {
1869    match expr {
1870        Expression::ObjectExpression(obj) => Some(obj),
1871        Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
1872        Expression::FunctionExpression(func) => extract_object_from_function(func),
1873        Expression::ParenthesizedExpression(paren) => {
1874            resolve_config_argument(program, &paren.expression, depth)
1875        }
1876        Expression::TSSatisfiesExpression(ts_sat) => {
1877            resolve_config_argument(program, &ts_sat.expression, depth)
1878        }
1879        Expression::TSAsExpression(ts_as) => {
1880            resolve_config_argument(program, &ts_as.expression, depth)
1881        }
1882        Expression::CallExpression(_) => resolve_call_config_object(program, expr, depth - 1),
1883        _ => unwrap_to_identifier_name(expr)
1884            .and_then(|name| find_variable_init_object(program, name)),
1885    }
1886}
1887
1888/// Find a named property in an object expression.
1889pub(crate) fn find_property<'a>(
1890    obj: &'a ObjectExpression<'a>,
1891    key: &str,
1892) -> Option<&'a ObjectProperty<'a>> {
1893    for prop in &obj.properties {
1894        if let ObjectPropertyKind::ObjectProperty(p) = prop
1895            && property_key_matches(&p.key, key)
1896        {
1897            return Some(p);
1898        }
1899    }
1900    None
1901}
1902
1903/// Check if a property key matches a string.
1904fn property_key_matches(key: &PropertyKey, name: &str) -> bool {
1905    match key {
1906        PropertyKey::StaticIdentifier(id) => id.name == name,
1907        PropertyKey::StringLiteral(s) => s.value == name,
1908        _ => false,
1909    }
1910}
1911
1912/// Get a string value from an object property.
1913fn get_object_string_property(obj: &ObjectExpression, key: &str) -> Option<String> {
1914    find_property(obj, key).and_then(|p| expression_to_string(&p.value))
1915}
1916
1917/// Get an array of strings from an object property.
1918fn get_object_string_array_property(obj: &ObjectExpression, key: &str) -> Vec<String> {
1919    find_property(obj, key)
1920        .map(|p| expression_to_string_array(&p.value))
1921        .unwrap_or_default()
1922}
1923
1924/// Navigate a nested property path and get a string array.
1925fn get_nested_string_array_from_object(
1926    obj: &ObjectExpression,
1927    path: &[&str],
1928) -> Option<Vec<String>> {
1929    if path.is_empty() {
1930        return None;
1931    }
1932    if path.len() == 1 {
1933        return Some(get_object_string_array_property(obj, path[0]));
1934    }
1935    let prop = find_property(obj, path[0])?;
1936    if let Expression::ObjectExpression(nested) = &prop.value {
1937        get_nested_string_array_from_object(nested, &path[1..])
1938    } else {
1939        None
1940    }
1941}
1942
1943/// Navigate a nested property path and get a string value.
1944fn get_nested_string_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
1945    if path.is_empty() {
1946        return None;
1947    }
1948    if path.len() == 1 {
1949        return get_object_string_property(obj, path[0]);
1950    }
1951    let prop = find_property(obj, path[0])?;
1952    if let Expression::ObjectExpression(nested) = &prop.value {
1953        get_nested_string_from_object(nested, &path[1..])
1954    } else {
1955        None
1956    }
1957}
1958
1959/// Navigate a nested property path and get a shell command value.
1960fn get_nested_command_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
1961    if path.is_empty() {
1962        return None;
1963    }
1964    if path.len() == 1 {
1965        return find_property(obj, path[0]).and_then(|prop| expression_to_command(&prop.value));
1966    }
1967    let prop = find_property(obj, path[0])?;
1968    if let Expression::ObjectExpression(nested) = &prop.value {
1969        get_nested_command_from_object(nested, &path[1..])
1970    } else {
1971        None
1972    }
1973}
1974
1975/// Convert an expression to a string if it's a string literal.
1976pub(crate) fn expression_to_string(expr: &Expression) -> Option<String> {
1977    match expr {
1978        Expression::StringLiteral(s) => Some(s.value.text().into_owned()),
1979        Expression::TemplateLiteral(t) if t.expressions.is_empty() => {
1980            t.quasis.first().map(|q| q.value.raw.to_string())
1981        }
1982        _ => None,
1983    }
1984}
1985
1986/// Convert an expression to a shell command when static command tokens are recoverable.
1987fn expression_to_command(expr: &Expression) -> Option<String> {
1988    match expr {
1989        Expression::StringLiteral(s) => Some(s.value.text().into_owned()),
1990        Expression::TemplateLiteral(template) => template_literal_to_command(template),
1991        Expression::ParenthesizedExpression(paren) => expression_to_command(&paren.expression),
1992        Expression::TSAsExpression(ts_as) => expression_to_command(&ts_as.expression),
1993        Expression::TSSatisfiesExpression(ts_sat) => expression_to_command(&ts_sat.expression),
1994        _ => None,
1995    }
1996}
1997
1998fn template_literal_to_command(template: &TemplateLiteral<'_>) -> Option<String> {
1999    let first = template.quasis.first()?.value.raw.as_str();
2000    if first.trim_start().is_empty() {
2001        return None;
2002    }
2003
2004    let mut command = String::new();
2005    for (idx, quasi) in template.quasis.iter().enumerate() {
2006        command.push_str(quasi.value.raw.as_str());
2007        if idx < template.expressions.len() {
2008            let next = template
2009                .quasis
2010                .get(idx + 1)
2011                .map_or("", |next| next.value.raw.as_str());
2012            if dynamic_template_boundary_splits_static_token(quasi.value.raw.as_str(), next) {
2013                return None;
2014            }
2015            command.push(' ');
2016        }
2017    }
2018
2019    Some(command)
2020}
2021
2022fn dynamic_template_boundary_splits_static_token(before: &str, after: &str) -> bool {
2023    before
2024        .chars()
2025        .next_back()
2026        .is_some_and(is_command_token_char)
2027        && after.chars().next().is_some_and(is_command_token_char)
2028}
2029
2030fn is_command_token_char(ch: char) -> bool {
2031    !ch.is_whitespace() && !matches!(ch, '&' | '|' | ';' | '"' | '\'')
2032}
2033
2034/// The identifiers that a path expression can resolve.
2035#[derive(Clone, Copy)]
2036enum PathScope<'p> {
2037    /// No identifier resolves.
2038    Bare,
2039    /// A call to a module-level path helper of this program resolves.
2040    Program(&'p Program<'p>),
2041    /// Inside a helper body, the parameter `name` holds the literal `value`.
2042    Param { name: &'p str, value: &'p str },
2043}
2044
2045/// Convert an expression to a path-like string if it's statically recoverable.
2046pub(crate) fn expression_to_path_string(expr: &Expression) -> Option<String> {
2047    path_string_in(expr, PathScope::Bare)
2048}
2049
2050fn path_string_in(expr: &Expression, scope: PathScope<'_>) -> Option<String> {
2051    match expr {
2052        Expression::ParenthesizedExpression(paren) => path_string_in(&paren.expression, scope),
2053        Expression::TSAsExpression(ts_as) => path_string_in(&ts_as.expression, scope),
2054        Expression::TSSatisfiesExpression(ts_sat) => path_string_in(&ts_sat.expression, scope),
2055        Expression::StaticMemberExpression(member) if member.property.name == "pathname" => {
2056            path_string_in(&member.object, scope)
2057        }
2058        Expression::CallExpression(call) => call_expression_to_path_string(call, scope),
2059        Expression::NewExpression(new_expr) => new_expression_to_path_string(new_expr, scope),
2060        _ => scoped_string(expr, scope),
2061    }
2062}
2063
2064/// A string literal, or the helper parameter that stands for one.
2065fn scoped_string(expr: &Expression, scope: PathScope<'_>) -> Option<String> {
2066    match (expr, scope) {
2067        (Expression::Identifier(id), PathScope::Param { name, value }) if id.name == name => {
2068            Some(value.to_string())
2069        }
2070        _ => expression_to_string(expr),
2071    }
2072}
2073
2074fn call_expression_to_path_string(call: &CallExpression, scope: PathScope<'_>) -> Option<String> {
2075    if let PathScope::Program(program) = scope
2076        && let Expression::Identifier(id) = &call.callee
2077        && let Some(path) = local_helper_call_path(program, &id.name, call)
2078    {
2079        return Some(path);
2080    }
2081
2082    if matches!(&call.callee, Expression::Identifier(id) if id.name == "fileURLToPath") {
2083        return call
2084            .arguments
2085            .first()
2086            .and_then(Argument::as_expression)
2087            .and_then(|arg| path_string_in(arg, scope));
2088    }
2089
2090    let callee_name = match &call.callee {
2091        Expression::Identifier(id) => Some(id.name.as_str()),
2092        Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
2093        _ => None,
2094    }?;
2095
2096    if !matches!(callee_name, "resolve" | "join") {
2097        return None;
2098    }
2099
2100    let mut segments = Vec::new();
2101    for (index, arg) in call.arguments.iter().enumerate() {
2102        let expr = arg.as_expression()?;
2103
2104        if is_dirname_anchor(expr) {
2105            if index == 0 {
2106                continue;
2107            }
2108            return None;
2109        }
2110
2111        segments.push(scoped_string(expr, scope)?);
2112    }
2113
2114    (!segments.is_empty()).then(|| join_path_segments(&segments))
2115}
2116
2117/// Evaluate a call to a module-level path helper with one literal argument.
2118///
2119/// Configs often declare a small helper such as
2120/// `const p = (rel) => fileURLToPath(new URL(rel, import.meta.url))` and call
2121/// it as `p("./src/main.ts")`. The helper body is evaluated with its parameter
2122/// bound to the literal argument. The body can not call another helper.
2123fn local_helper_call_path(program: &Program, name: &str, call: &CallExpression) -> Option<String> {
2124    let [argument] = call.arguments.as_slice() else {
2125        return None;
2126    };
2127    let value = expression_to_string(argument.as_expression()?)?;
2128    let (param, body) = find_local_path_helper(program, name)?;
2129    path_string_in(
2130        body,
2131        PathScope::Param {
2132            name: param,
2133            value: &value,
2134        },
2135    )
2136}
2137
2138/// Find a module-level function `name` with one simple parameter and a body
2139/// that only returns one expression. Return the parameter name and that
2140/// expression.
2141fn find_local_path_helper<'a>(
2142    program: &'a Program<'a>,
2143    name: &str,
2144) -> Option<(&'a str, &'a Expression<'a>)> {
2145    let declared = program.body.iter().find_map(|stmt| {
2146        let func = match stmt {
2147            Statement::FunctionDeclaration(func) => func,
2148            Statement::ExportDeclaration(export) => match &export.declaration {
2149                Declaration::FunctionDeclaration(func) => func,
2150                _ => return None,
2151            },
2152            _ => return None,
2153        };
2154        func.id
2155            .as_ref()
2156            .is_some_and(|id| id.name == name)
2157            .then_some(&**func)
2158    });
2159    if let Some(func) = declared {
2160        return function_helper_body(func);
2161    }
2162    match find_variable_init_expression(program, name)?.without_parentheses() {
2163        Expression::ArrowFunctionExpression(arrow) => {
2164            let param = single_simple_param(&arrow.params)?;
2165            let body = match &arrow.body {
2166                ArrowFunctionBody::FunctionBody(body) => single_returned_expression(body)?,
2167                body => body.as_expression()?,
2168            };
2169            Some((param, body))
2170        }
2171        Expression::FunctionExpression(func) => function_helper_body(func),
2172        _ => None,
2173    }
2174}
2175
2176fn function_helper_body<'a>(func: &'a Function<'a>) -> Option<(&'a str, &'a Expression<'a>)> {
2177    let param = single_simple_param(&func.params)?;
2178    let body = single_returned_expression(func.body.as_ref()?)?;
2179    Some((param, body))
2180}
2181
2182fn single_simple_param<'a>(params: &'a FormalParameters<'a>) -> Option<&'a str> {
2183    let [param] = params.items.as_slice() else {
2184        return None;
2185    };
2186    if params.rest.is_some() || param.initializer.is_some() {
2187        return None;
2188    }
2189    match &param.pattern {
2190        BindingPattern::BindingIdentifier(id) => Some(id.name.as_str()),
2191        _ => None,
2192    }
2193}
2194
2195fn single_returned_expression<'a>(body: &'a FunctionBody<'a>) -> Option<&'a Expression<'a>> {
2196    match body.statements.as_slice() {
2197        [Statement::ReturnStatement(ret)] => ret.argument.as_ref(),
2198        _ => None,
2199    }
2200}
2201
2202/// True when an expression is a "current directory" anchor: the `__dirname`
2203/// CommonJS global or its ESM equivalent `import.meta.dirname` (Node 20.11+).
2204/// As the leading argument of `resolve(...)` / `join(...)` it is dropped so the
2205/// remaining literal segments yield a config-directory-relative path.
2206fn is_dirname_anchor(expr: &Expression) -> bool {
2207    match expr {
2208        Expression::Identifier(id) => id.name == "__dirname",
2209        Expression::StaticMemberExpression(member) => {
2210            member.property.name == "dirname" && is_import_meta_expression(&member.object)
2211        }
2212        _ => false,
2213    }
2214}
2215
2216/// True for the `import.meta` meta-property, distinct from `new.target`.
2217fn is_import_meta_expression(expr: &Expression) -> bool {
2218    matches!(expr, Expression::ImportMeta(_))
2219}
2220
2221fn new_expression_to_path_string(new_expr: &NewExpression, scope: PathScope<'_>) -> Option<String> {
2222    if !matches!(&new_expr.callee, Expression::Identifier(id) if id.name == "URL") {
2223        return None;
2224    }
2225
2226    let source = new_expr
2227        .arguments
2228        .first()
2229        .and_then(Argument::as_expression)
2230        .and_then(|arg| scoped_string(arg, scope))?;
2231
2232    let base = new_expr
2233        .arguments
2234        .get(1)
2235        .and_then(Argument::as_expression)?;
2236    is_import_meta_url_expression(base).then_some(source)
2237}
2238
2239fn is_import_meta_url_expression(expr: &Expression) -> bool {
2240    if let Expression::StaticMemberExpression(member) = expr {
2241        member.property.name == "url"
2242            && matches!(
2243                member.object,
2244                Expression::ImportMeta(_) | Expression::NewTarget(_)
2245            )
2246    } else {
2247        false
2248    }
2249}
2250
2251fn join_path_segments(segments: &[String]) -> String {
2252    let mut joined = PathBuf::new();
2253    for segment in segments {
2254        joined.push(segment);
2255    }
2256    joined.to_string_lossy().replace('\\', "/")
2257}
2258
2259/// Extract an alias replacement string plus whether it was written as a plain
2260/// bare string literal. A bare string literal (not starting with `./`/`../`/`/`)
2261/// signals a potential package-to-package alias; a path expression
2262/// (`path.resolve(...)`, `path.join(...)`, `fileURLToPath(...)`, `new URL(...)`)
2263/// or a `./`-prefixed string is always a filesystem path. This is the
2264/// filesystem-free discriminator the package-to-package gate relies on.
2265fn alias_replacement_kinded(expr: &Expression, scope: PathScope<'_>) -> Option<(String, bool)> {
2266    match expr {
2267        Expression::ParenthesizedExpression(paren) => {
2268            alias_replacement_kinded(&paren.expression, scope)
2269        }
2270        Expression::TSAsExpression(ts_as) => alias_replacement_kinded(&ts_as.expression, scope),
2271        Expression::TSSatisfiesExpression(ts_sat) => {
2272            alias_replacement_kinded(&ts_sat.expression, scope)
2273        }
2274        Expression::StringLiteral(s) => {
2275            let value = s.value.text().into_owned();
2276            let is_bare =
2277                !value.starts_with("./") && !value.starts_with("../") && !value.starts_with('/');
2278            Some((value, is_bare))
2279        }
2280        // tsconfig `compilerOptions.paths` maps each key to an ARRAY of targets
2281        // (`{ "@/*": ["./src/*"] }`); take the first entry, matching the prior
2282        // non-kinded `expression_to_path_values().next()` behavior.
2283        Expression::ArrayExpression(arr) => arr
2284            .elements
2285            .iter()
2286            .find_map(ArrayExpressionElement::as_expression)
2287            .and_then(|element| alias_replacement_kinded(element, scope)),
2288        Expression::Identifier(id) => alias_constant::constant_replacement(id.name.as_str(), scope),
2289        _ => alias_entry::path_value(expr, scope).map(|value| (value, false)),
2290    }
2291}
2292
2293/// Maximum identifier-indirection hops the alias resolver follows before giving
2294/// up. Each local-variable or imported-binding resolution counts one hop. The
2295/// per-file `visited` set is the real cycle guard; this bound additionally
2296/// terminates pathological local self-references (`const a = a`). Real configs
2297/// rarely exceed one or two hops (`alias: importedAliases`).
2298const MAX_ALIAS_RESOLVE_DEPTH: usize = 8;
2299
2300/// Sibling-file extensions probed when an alias identifier is imported from a
2301/// relative specifier. Mirrors the JS/TS config extensions Vite/Vitest configs
2302/// and their shared alias modules use. `.js` first matches the common
2303/// JS-project case; the direct-as-written read happens before any probing. JSON
2304/// is intentionally excluded: it parses as a bare expression with no `export`,
2305/// so `find_exported_init` could never recover an alias literal from it.
2306const ALIAS_SIBLING_EXTS: [&str; 6] = ["js", "mjs", "cjs", "ts", "mts", "cts"];
2307
2308/// Resolve an alias expression into `(find, replacement, is_bare)` tuples,
2309/// following identifiers and expanding spreads.
2310///
2311/// Beyond the inline object (`{ '@': './src' }`) and array
2312/// (`[{ find, replacement }]`) forms, this handles the indirection shapes from
2313/// issue #811:
2314/// - an identifier bound to a local `const NAME = [...] | {...}`,
2315/// - an identifier imported from a relative sibling file
2316///   (`import { sharedAliases } from "./vite.shared.js"`), read one hop and
2317///   parsed for `export const NAME` / `export default` / `export { NAME }`,
2318/// - array spread elements (`[...a, ...b]`) and object spread properties
2319///   (`{ ...a, '@': './src' }`), each resolved recursively.
2320///
2321/// `config_path` is the file `expr` lives in (used to resolve relative sibling
2322/// imports). `visited` holds already-read sibling paths to break import cycles;
2323/// `depth` bounds identifier indirection via [`MAX_ALIAS_RESOLVE_DEPTH`].
2324fn resolve_alias_pairs_kinded(
2325    program: &Program,
2326    config_path: &Path,
2327    expr: &Expression,
2328    visited: &mut FxHashSet<PathBuf>,
2329    depth: usize,
2330) -> Vec<(String, String, bool)> {
2331    match expr {
2332        Expression::ParenthesizedExpression(paren) => {
2333            resolve_alias_pairs_kinded(program, config_path, &paren.expression, visited, depth)
2334        }
2335        Expression::TSAsExpression(ts_as) => {
2336            resolve_alias_pairs_kinded(program, config_path, &ts_as.expression, visited, depth)
2337        }
2338        Expression::TSSatisfiesExpression(ts_sat) => {
2339            resolve_alias_pairs_kinded(program, config_path, &ts_sat.expression, visited, depth)
2340        }
2341        Expression::ObjectExpression(obj) => {
2342            resolve_object_alias_pairs_kinded(program, config_path, obj, visited, depth)
2343        }
2344        Expression::ArrayExpression(arr) => {
2345            resolve_array_alias_pairs_kinded(program, config_path, arr, visited, depth)
2346        }
2347        Expression::Identifier(id) => {
2348            resolve_identifier_alias_pairs(program, config_path, id.name.as_str(), visited, depth)
2349        }
2350        _ => Vec::new(),
2351    }
2352}
2353
2354/// Resolve object-form alias pairs (`{ '@': './src', ...spread }`), expanding
2355/// spread properties recursively.
2356fn resolve_object_alias_pairs_kinded(
2357    program: &Program,
2358    config_path: &Path,
2359    obj: &ObjectExpression,
2360    visited: &mut FxHashSet<PathBuf>,
2361    depth: usize,
2362) -> Vec<(String, String, bool)> {
2363    let mut pairs = Vec::new();
2364    for prop in &obj.properties {
2365        match prop {
2366            ObjectPropertyKind::ObjectProperty(prop) => {
2367                if let Some(find) = property_key_to_string(&prop.key)
2368                    && let Some((replacement, is_bare)) =
2369                        alias_replacement_kinded(&prop.value, PathScope::Program(program))
2370                {
2371                    pairs.push((find, replacement, is_bare));
2372                }
2373            }
2374            // `{ ...sharedAliases, '@': './src' }`
2375            ObjectPropertyKind::SpreadProperty(spread) => {
2376                pairs.extend(resolve_alias_pairs_kinded(
2377                    program,
2378                    config_path,
2379                    &spread.argument,
2380                    visited,
2381                    depth,
2382                ));
2383            }
2384        }
2385    }
2386    pairs
2387}
2388
2389/// Resolve array-form alias pairs (`[{ find, replacement }, ...spread]`),
2390/// expanding spread elements recursively.
2391fn resolve_array_alias_pairs_kinded(
2392    program: &Program,
2393    config_path: &Path,
2394    arr: &ArrayExpression,
2395    visited: &mut FxHashSet<PathBuf>,
2396    depth: usize,
2397) -> Vec<(String, String, bool)> {
2398    let mut pairs = Vec::new();
2399    for element in &arr.elements {
2400        match element {
2401            // `[...sharedAliases, { find, replacement }]`
2402            ArrayExpressionElement::SpreadElement(spread) => {
2403                pairs.extend(resolve_alias_pairs_kinded(
2404                    program,
2405                    config_path,
2406                    &spread.argument,
2407                    visited,
2408                    depth,
2409                ));
2410            }
2411            _ => {
2412                if let Some(Expression::ObjectExpression(obj)) = element.as_expression()
2413                    && let Some(pair) =
2414                        alias_entry::object_alias_pair(obj, PathScope::Program(program))
2415                {
2416                    pairs.push(pair);
2417                }
2418            }
2419        }
2420    }
2421    pairs
2422}
2423
2424/// Resolve an identifier used as an alias value to its literal pairs, first by
2425/// local `const`/`let`/`var` binding, then by a one-hop relative import.
2426fn resolve_identifier_alias_pairs(
2427    program: &Program,
2428    config_path: &Path,
2429    name: &str,
2430    visited: &mut FxHashSet<PathBuf>,
2431    depth: usize,
2432) -> Vec<(String, String, bool)> {
2433    if depth >= MAX_ALIAS_RESOLVE_DEPTH {
2434        return Vec::new();
2435    }
2436    // Local `const NAME = [...] | {...}` (or `const NAME = otherIdentifier`).
2437    if let Some(init) = find_variable_init_expression(program, name) {
2438        return resolve_alias_pairs_kinded(program, config_path, init, visited, depth + 1);
2439    }
2440    // `import { NAME } from "./sibling"` / `import NAME from "./sibling"`.
2441    let Some((specifier, imported_name)) = find_relative_import_binding(program, name) else {
2442        return Vec::new();
2443    };
2444    resolve_imported_alias_pairs(
2445        config_path,
2446        &specifier,
2447        imported_name.as_deref(),
2448        visited,
2449        depth + 1,
2450    )
2451}
2452
2453/// Read a relative sibling file and resolve the alias literal it exports under
2454/// `imported_name` (`None` = default export).
2455fn resolve_imported_alias_pairs(
2456    config_path: &Path,
2457    specifier: &str,
2458    imported_name: Option<&str>,
2459    visited: &mut FxHashSet<PathBuf>,
2460    depth: usize,
2461) -> Vec<(String, String, bool)> {
2462    let Some((sibling_path, sibling_source)) = resolve_sibling_module(config_path, specifier)
2463    else {
2464        return Vec::new();
2465    };
2466    if !visited.insert(sibling_path.clone()) {
2467        return Vec::new();
2468    }
2469    extract_from_source(&sibling_source, &sibling_path, |program| {
2470        let init = find_exported_init(program, imported_name)?;
2471        let pairs = resolve_alias_pairs_kinded(program, &sibling_path, init, visited, depth);
2472        (!pairs.is_empty()).then_some(pairs)
2473    })
2474    .unwrap_or_default()
2475}
2476
2477/// Find a top-level variable declaration by name and return its init expression
2478/// (array, object, or another identifier). Covers bare `const NAME = ...` and
2479/// `export const NAME = ...`. Generalizes [`find_variable_init_object`] to any
2480/// init shape so the alias resolver can recurse on array/identifier inits.
2481fn find_variable_init_expression<'a>(
2482    program: &'a Program<'a>,
2483    name: &str,
2484) -> Option<&'a Expression<'a>> {
2485    for decl in top_level_variable_declarations(program) {
2486        for declarator in &decl.declarations {
2487            if let BindingPattern::BindingIdentifier(id) = &declarator.id
2488                && id.name == name
2489                && let Some(init) = &declarator.init
2490            {
2491                return Some(init);
2492            }
2493        }
2494    }
2495    None
2496}
2497
2498/// The expression a module exports as a whole: the right side of
2499/// `module.exports = ...`, or the expression of `export default ...`.
2500pub(crate) fn find_module_export_expression<'a>(
2501    program: &'a Program<'a>,
2502) -> Option<&'a Expression<'a>> {
2503    program.body.iter().find_map(|stmt| match stmt {
2504        Statement::ExportDefaultDeclaration(decl) => decl.declaration.as_expression(),
2505        Statement::ExpressionStatement(expr_stmt) => match &expr_stmt.expression {
2506            Expression::AssignmentExpression(assign) if is_module_exports_target(&assign.left) => {
2507                Some(&assign.right)
2508            }
2509            _ => None,
2510        },
2511        _ => None,
2512    })
2513}
2514
2515/// Find the init expression a sibling module exports under `name`
2516/// (`None` = default export). For named exports this covers both
2517/// `export const NAME = ...` and a local `const NAME = ...` later re-exported
2518/// via `export { NAME }` (both surface through [`find_variable_init_expression`]).
2519pub(crate) fn find_exported_init<'a>(
2520    program: &'a Program<'a>,
2521    name: Option<&str>,
2522) -> Option<&'a Expression<'a>> {
2523    match name {
2524        Some(name) => find_variable_init_expression(program, name),
2525        None => program.body.iter().find_map(|stmt| {
2526            if let Statement::ExportDefaultDeclaration(decl) = stmt {
2527                decl.declaration.as_expression()
2528            } else {
2529                None
2530            }
2531        }),
2532    }
2533}
2534
2535/// Find the import that binds local `name` to a RELATIVE module, returning the
2536/// specifier and the imported name (`None` for a default import). Bare-package
2537/// imports are intentionally skipped: reading a literal alias table out of
2538/// `node_modules` is not a real-world config shape.
2539pub(crate) fn find_relative_import_binding(
2540    program: &Program,
2541    name: &str,
2542) -> Option<(String, Option<String>)> {
2543    for stmt in &program.body {
2544        let Statement::ImportDeclaration(decl) = stmt else {
2545            continue;
2546        };
2547        let specifier = &*decl.source.value.text();
2548        if !is_relative_specifier(specifier) {
2549            continue;
2550        }
2551        let Some(specifiers) = &decl.specifiers else {
2552            continue;
2553        };
2554        for spec in specifiers {
2555            match spec {
2556                ImportDeclarationSpecifier::ImportSpecifier(spec) if spec.local.name == name => {
2557                    return Some((
2558                        specifier.to_string(),
2559                        Some(spec.imported.name().to_string()),
2560                    ));
2561                }
2562                ImportDeclarationSpecifier::ImportDefaultSpecifier(spec)
2563                    if spec.local.name == name =>
2564                {
2565                    return Some((specifier.to_string(), None));
2566                }
2567                _ => {}
2568            }
2569        }
2570    }
2571    None
2572}
2573
2574/// True for a relative/absolute module specifier (`./x`, `../x`, `/x`), the
2575/// shapes that point at a sibling file rather than an npm package.
2576pub(crate) fn is_relative_specifier(specifier: &str) -> bool {
2577    specifier.starts_with("./") || specifier.starts_with("../") || specifier.starts_with('/')
2578}
2579
2580/// Resolve a relative specifier against `config_path`'s directory to a readable
2581/// sibling file, returning the resolved path and its source. Tries the path as
2582/// written first (covers `./vite.shared.js`), then appends each known config
2583/// extension (covers extensionless `./vite.shared` and dotted basenames where
2584/// `Path::extension` would misread `.shared`), then an `index.*` directory file.
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 direct = parent.join(specifier);
2591    if let Ok(source) = std::fs::read_to_string(&direct) {
2592        return Some((direct, source));
2593    }
2594    for ext in ALIAS_SIBLING_EXTS {
2595        let candidate = parent.join(format!("{specifier}.{ext}"));
2596        if let Ok(source) = std::fs::read_to_string(&candidate) {
2597            return Some((candidate, source));
2598        }
2599    }
2600    for ext in ALIAS_SIBLING_EXTS {
2601        let candidate = direct.join(format!("index.{ext}"));
2602        if let Ok(source) = std::fs::read_to_string(&candidate) {
2603            return Some((candidate, source));
2604        }
2605    }
2606    None
2607}
2608
2609pub(crate) fn lexical_normalize(path: &Path) -> PathBuf {
2610    let mut normalized = PathBuf::new();
2611
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}