1use std::path::{Path, PathBuf};
6
7use crate::discover::project_read::{carry_project_root, config_project_root, read_project_file};
8use fallow_extract::{JsText, visitor::extract_import_from_callable};
9use oxc_ast::ast::*;
10use oxc_span::SourceType;
11use rustc_hash::FxHashSet;
12
13#[path = "config_parser_const_inline.rs"]
14mod const_inline;
15use const_inline::holds_one_stable_object;
16#[path = "config_parser_local_inline.rs"]
17mod local_inline;
18#[path = "config_parser_merge_config.rs"]
19mod merge_config;
20use merge_config::{read_each_config, read_last_config, read_last_match};
21#[path = "config_parser_multi_config.rs"]
22mod multi_config;
23use multi_config::find_default_export_array;
24#[path = "config_parser_string_values.rs"]
25mod string_values;
26pub(crate) use multi_config::{
27 extract_each_config_entries, extract_each_config_path_aliases,
28 extract_each_config_require_strings, extract_each_config_shallow_strings, find_config_objects,
29};
30use string_values::string_or_array_in;
31#[path = "config_parser_alias_constant.rs"]
32mod alias_constant;
33#[path = "config_parser_alias_entry.rs"]
34pub(super) mod alias_entry;
35#[path = "config_parser_vite_plugin_call.rs"]
36pub(crate) mod vite_plugin_call;
37pub(crate) use vite_plugin_call::extract_vite_plugin_call_option_path;
38use vite_plugin_call::is_plugin_binding_call;
39
40#[must_use]
42pub(crate) fn extract_imports(source: &str, path: &Path) -> Vec<String> {
43 extract_from_source(source, path, |program| {
44 let mut sources = Vec::new();
45 for stmt in &program.body {
46 if let Statement::ImportDeclaration(decl) = stmt {
47 sources.push(decl.source.value.text().into_owned());
48 }
49 }
50 Some(sources)
51 })
52 .unwrap_or_default()
53}
54
55#[must_use]
57pub(crate) fn extract_imports_and_requires(source: &str, path: &Path) -> Vec<String> {
58 extract_from_source(source, path, |program| {
59 let mut sources = Vec::new();
60 for stmt in &program.body {
61 match stmt {
62 Statement::ImportDeclaration(decl) => {
63 sources.push(decl.source.value.text().into_owned());
64 }
65 Statement::ExpressionStatement(expr) => {
66 if let Expression::CallExpression(call) = &expr.expression
67 && is_require_call(call)
68 && let Some(s) = get_require_source(call)
69 {
70 sources.push(s);
71 }
72 }
73 _ => {}
74 }
75 }
76 Some(sources)
77 })
78 .unwrap_or_default()
79}
80
81#[must_use]
83pub(crate) fn extract_config_string_array(
84 source: &str,
85 path: &Path,
86 prop_path: &[&str],
87) -> Vec<String> {
88 extract_from_source(source, path, |program| {
89 read_each_config(program, |obj| {
90 get_nested_string_array_from_object(obj, prop_path)
91 })
92 })
93 .unwrap_or_default()
94}
95
96#[must_use]
98pub(crate) fn extract_config_string(
99 source: &str,
100 path: &Path,
101 prop_path: &[&str],
102) -> Option<String> {
103 extract_from_source(source, path, |program| {
104 read_last_config(program, prop_path, get_nested_string_from_object)
105 })
106}
107
108#[must_use]
110pub(crate) fn extract_config_command(
111 source: &str,
112 path: &Path,
113 prop_path: &[&str],
114) -> Option<String> {
115 extract_from_source(source, path, |program| {
116 read_last_config(program, prop_path, get_nested_command_from_object)
117 })
118}
119
120#[must_use]
123pub(crate) fn extract_config_property_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
124 extract_from_source(source, path, |program| {
125 read_each_config(program, |obj| {
126 let mut values = Vec::new();
127 if let Some(prop) = find_property(obj, key) {
128 collect_all_string_values(&prop.value, &mut values);
129 }
130 Some(values)
131 })
132 })
133 .unwrap_or_default()
134}
135
136#[must_use]
138pub(crate) fn extract_config_shallow_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
139 extract_from_source(source, path, |program| {
140 read_each_config(program, |obj| {
141 let prop = find_property(obj, key)?;
142 Some(collect_shallow_string_values(&prop.value))
143 })
144 })
145 .unwrap_or_default()
146}
147
148#[must_use]
150pub(crate) fn extract_config_shallow_strings_or_object_property(
151 source: &str,
152 path: &Path,
153 key: &str,
154 object_property: &str,
155) -> Vec<String> {
156 extract_from_source(source, path, |program| {
157 read_each_config(program, |obj| {
158 let prop = find_property(obj, key)?;
159 Some(collect_shallow_string_or_object_property_values(
160 &prop.value,
161 object_property,
162 ))
163 })
164 })
165 .unwrap_or_default()
166}
167
168#[must_use]
170pub(crate) fn extract_config_nested_shallow_strings(
171 source: &str,
172 path: &Path,
173 outer_path: &[&str],
174 key: &str,
175) -> Vec<String> {
176 extract_from_source(source, path, |program| {
177 read_each_config(program, |obj| {
178 let nested = get_nested_expression(obj, outer_path)?;
179 if let Expression::ObjectExpression(nested_obj) = nested {
180 let prop = find_property(nested_obj, key)?;
181 Some(collect_shallow_string_values(&prop.value))
182 } else {
183 None
184 }
185 })
186 })
187 .unwrap_or_default()
188}
189
190pub(crate) fn property_expr<'a>(
192 obj: &'a ObjectExpression<'a>,
193 key: &str,
194) -> Option<&'a Expression<'a>> {
195 find_property(obj, key).map(|prop| &prop.value)
196}
197
198pub(crate) fn property_object<'a>(
200 obj: &'a ObjectExpression<'a>,
201 key: &str,
202) -> Option<&'a ObjectExpression<'a>> {
203 property_expr(obj, key).and_then(object_expression)
204}
205
206pub(crate) fn property_string(obj: &ObjectExpression<'_>, key: &str) -> Option<String> {
208 property_expr(obj, key).and_then(expression_to_string)
209}
210
211pub(crate) fn object_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ObjectExpression<'a>> {
213 match expr {
214 Expression::ObjectExpression(obj) => Some(obj),
215 Expression::ParenthesizedExpression(paren) => object_expression(&paren.expression),
216 Expression::TSSatisfiesExpression(ts_sat) => object_expression(&ts_sat.expression),
217 Expression::TSAsExpression(ts_as) => object_expression(&ts_as.expression),
218 _ => None,
219 }
220}
221
222pub(crate) fn array_expression<'a>(expr: &'a Expression<'a>) -> Option<&'a ArrayExpression<'a>> {
224 match expr {
225 Expression::ArrayExpression(arr) => Some(arr),
226 Expression::ParenthesizedExpression(paren) => array_expression(&paren.expression),
227 Expression::TSSatisfiesExpression(ts_sat) => array_expression(&ts_sat.expression),
228 Expression::TSAsExpression(ts_as) => array_expression(&ts_as.expression),
229 _ => None,
230 }
231}
232
233pub(crate) fn path_from_config_string(raw: &str) -> PathBuf {
236 PathBuf::from(raw.replace('\\', "/"))
237}
238
239pub(crate) fn path_to_config_string(path: &Path) -> String {
241 path.to_string_lossy().replace('\\', "/")
242}
243
244pub(crate) fn expression_to_path(expr: &Expression<'_>) -> Option<PathBuf> {
246 expression_to_path_string(expr).map(|path| path_from_config_string(&path))
247}
248
249pub(crate) fn expression_to_path_values(expr: &Expression<'_>) -> Vec<PathBuf> {
251 match expr {
252 Expression::ArrayExpression(arr) => arr
253 .elements
254 .iter()
255 .filter_map(|element| element.as_expression().and_then(expression_to_path))
256 .collect(),
257 _ => expression_to_path(expr).into_iter().collect(),
258 }
259}
260
261pub(crate) fn is_disabled_expression(expr: &Expression<'_>) -> bool {
263 matches!(expr, Expression::BooleanLiteral(boolean) if !boolean.value)
264 || matches!(expr, Expression::NullLiteral(_))
265}
266
267#[must_use]
269pub(crate) fn extract_config_truthy_bool_or_object(
270 source: &str,
271 path: &Path,
272 prop_path: &[&str],
273) -> bool {
274 extract_from_source(source, path, |program| {
275 read_last_config(program, prop_path, |obj, key_path| {
276 let expr = get_nested_expression(obj, key_path)?;
277 Some(is_truthy_bool_or_object(expr))
278 })
279 })
280 .unwrap_or(false)
281}
282
283fn is_truthy_bool_or_object(expr: &Expression<'_>) -> bool {
284 match expr {
285 Expression::BooleanLiteral(boolean) => boolean.value,
286 Expression::ObjectExpression(_) => true,
287 Expression::ParenthesizedExpression(paren) => is_truthy_bool_or_object(&paren.expression),
288 Expression::TSSatisfiesExpression(ts_sat) => is_truthy_bool_or_object(&ts_sat.expression),
289 Expression::TSAsExpression(ts_as) => is_truthy_bool_or_object(&ts_as.expression),
290 _ => false,
291 }
292}
293
294#[must_use]
296pub(crate) fn extract_config_object_keys(
297 source: &str,
298 path: &Path,
299 prop_path: &[&str],
300) -> Vec<String> {
301 extract_from_source(source, path, |program| {
302 read_each_config(program, |obj| get_nested_object_keys(obj, prop_path))
303 })
304 .unwrap_or_default()
305}
306
307#[must_use]
310pub(crate) fn extract_config_string_or_array(
311 source: &str,
312 path: &Path,
313 prop_path: &[&str],
314) -> Vec<String> {
315 extract_from_source(source, path, |program| {
316 read_each_config(program, |obj| {
317 get_nested_string_or_array(obj, prop_path, PathScope::Program(program))
318 })
319 })
320 .unwrap_or_default()
321}
322
323#[must_use]
330pub(crate) fn extract_config_array_or_object_string_or_array(
331 source: &str,
332 path: &Path,
333 prop_path: &[&str],
334) -> Vec<String> {
335 extract_from_source(source, path, |program| {
336 let Some(arr) = find_default_export_array(program) else {
337 return read_each_config(program, |obj| {
338 get_nested_string_or_array(obj, prop_path, PathScope::Program(program))
339 });
340 };
341 let values = arr
342 .elements
343 .iter()
344 .filter_map(|element| element.as_expression().and_then(object_expression))
345 .filter_map(|element_obj| {
346 get_nested_string_or_array(element_obj, prop_path, PathScope::Program(program))
347 })
348 .flatten()
349 .collect();
350 Some(values)
351 })
352 .unwrap_or_default()
353}
354
355#[must_use]
357pub(crate) fn extract_config_path(
358 source: &str,
359 path: &Path,
360 prop_path: &[&str],
361) -> Option<PathBuf> {
362 extract_from_source(source, path, |program| {
363 read_last_config(program, prop_path, |obj, key_path| {
364 let expr = get_nested_expression(obj, key_path)?;
365 expression_to_path(expr)
366 })
367 })
368}
369
370#[must_use]
372pub(crate) fn extract_config_array_nested_string_or_array(
373 source: &str,
374 path: &Path,
375 array_path: &[&str],
376 inner_path: &[&str],
377) -> Vec<String> {
378 extract_from_source(source, path, |program| {
379 read_each_config(program, |obj| {
380 let array_expr = get_nested_expression(obj, array_path)?;
381 let Expression::ArrayExpression(arr) = array_expr else {
382 return None;
383 };
384 let mut results = Vec::new();
385 for element in &arr.elements {
386 if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
387 && let Some(values) = get_nested_string_or_array(
388 element_obj,
389 inner_path,
390 PathScope::Program(program),
391 )
392 {
393 results.extend(values);
394 }
395 }
396 if results.is_empty() {
397 None
398 } else {
399 Some(results)
400 }
401 })
402 })
403 .unwrap_or_default()
404}
405
406#[must_use]
413pub(crate) fn extract_config_array_object_fields(
414 source: &str,
415 path: &Path,
416 array_path: &[&str],
417 keys: &[&str],
418) -> Vec<Vec<Vec<String>>> {
419 extract_from_source(source, path, |program| {
420 read_each_config(program, |obj| {
421 let Expression::ArrayExpression(arr) = get_nested_expression(obj, array_path)? else {
422 return None;
423 };
424 let elements = arr
425 .elements
426 .iter()
427 .filter_map(|element| match element.as_expression() {
428 Some(Expression::ObjectExpression(element_obj)) => Some(
429 keys.iter()
430 .map(|key| {
431 get_nested_string_or_array(
432 element_obj,
433 &[key],
434 PathScope::Program(program),
435 )
436 .unwrap_or_default()
437 })
438 .collect(),
439 ),
440 _ => None,
441 })
442 .collect();
443 Some(elements)
444 })
445 })
446 .unwrap_or_default()
447}
448
449#[must_use]
451pub(crate) fn extract_config_object_nested_string_or_array(
452 source: &str,
453 path: &Path,
454 object_path: &[&str],
455 inner_path: &[&str],
456) -> Vec<String> {
457 extract_config_object_nested(source, path, object_path, |value_obj| {
458 get_nested_string_or_array(value_obj, inner_path, PathScope::Bare)
459 })
460}
461
462#[must_use]
464pub(crate) fn extract_config_object_nested_strings(
465 source: &str,
466 path: &Path,
467 object_path: &[&str],
468 inner_path: &[&str],
469) -> Vec<String> {
470 extract_config_object_nested(source, path, object_path, |value_obj| {
471 get_nested_string_from_object(value_obj, inner_path).map(|s| vec![s])
472 })
473}
474
475fn extract_config_object_nested(
477 source: &str,
478 path: &Path,
479 object_path: &[&str],
480 extract_fn: impl Fn(&ObjectExpression<'_>) -> Option<Vec<String>> + Sync,
481) -> Vec<String> {
482 extract_from_source(source, path, |program| {
483 read_each_config(program, |obj| {
484 let obj_expr = get_nested_expression(obj, object_path)?;
485 let Expression::ObjectExpression(target_obj) = obj_expr else {
486 return None;
487 };
488 let mut results = Vec::new();
489 for prop in &target_obj.properties {
490 if let ObjectPropertyKind::ObjectProperty(p) = prop
491 && let Expression::ObjectExpression(value_obj) = &p.value
492 && let Some(values) = extract_fn(value_obj)
493 {
494 results.extend(values);
495 }
496 }
497 if results.is_empty() {
498 None
499 } else {
500 Some(results)
501 }
502 })
503 })
504 .unwrap_or_default()
505}
506
507#[must_use]
509pub(crate) fn extract_config_require_strings(source: &str, path: &Path, key: &str) -> Vec<String> {
510 extract_from_source(source, path, |program| {
511 read_each_config(program, |obj| {
512 let prop = find_property(obj, key)?;
513 Some(collect_require_sources(&prop.value))
514 })
515 })
516 .unwrap_or_default()
517}
518
519#[must_use]
521pub(crate) fn extract_config_aliases(
522 source: &str,
523 path: &Path,
524 prop_path: &[&str],
525) -> Vec<(String, String)> {
526 extract_config_aliases_kinded(source, path, prop_path)
527 .into_iter()
528 .map(|(find, replacement, _is_bare)| (find, replacement))
529 .collect()
530}
531
532#[must_use]
534pub(crate) fn extract_config_path_aliases(
535 source: &str,
536 path: &Path,
537 prop_path: &[&str],
538) -> Vec<(String, PathBuf)> {
539 extract_config_aliases_kinded(source, path, prop_path)
540 .into_iter()
541 .map(|(find, replacement, _is_bare)| (find, path_from_config_string(&replacement)))
542 .collect()
543}
544
545#[must_use]
547pub(crate) fn extract_config_aliases_kinded(
548 source: &str,
549 path: &Path,
550 prop_path: &[&str],
551) -> Vec<(String, String, bool)> {
552 extract_from_source(source, path, |program| {
553 read_each_config(program, |obj| {
554 let expr = get_nested_expression(obj, prop_path)?;
555 let mut visited = FxHashSet::default();
556 let aliases = resolve_alias_pairs_kinded(program, path, expr, &mut visited, 0);
557 (!aliases.is_empty()).then_some(aliases)
558 })
559 })
560 .unwrap_or_default()
561}
562
563#[must_use]
567pub(crate) fn extract_config_array_nested_aliases_kinded(
568 source: &str,
569 path: &Path,
570 array_path: &[&str],
571 alias_path: &[&str],
572) -> Vec<(String, String, bool)> {
573 extract_from_source(source, path, |program| {
574 read_each_config(program, |obj| {
575 let array_expr = get_nested_expression(obj, array_path)?;
576 let Expression::ArrayExpression(arr) = array_expr else {
577 return None;
578 };
579 let mut results = Vec::new();
580 for element in &arr.elements {
581 if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
582 && let Some(alias_expr) = get_nested_expression(element_obj, alias_path)
583 {
584 results.extend(alias_constant::expression_to_alias_pairs_kinded(
585 alias_expr,
586 PathScope::Program(program),
587 ));
588 }
589 }
590 (!results.is_empty()).then_some(results)
591 })
592 })
593 .unwrap_or_default()
594}
595
596#[must_use]
598pub(crate) fn extract_default_export_array_aliases_kinded(
599 source: &str,
600 path: &Path,
601 alias_path: &[&str],
602) -> Vec<(String, String, bool)> {
603 extract_from_source(source, path, |program| {
604 let arr = find_default_export_array(program)?;
605 let mut results = Vec::new();
606 for element in &arr.elements {
607 if let Some(Expression::ObjectExpression(element_obj)) = element.as_expression()
608 && let Some(alias_expr) = get_nested_expression(element_obj, alias_path)
609 {
610 results.extend(alias_constant::expression_to_alias_pairs_kinded(
611 alias_expr,
612 PathScope::Program(program),
613 ));
614 }
615 }
616 (!results.is_empty()).then_some(results)
617 })
618 .unwrap_or_default()
619}
620
621#[must_use]
623pub(crate) fn config_default_export_unreachable(source: &str, path: &Path) -> bool {
624 extract_from_source(source, path, |program| {
625 let reachable =
626 find_config_object(program).is_some() || find_default_export_array(program).is_some();
627 Some(reachable)
628 })
629 .is_some_and(|reachable| !reachable)
630}
631
632#[must_use]
638pub(crate) fn extract_config_array_object_strings(
639 source: &str,
640 path: &Path,
641 array_path: &[&str],
642 key: &str,
643) -> Vec<String> {
644 extract_from_source(source, path, |program| {
645 read_each_config(program, |obj| {
646 let array_expr = get_nested_expression(obj, array_path)?;
647 let Expression::ArrayExpression(arr) = array_expr else {
648 return None;
649 };
650
651 let mut results = Vec::new();
652 for element in &arr.elements {
653 let Some(expr) = element.as_expression() else {
654 continue;
655 };
656 match expr {
657 Expression::ObjectExpression(item) => {
658 if let Some(prop) = find_property(item, key)
659 && let Some(value) = expression_to_path_string(&prop.value)
660 {
661 results.push(value);
662 }
663 }
664 _ => {
665 if let Some(value) = expression_to_path_string(expr) {
666 results.push(value);
667 }
668 }
669 }
670 }
671
672 (!results.is_empty()).then_some(results)
673 })
674 })
675 .unwrap_or_default()
676}
677
678#[must_use]
683pub(crate) fn extract_config_static_dir_entries(
684 source: &str,
685 path: &Path,
686 array_path: &[&str],
687) -> Vec<(String, Option<String>)> {
688 extract_from_source(source, path, |program| {
689 read_each_config(program, |obj| {
690 let array_expr = get_nested_expression(obj, array_path)?;
691 let Expression::ArrayExpression(arr) = array_expr else {
692 return None;
693 };
694
695 let mut results = Vec::new();
696 for element in &arr.elements {
697 let Some(expr) = element.as_expression() else {
698 continue;
699 };
700 match expr {
701 Expression::ObjectExpression(item) => {
702 if let Some(from) = property_string(item, "from") {
703 let to = property_string(item, "to");
704 results.push((from, to));
705 }
706 }
707 _ => {
708 if let Some(from) = expression_to_path_string(expr) {
709 results.push((from, None));
710 }
711 }
712 }
713 }
714
715 (!results.is_empty()).then_some(results)
716 })
717 })
718 .unwrap_or_default()
719}
720
721#[must_use]
723pub(crate) fn extract_config_array_object_command_pairs(
724 source: &str,
725 path: &Path,
726 array_path: &[&str],
727 primary_key: &str,
728 secondary_key: &str,
729) -> Vec<(String, Option<String>)> {
730 extract_from_source(source, path, |program| {
731 read_each_config(program, |obj| {
732 let array_expr = get_nested_expression(obj, array_path)?;
733 let Expression::ArrayExpression(arr) = array_expr else {
734 return None;
735 };
736
737 let mut results = Vec::new();
738 for element in &arr.elements {
739 let Some(Expression::ObjectExpression(item)) = element.as_expression() else {
740 continue;
741 };
742 let Some(primary) = find_property(item, primary_key)
743 .and_then(|prop| expression_to_command(&prop.value))
744 else {
745 continue;
746 };
747 let secondary = find_property(item, secondary_key)
748 .and_then(|prop| expression_to_path_string(&prop.value));
749 results.push((primary, secondary));
750 }
751
752 (!results.is_empty()).then_some(results)
753 })
754 })
755 .unwrap_or_default()
756}
757
758#[must_use]
804pub(crate) fn extract_lazy_imports_in_array(
805 source: &str,
806 path: &Path,
807 prop_path: &[&str],
808) -> Vec<String> {
809 extract_from_source(source, path, |program| {
810 read_each_config(program, |obj| {
811 let array_expr = get_nested_expression(obj, prop_path)?;
812 let Expression::ArrayExpression(arr) = array_expr else {
813 return None;
814 };
815 let mut specs = Vec::new();
816 for element in &arr.elements {
817 let Some(expr) = element.as_expression() else {
818 continue;
819 };
820 if let Some(spec) = lazy_import_specifier(expr) {
821 specs.push(spec);
822 }
823 }
824 (!specs.is_empty()).then_some(specs)
825 })
826 })
827 .unwrap_or_default()
828}
829
830fn lazy_import_specifier(expr: &Expression<'_>) -> Option<String> {
843 let callable = match expr {
844 Expression::ObjectExpression(obj) => &find_property(obj, "file")?.value,
845 _ => expr,
846 };
847 let import_expr = extract_import_from_callable(callable)?;
848 expression_to_string(&import_expr.source)
849}
850
851#[must_use]
856pub(crate) fn extract_config_array_tuple_heads(
857 source: &str,
858 path: &Path,
859 array_path: &[&str],
860) -> Vec<String> {
861 extract_from_source(source, path, |program| {
862 read_each_config(program, |obj| {
863 let Expression::ArrayExpression(entries) = get_nested_expression(obj, array_path)?
864 else {
865 return None;
866 };
867 let heads = entries
868 .elements
869 .iter()
870 .filter_map(|entry| match entry.as_expression() {
871 Some(Expression::ArrayExpression(tuple)) => tuple
872 .elements
873 .first()
874 .and_then(ArrayExpressionElement::as_expression)
875 .and_then(expression_to_string),
876 _ => None,
877 })
878 .collect();
879 Some(heads)
880 })
881 })
882 .unwrap_or_default()
883}
884
885#[must_use]
892fn extract_config_plugin_option_string(
893 source: &str,
894 path: &Path,
895 plugins_path: &[&str],
896 plugin_name: &str,
897 option_key: &str,
898) -> Option<String> {
899 extract_from_source(source, path, |program| {
900 read_last_match(program, |obj| {
901 let plugins_expr = get_nested_expression(obj, plugins_path)?;
902 let Expression::ArrayExpression(plugins) = plugins_expr else {
903 return None;
904 };
905
906 for entry in &plugins.elements {
907 let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
908 continue;
909 };
910 let Some(plugin_expr) = tuple
911 .elements
912 .first()
913 .and_then(ArrayExpressionElement::as_expression)
914 else {
915 continue;
916 };
917 if expression_to_string(plugin_expr).as_deref() != Some(plugin_name) {
918 continue;
919 }
920
921 let Some(options_expr) = tuple
922 .elements
923 .get(1)
924 .and_then(ArrayExpressionElement::as_expression)
925 else {
926 continue;
927 };
928 let Expression::ObjectExpression(options_obj) = options_expr else {
929 continue;
930 };
931 let option = find_property(options_obj, option_key)?;
932 return expression_to_path_string(&option.value);
933 }
934
935 None
936 })
937 })
938}
939
940#[must_use]
942pub(crate) fn extract_config_plugin_option_string_from_paths(
943 source: &str,
944 path: &Path,
945 plugin_paths: &[&[&str]],
946 plugin_name: &str,
947 option_key: &str,
948) -> Option<String> {
949 plugin_paths.iter().find_map(|plugins_path| {
950 extract_config_plugin_option_string(source, path, plugins_path, plugin_name, option_key)
951 })
952}
953
954struct VitePluginOptionReader {
956 package: &'static str,
957 read: fn(&ObjectExpression<'_>, &mut Vec<String>),
958}
959
960const VITE_PLUGIN_OPTION_READERS: &[VitePluginOptionReader] = &[
964 VitePluginOptionReader {
965 package: "@vitejs/plugin-react",
966 read: collect_vite_react_babel_dependencies,
967 },
968 VitePluginOptionReader {
969 package: "@vitejs/plugin-react-swc",
970 read: collect_vite_react_swc_dependencies,
971 },
972 VitePluginOptionReader {
973 package: "@wyw-in-js/vite",
974 read: collect_wyw_babel_options_dependencies,
975 },
976];
977
978const MAX_VITE_PLUGIN_WRAPPER_DEPTH: usize = 3;
981
982#[must_use]
987pub(crate) fn extract_vite_plugin_option_dependencies(source: &str, path: &Path) -> Vec<String> {
988 extract_from_source(source, path, |program| {
989 let bindings: Vec<(PluginImportBindings, &VitePluginOptionReader)> =
990 VITE_PLUGIN_OPTION_READERS
991 .iter()
992 .map(|reader| {
993 (
994 collect_plugin_import_bindings(program, reader.package),
995 reader,
996 )
997 })
998 .filter(|(imports, _)| !imports.is_empty())
999 .collect();
1000 if bindings.is_empty() {
1001 return None;
1002 }
1003
1004 read_each_config(program, |obj| {
1005 let plugins = get_nested_expression(obj, &["plugins"])?;
1006 let Expression::ArrayExpression(plugin_array) = plugins else {
1007 return None;
1008 };
1009
1010 let mut deps = Vec::new();
1011 for element in &plugin_array.elements {
1012 if let Some(Expression::CallExpression(call)) = element.as_expression() {
1013 read_vite_plugin_call(call, &bindings, 0, &mut deps);
1014 }
1015 }
1016
1017 (!deps.is_empty()).then_some(deps)
1018 })
1019 })
1020 .unwrap_or_default()
1021}
1022
1023fn read_vite_plugin_call(
1024 call: &CallExpression<'_>,
1025 bindings: &[(PluginImportBindings, &VitePluginOptionReader)],
1026 depth: usize,
1027 deps: &mut Vec<String>,
1028) {
1029 if let Some((_, reader)) = bindings
1030 .iter()
1031 .find(|(imports, _)| is_plugin_binding_call(call, imports))
1032 {
1033 if let Some(Expression::ObjectExpression(options)) =
1034 call.arguments.first().and_then(Argument::as_expression)
1035 {
1036 (reader.read)(options, deps);
1037 }
1038 return;
1039 }
1040 if depth >= MAX_VITE_PLUGIN_WRAPPER_DEPTH {
1041 return;
1042 }
1043 for argument in &call.arguments {
1044 if let Some(Expression::CallExpression(inner)) = argument.as_expression() {
1045 read_vite_plugin_call(inner, bindings, depth + 1, deps);
1046 }
1047 }
1048}
1049
1050#[must_use]
1054pub(crate) fn config_string_package_name(raw: &str) -> Option<String> {
1055 let specifier = raw.trim();
1056 is_package_specifier(specifier).then(|| crate::resolve::extract_package_name(specifier))
1057}
1058
1059#[must_use]
1062pub(crate) fn extract_config_swc_plugin_dependencies(
1063 source: &str,
1064 path: &Path,
1065 array_path: &[&str],
1066) -> Vec<String> {
1067 extract_config_array_tuple_heads(source, path, array_path)
1068 .iter()
1069 .filter_map(|raw| config_string_package_name(raw))
1070 .fold(Vec::new(), |mut deps, dep| {
1071 push_unique_string(&mut deps, dep);
1072 deps
1073 })
1074}
1075
1076#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1078enum LeadingSlash {
1079 RootRelative,
1081 Filesystem,
1083}
1084
1085#[must_use]
1094pub(crate) fn normalize_config_path_buf(
1095 raw: impl AsRef<Path>,
1096 config_path: &Path,
1097 root: &Path,
1098) -> Option<PathBuf> {
1099 normalize_path_value(raw.as_ref(), config_path, root, LeadingSlash::RootRelative)
1100}
1101
1102#[must_use]
1106pub(crate) fn normalize_filesystem_config_path_buf(
1107 raw: impl AsRef<Path>,
1108 config_path: &Path,
1109 root: &Path,
1110) -> Option<PathBuf> {
1111 normalize_path_value(raw.as_ref(), config_path, root, LeadingSlash::Filesystem)
1112}
1113
1114fn normalize_path_value(
1115 raw: &Path,
1116 config_path: &Path,
1117 root: &Path,
1118 leading_slash: LeadingSlash,
1119) -> Option<PathBuf> {
1120 if raw.as_os_str().is_empty() {
1121 return None;
1122 }
1123
1124 let raw_string = path_to_config_string(raw);
1125 let raw_path = Path::new(&raw_string);
1126 let root_relative_slash =
1127 leading_slash == LeadingSlash::RootRelative && raw_string.starts_with('/');
1128 let absolute = raw_path
1129 .is_absolute()
1130 .then(|| lexical_normalize(raw_path))
1131 .filter(|absolute| absolute.starts_with(root))
1132 .filter(|absolute| !(root_relative_slash && (absolute == root || root_in_root(root))));
1133 let candidate = if let Some(absolute) = absolute {
1134 absolute
1135 } else if let Some(stripped) = raw_string.strip_prefix('/') {
1136 match leading_slash {
1137 LeadingSlash::RootRelative => lexical_normalize(&root.join(stripped)),
1138 LeadingSlash::Filesystem => return None,
1139 }
1140 } else if raw_path.is_absolute() {
1141 return None;
1142 } else {
1143 let base = config_path.parent().unwrap_or(root);
1144 lexical_normalize(&base.join(raw_path))
1145 };
1146
1147 let relative = candidate.strip_prefix(root).ok()?;
1148 (!relative.as_os_str().is_empty()).then(|| relative.to_path_buf())
1149}
1150
1151fn root_in_root(root: &Path) -> bool {
1155 let root_string = path_to_config_string(root);
1156 let Some(stripped) = root_string.strip_prefix('/') else {
1157 return false;
1158 };
1159 !stripped.is_empty() && root.join(stripped).is_dir()
1160}
1161
1162#[must_use]
1165pub(crate) fn normalize_filesystem_config_path(
1166 raw: impl AsRef<Path>,
1167 config_path: &Path,
1168 root: &Path,
1169) -> Option<String> {
1170 normalize_filesystem_config_path_buf(raw, config_path, root)
1171 .map(|path| path_to_config_string(&path))
1172}
1173
1174#[must_use]
1176pub(crate) fn normalize_config_path(
1177 raw: impl AsRef<Path>,
1178 config_path: &Path,
1179 root: &Path,
1180) -> Option<String> {
1181 normalize_config_path_buf(raw, config_path, root).map(|path| path_to_config_string(&path))
1182}
1183
1184pub(crate) fn parent_relative_config_path(
1194 target: &str,
1195 config_path: &Path,
1196 root: &Path,
1197) -> Option<String> {
1198 if !target.starts_with("../") {
1199 return None;
1200 }
1201 let directory = config_path.parent().unwrap_or(root);
1202 let candidate = lexical_normalize(&directory.join(target));
1203 let root = lexical_normalize(root);
1204 let mut ancestor = root.as_path();
1205 let mut climbs = 0;
1206 while !candidate.starts_with(ancestor) {
1207 ancestor = ancestor.parent()?;
1208 climbs += 1;
1209 }
1210 let rest = candidate.strip_prefix(ancestor).ok()?;
1211 (climbs > 0 && !rest.as_os_str().is_empty())
1212 .then(|| format!("{}{}", "../".repeat(climbs), path_to_config_string(rest)))
1213}
1214
1215pub(crate) fn extract_from_source<T: Send>(
1229 source: &str,
1230 path: &Path,
1231 extractor: impl FnOnce(&Program) -> Option<T> + Send,
1232) -> Option<T> {
1233 let is_json = path
1234 .extension()
1235 .is_some_and(|ext| ext == "json" || ext == "jsonc");
1236 if is_json {
1237 let wrapped = wrap_json_as_expression(source);
1238 return fallow_extract::parse_bounded_or_default(&wrapped, SourceType::mjs(), |parsed| {
1239 extractor(&parsed.program)
1240 });
1241 }
1242 let source_type = SourceType::from_path(path).unwrap_or_default();
1243 let parse = carry_project_root(|| {
1244 let allocator = oxc_allocator::Allocator::default();
1245 let mut parsed = oxc_parser::Parser::new(&allocator, source, source_type).parse();
1246 const_inline::with_inlined_program(&allocator, &mut parsed.program, source.len(), extractor)
1247 });
1248 fallow_extract::parse_bounded(source, parse).flatten()
1249}
1250
1251pub(crate) fn wrap_json_as_expression(source: &str) -> String {
1255 format!("({source}\n)")
1256}
1257
1258#[derive(Default)]
1261struct PluginImportBindings {
1262 callables: Vec<String>,
1263 namespaces: Vec<String>,
1264}
1265
1266impl PluginImportBindings {
1267 fn is_empty(&self) -> bool {
1268 self.callables.is_empty() && self.namespaces.is_empty()
1269 }
1270}
1271
1272fn collect_plugin_import_bindings(program: &Program<'_>, package: &str) -> PluginImportBindings {
1273 let mut imports = PluginImportBindings::default();
1274
1275 for stmt in &program.body {
1276 let Statement::ImportDeclaration(decl) = stmt else {
1277 continue;
1278 };
1279 if decl.source.value != package {
1280 continue;
1281 }
1282 let Some(specifiers) = &decl.specifiers else {
1283 continue;
1284 };
1285 for specifier in specifiers {
1286 match specifier {
1287 ImportDeclarationSpecifier::ImportDefaultSpecifier(specifier) => {
1288 push_unique_string(&mut imports.callables, specifier.local.name.to_string());
1289 }
1290 ImportDeclarationSpecifier::ImportSpecifier(specifier)
1291 if specifier.imported.name().as_ref() == "default" =>
1292 {
1293 push_unique_string(&mut imports.callables, specifier.local.name.to_string());
1294 }
1295 ImportDeclarationSpecifier::ImportNamespaceSpecifier(specifier) => {
1296 push_unique_string(&mut imports.namespaces, specifier.local.name.to_string());
1297 }
1298 ImportDeclarationSpecifier::ImportSpecifier(_) => {}
1299 }
1300 }
1301 }
1302
1303 imports
1304}
1305
1306fn collect_vite_react_babel_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1307 if let Some(babel) = property_object(options, "babel") {
1308 collect_babel_plugin_and_preset_dependencies(babel, deps);
1309 }
1310}
1311
1312fn collect_wyw_babel_options_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1315 if let Some(babel) = property_object(options, "babelOptions") {
1316 collect_babel_plugin_and_preset_dependencies(babel, deps);
1317 }
1318}
1319
1320fn collect_vite_react_swc_dependencies(options: &ObjectExpression<'_>, deps: &mut Vec<String>) {
1323 let Some(prop) = find_property(options, "plugins") else {
1324 return;
1325 };
1326 let Expression::ArrayExpression(plugins) = &prop.value else {
1327 return;
1328 };
1329 for entry in &plugins.elements {
1330 let Some(Expression::ArrayExpression(tuple)) = entry.as_expression() else {
1331 continue;
1332 };
1333 if let Some(dep) = tuple
1334 .elements
1335 .first()
1336 .and_then(ArrayExpressionElement::as_expression)
1337 .and_then(expression_to_string)
1338 .and_then(|raw| config_string_package_name(&raw))
1339 {
1340 push_unique_string(deps, dep);
1341 }
1342 }
1343}
1344
1345fn collect_babel_plugin_and_preset_dependencies(
1346 babel: &ObjectExpression<'_>,
1347 deps: &mut Vec<String>,
1348) {
1349 for key in ["plugins", "presets"] {
1350 let Some(prop) = find_property(babel, key) else {
1351 continue;
1352 };
1353 for raw in collect_shallow_string_values(&prop.value) {
1354 if let Some(dep) = vite_react_babel_dependency_name(&raw) {
1355 push_unique_string(deps, dep);
1356 }
1357 }
1358 }
1359}
1360
1361fn vite_react_babel_dependency_name(raw: &str) -> Option<String> {
1362 let raw = raw.trim();
1363 let specifier = raw.strip_prefix("module:").unwrap_or(raw).trim();
1364 if specifier.is_empty()
1365 || specifier.starts_with('.')
1366 || specifier.starts_with('/')
1367 || specifier.contains(':')
1368 || specifier.contains('\\')
1369 {
1370 return None;
1371 }
1372 Some(crate::resolve::extract_package_name(specifier))
1373}
1374
1375fn push_unique_string(items: &mut Vec<String>, value: String) {
1376 if !items.contains(&value) {
1377 items.push(value);
1378 }
1379}
1380
1381pub(crate) fn find_config_object<'a>(program: &'a Program) -> Option<&'a ObjectExpression<'a>> {
1393 for stmt in &program.body {
1394 match stmt {
1395 Statement::ExportDefaultDeclaration(decl) => {
1396 let expr: Option<&Expression> = match &decl.declaration {
1397 ExportDefaultDeclarationKind::ObjectExpression(obj) => {
1398 return Some(obj);
1399 }
1400 ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
1401 return extract_object_from_function(func);
1402 }
1403 _ => decl.declaration.as_expression(),
1404 };
1405 if let Some(expr) = expr {
1406 if let Some(obj) =
1407 resolve_call_config_object(program, expr, MAX_CONFIG_WRAPPER_DEPTH)
1408 {
1409 return Some(obj);
1410 }
1411 if let Some(obj) = extract_object_from_expression(expr) {
1412 return Some(obj);
1413 }
1414 if let Some(name) = unwrap_to_identifier_name(expr) {
1415 return find_variable_init_object(program, name);
1416 }
1417 if let Some(obj) = resolve_wrapped_config_object(program, expr) {
1418 return Some(obj);
1419 }
1420 }
1421 }
1422 Statement::ExpressionStatement(expr_stmt) => {
1423 if let Expression::AssignmentExpression(assign) = &expr_stmt.expression
1424 && is_module_exports_target(&assign.left)
1425 {
1426 if let Some(obj) =
1427 resolve_call_config_object(program, &assign.right, MAX_CONFIG_WRAPPER_DEPTH)
1428 {
1429 return Some(obj);
1430 }
1431 if let Some(obj) = extract_object_from_expression(&assign.right) {
1432 return Some(obj);
1433 }
1434 if let Some(name) = unwrap_to_identifier_name(&assign.right) {
1435 return find_variable_init_object(program, name);
1436 }
1437 return resolve_wrapped_config_object(program, &assign.right);
1438 }
1439 }
1440 _ => {}
1441 }
1442 }
1443
1444 if program.body.len() == 1
1445 && let Statement::ExpressionStatement(expr_stmt) = &program.body[0]
1446 {
1447 match &expr_stmt.expression {
1448 Expression::ObjectExpression(obj) => return Some(obj),
1449 Expression::ParenthesizedExpression(paren) => {
1450 if let Expression::ObjectExpression(obj) = &paren.expression {
1451 return Some(obj);
1452 }
1453 }
1454 _ => {}
1455 }
1456 }
1457
1458 None
1459}
1460
1461pub(crate) fn extract_object_from_expression<'a>(
1463 expr: &'a Expression<'a>,
1464) -> Option<&'a ObjectExpression<'a>> {
1465 match expr {
1466 Expression::ObjectExpression(obj) => Some(obj),
1467 Expression::CallExpression(call) => {
1468 for arg in &call.arguments {
1469 match arg {
1470 Argument::ObjectExpression(obj) => return Some(obj),
1471 Argument::ArrowFunctionExpression(arrow) => {
1478 if let Some(obj) = extract_object_from_arrow_function(arrow) {
1479 return Some(obj);
1480 }
1481 }
1482 Argument::FunctionExpression(func) => {
1483 if let Some(obj) = extract_object_from_function(func) {
1484 return Some(obj);
1485 }
1486 }
1487 _ => {}
1488 }
1489 }
1490 None
1491 }
1492 Expression::ParenthesizedExpression(paren) => {
1493 extract_object_from_expression(&paren.expression)
1494 }
1495 Expression::TSSatisfiesExpression(ts_sat) => {
1496 extract_object_from_expression(&ts_sat.expression)
1497 }
1498 Expression::TSAsExpression(ts_as) => extract_object_from_expression(&ts_as.expression),
1499 Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
1500 Expression::FunctionExpression(func) => extract_object_from_function(func),
1501 _ => None,
1502 }
1503}
1504
1505fn extract_object_from_arrow_function<'a>(
1506 arrow: &'a ArrowFunctionExpression<'a>,
1507) -> Option<&'a ObjectExpression<'a>> {
1508 match &arrow.body {
1509 ArrowFunctionBody::FunctionBody(body) => extract_object_from_function_body(body),
1510 body => body
1511 .as_expression()
1512 .and_then(extract_object_from_expression),
1513 }
1514}
1515
1516fn extract_object_from_function<'a>(func: &'a Function<'a>) -> Option<&'a ObjectExpression<'a>> {
1517 func.body
1518 .as_ref()
1519 .and_then(|body| extract_object_from_function_body(body))
1520}
1521
1522fn extract_object_from_function_body<'a>(
1531 body: &'a FunctionBody<'a>,
1532) -> Option<&'a ObjectExpression<'a>> {
1533 find_top_level_returned_object(&body.statements)
1534 .or_else(|| find_returned_object(&body.statements, MAX_CONFIG_BRANCH_DEPTH))
1535}
1536
1537const MAX_CONFIG_BRANCH_DEPTH: u8 = 4;
1539
1540fn find_top_level_returned_object<'a>(
1542 statements: &'a [Statement<'a>],
1543) -> Option<&'a ObjectExpression<'a>> {
1544 statements.iter().find_map(|stmt| match stmt {
1545 Statement::ReturnStatement(ret) => ret
1546 .argument
1547 .as_ref()
1548 .and_then(|argument| extract_object_from_expression(argument)),
1549 _ => None,
1550 })
1551}
1552
1553fn find_returned_object<'a>(
1562 statements: &'a [Statement<'a>],
1563 depth: u8,
1564) -> Option<&'a ObjectExpression<'a>> {
1565 if depth == 0 {
1566 return None;
1567 }
1568 for stmt in statements {
1569 let found = match stmt {
1570 Statement::ReturnStatement(ret) => ret
1571 .argument
1572 .as_ref()
1573 .and_then(|argument| extract_object_from_expression(argument)),
1574 Statement::BlockStatement(block) => find_returned_object(&block.body, depth - 1),
1575 Statement::IfStatement(if_stmt) => {
1576 find_returned_object_in_statement(&if_stmt.consequent, depth - 1).or_else(|| {
1577 if_stmt
1578 .alternate
1579 .as_ref()
1580 .and_then(|alt| find_returned_object_in_statement(alt, depth - 1))
1581 })
1582 }
1583 Statement::TryStatement(try_stmt) => {
1584 find_returned_object(&try_stmt.block.body, depth - 1)
1585 .or_else(|| {
1586 try_stmt
1587 .handler
1588 .as_ref()
1589 .and_then(|handler| find_returned_object(&handler.body.body, depth - 1))
1590 })
1591 .or_else(|| {
1592 try_stmt
1593 .finalizer
1594 .as_ref()
1595 .and_then(|finalizer| find_returned_object(&finalizer.body, depth - 1))
1596 })
1597 }
1598 Statement::SwitchStatement(switch) => switch
1599 .cases
1600 .iter()
1601 .find_map(|case| find_returned_object(&case.consequent, depth - 1)),
1602 _ => None,
1603 };
1604 if found.is_some() {
1605 return found;
1606 }
1607 }
1608 None
1609}
1610
1611fn find_returned_object_in_statement<'a>(
1612 stmt: &'a Statement<'a>,
1613 depth: u8,
1614) -> Option<&'a ObjectExpression<'a>> {
1615 match stmt {
1616 Statement::BlockStatement(block) => find_returned_object(&block.body, depth),
1617 other => find_returned_object(std::slice::from_ref(other), depth),
1618 }
1619}
1620
1621fn is_module_exports_target(target: &AssignmentTarget) -> bool {
1623 if let AssignmentTarget::StaticMemberExpression(member) = target
1624 && let Expression::Identifier(obj) = &member.object
1625 {
1626 return obj.name == "module" && member.property.name == "exports";
1627 }
1628 false
1629}
1630
1631fn unwrap_to_identifier_name<'a>(expr: &'a Expression<'a>) -> Option<&'a str> {
1635 match expr {
1636 Expression::Identifier(id) => Some(&id.name),
1637 Expression::TSSatisfiesExpression(ts_sat) => unwrap_to_identifier_name(&ts_sat.expression),
1638 Expression::TSAsExpression(ts_as) => unwrap_to_identifier_name(&ts_as.expression),
1639 _ => None,
1640 }
1641}
1642
1643fn find_variable_init_object<'a>(
1648 program: &'a Program,
1649 name: &str,
1650) -> Option<&'a ObjectExpression<'a>> {
1651 for decl in top_level_variable_declarations(program) {
1652 for declarator in &decl.declarations {
1653 if let BindingPattern::BindingIdentifier(id) = &declarator.id
1654 && id.name == name
1655 && let Some(init) = &declarator.init
1656 {
1657 return extract_object_from_expression(init);
1658 }
1659 }
1660 }
1661 None
1662}
1663
1664fn find_variable_init<'a>(program: &'a Program<'a>, name: &str) -> Option<&'a Expression<'a>> {
1666 top_level_variable_declarations(program)
1667 .flat_map(|decl| &decl.declarations)
1668 .find(|declarator| {
1669 matches!(&declarator.id, BindingPattern::BindingIdentifier(id) if id.name == name)
1670 })
1671 .and_then(|declarator| declarator.init.as_ref())
1672}
1673
1674fn exported_config_expression<'a>(program: &'a Program<'a>) -> Option<&'a Expression<'a>> {
1677 program.body.iter().find_map(|stmt| match stmt {
1678 Statement::ExportDefaultDeclaration(decl) => decl.declaration.as_expression(),
1679 Statement::ExpressionStatement(expr_stmt) => match &expr_stmt.expression {
1680 Expression::AssignmentExpression(assign) if is_module_exports_target(&assign.left) => {
1681 Some(&assign.right)
1682 }
1683 _ => None,
1684 },
1685 _ => None,
1686 })
1687}
1688
1689fn config_call<'a>(
1692 program: &'a Program<'a>,
1693 expr: &'a Expression<'a>,
1694 follow_binding: bool,
1695) -> Option<&'a CallExpression<'a>> {
1696 match expr {
1697 Expression::CallExpression(call) => Some(call),
1698 Expression::ParenthesizedExpression(paren) => {
1699 config_call(program, &paren.expression, follow_binding)
1700 }
1701 Expression::TSSatisfiesExpression(ts_sat) => {
1702 config_call(program, &ts_sat.expression, follow_binding)
1703 }
1704 Expression::TSAsExpression(ts_as) => {
1705 config_call(program, &ts_as.expression, follow_binding)
1706 }
1707 Expression::Identifier(id) if follow_binding => {
1708 config_call(program, find_variable_init(program, &id.name)?, false)
1709 }
1710 _ => None,
1711 }
1712}
1713
1714pub(crate) fn find_config_merge_arguments<'a>(
1723 program: &'a Program<'a>,
1724) -> Option<Vec<Option<&'a ObjectExpression<'a>>>> {
1725 let call = config_call(program, exported_config_expression(program)?, true)?;
1726 if call.arguments.len() < 2 {
1727 return None;
1728 }
1729 let resolve = |arg: &'a Argument<'a>| {
1730 let expr = arg.as_expression()?;
1731 if config_call(program, expr, true).is_some_and(|nested| nested.arguments.len() > 1) {
1732 return None;
1733 }
1734 resolve_config_argument(program, expr, MAX_CONFIG_WRAPPER_DEPTH)
1735 };
1736 Some(call.arguments.iter().map(resolve).collect())
1737}
1738
1739fn top_level_variable_declarations<'a>(
1742 program: &'a Program<'a>,
1743) -> impl Iterator<Item = &'a VariableDeclaration<'a>> {
1744 program.body.iter().filter_map(|stmt| match stmt {
1745 Statement::VariableDeclaration(decl) => Some(&**decl),
1746 Statement::ExportDeclaration(export) => match &export.declaration {
1747 Declaration::VariableDeclaration(decl) => Some(&**decl),
1748 _ => None,
1749 },
1750 _ => None,
1751 })
1752}
1753
1754pub(crate) fn find_stable_binding_init<'a>(
1765 program: &'a Program<'a>,
1766 name: &str,
1767 allow_mutating_calls: bool,
1768) -> Option<&'a Expression<'a>> {
1769 if !holds_one_stable_object(program, name, allow_mutating_calls) {
1770 return None;
1771 }
1772 find_variable_init_expression(program, name)
1773}
1774
1775fn resolve_wrapped_config_object<'a>(
1788 program: &'a Program,
1789 expr: &'a Expression<'a>,
1790) -> Option<&'a ObjectExpression<'a>> {
1791 let call = match expr {
1792 Expression::CallExpression(call) => call,
1793 Expression::ParenthesizedExpression(paren) => {
1794 return resolve_wrapped_config_object(program, &paren.expression);
1795 }
1796 Expression::TSSatisfiesExpression(ts_sat) => {
1797 return resolve_wrapped_config_object(program, &ts_sat.expression);
1798 }
1799 Expression::TSAsExpression(ts_as) => {
1800 return resolve_wrapped_config_object(program, &ts_as.expression);
1801 }
1802 _ => return None,
1803 };
1804 for arg in &call.arguments {
1805 let Some(arg_expr) = arg.as_expression() else {
1806 continue;
1807 };
1808 if let Some(name) = unwrap_to_identifier_name(arg_expr)
1809 && let Some(obj) = find_variable_init_object(program, name)
1810 {
1811 return Some(obj);
1812 }
1813 if let Some(obj) = resolve_wrapped_config_object(program, arg_expr) {
1814 return Some(obj);
1815 }
1816 }
1817 None
1818}
1819
1820const MAX_CONFIG_WRAPPER_DEPTH: u8 = 3;
1825
1826fn resolve_call_config_object<'a>(
1837 program: &'a Program,
1838 expr: &'a Expression<'a>,
1839 depth: u8,
1840) -> Option<&'a ObjectExpression<'a>> {
1841 if depth == 0 {
1842 return None;
1843 }
1844 let call = match expr {
1845 Expression::CallExpression(call) => call,
1846 Expression::ParenthesizedExpression(paren) => {
1847 return resolve_call_config_object(program, &paren.expression, depth);
1848 }
1849 Expression::TSSatisfiesExpression(ts_sat) => {
1850 return resolve_call_config_object(program, &ts_sat.expression, depth);
1851 }
1852 Expression::TSAsExpression(ts_as) => {
1853 return resolve_call_config_object(program, &ts_as.expression, depth);
1854 }
1855 _ => return None,
1856 };
1857
1858 call.arguments
1859 .iter()
1860 .filter_map(oxc_ast::ast::Argument::as_expression)
1861 .find_map(|arg| resolve_config_argument(program, arg, depth))
1862}
1863
1864fn resolve_config_argument<'a>(
1866 program: &'a Program,
1867 expr: &'a Expression<'a>,
1868 depth: u8,
1869) -> Option<&'a ObjectExpression<'a>> {
1870 match expr {
1871 Expression::ObjectExpression(obj) => Some(obj),
1872 Expression::ArrowFunctionExpression(arrow) => extract_object_from_arrow_function(arrow),
1873 Expression::FunctionExpression(func) => extract_object_from_function(func),
1874 Expression::ParenthesizedExpression(paren) => {
1875 resolve_config_argument(program, &paren.expression, depth)
1876 }
1877 Expression::TSSatisfiesExpression(ts_sat) => {
1878 resolve_config_argument(program, &ts_sat.expression, depth)
1879 }
1880 Expression::TSAsExpression(ts_as) => {
1881 resolve_config_argument(program, &ts_as.expression, depth)
1882 }
1883 Expression::CallExpression(_) => resolve_call_config_object(program, expr, depth - 1),
1884 _ => unwrap_to_identifier_name(expr)
1885 .and_then(|name| find_variable_init_object(program, name)),
1886 }
1887}
1888
1889pub(crate) fn find_property<'a>(
1891 obj: &'a ObjectExpression<'a>,
1892 key: &str,
1893) -> Option<&'a ObjectProperty<'a>> {
1894 for prop in &obj.properties {
1895 if let ObjectPropertyKind::ObjectProperty(p) = prop
1896 && property_key_matches(&p.key, key)
1897 {
1898 return Some(p);
1899 }
1900 }
1901 None
1902}
1903
1904fn property_key_matches(key: &PropertyKey, name: &str) -> bool {
1906 match key {
1907 PropertyKey::StaticIdentifier(id) => id.name == name,
1908 PropertyKey::StringLiteral(s) => s.value == name,
1909 _ => false,
1910 }
1911}
1912
1913fn get_object_string_property(obj: &ObjectExpression, key: &str) -> Option<String> {
1915 find_property(obj, key).and_then(|p| expression_to_string(&p.value))
1916}
1917
1918fn get_object_string_array_property(obj: &ObjectExpression, key: &str) -> Vec<String> {
1920 find_property(obj, key)
1921 .map(|p| expression_to_string_array(&p.value))
1922 .unwrap_or_default()
1923}
1924
1925fn get_nested_string_array_from_object(
1927 obj: &ObjectExpression,
1928 path: &[&str],
1929) -> Option<Vec<String>> {
1930 if path.is_empty() {
1931 return None;
1932 }
1933 if path.len() == 1 {
1934 return Some(get_object_string_array_property(obj, path[0]));
1935 }
1936 let prop = find_property(obj, path[0])?;
1937 if let Expression::ObjectExpression(nested) = &prop.value {
1938 get_nested_string_array_from_object(nested, &path[1..])
1939 } else {
1940 None
1941 }
1942}
1943
1944fn get_nested_string_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
1946 if path.is_empty() {
1947 return None;
1948 }
1949 if path.len() == 1 {
1950 return get_object_string_property(obj, path[0]);
1951 }
1952 let prop = find_property(obj, path[0])?;
1953 if let Expression::ObjectExpression(nested) = &prop.value {
1954 get_nested_string_from_object(nested, &path[1..])
1955 } else {
1956 None
1957 }
1958}
1959
1960fn get_nested_command_from_object(obj: &ObjectExpression, path: &[&str]) -> Option<String> {
1962 if path.is_empty() {
1963 return None;
1964 }
1965 if path.len() == 1 {
1966 return find_property(obj, path[0]).and_then(|prop| expression_to_command(&prop.value));
1967 }
1968 let prop = find_property(obj, path[0])?;
1969 if let Expression::ObjectExpression(nested) = &prop.value {
1970 get_nested_command_from_object(nested, &path[1..])
1971 } else {
1972 None
1973 }
1974}
1975
1976pub(crate) fn expression_to_string(expr: &Expression) -> Option<String> {
1978 match expr {
1979 Expression::StringLiteral(s) => Some(s.value.text().into_owned()),
1980 Expression::TemplateLiteral(t) if t.expressions.is_empty() => {
1981 t.quasis.first().map(|q| q.value.raw.to_string())
1982 }
1983 _ => None,
1984 }
1985}
1986
1987fn expression_to_command(expr: &Expression) -> Option<String> {
1989 match expr {
1990 Expression::StringLiteral(s) => Some(s.value.text().into_owned()),
1991 Expression::TemplateLiteral(template) => template_literal_to_command(template),
1992 Expression::ParenthesizedExpression(paren) => expression_to_command(&paren.expression),
1993 Expression::TSAsExpression(ts_as) => expression_to_command(&ts_as.expression),
1994 Expression::TSSatisfiesExpression(ts_sat) => expression_to_command(&ts_sat.expression),
1995 _ => None,
1996 }
1997}
1998
1999fn template_literal_to_command(template: &TemplateLiteral<'_>) -> Option<String> {
2000 let first = template.quasis.first()?.value.raw.as_str();
2001 if first.trim_start().is_empty() {
2002 return None;
2003 }
2004
2005 let mut command = String::new();
2006 for (idx, quasi) in template.quasis.iter().enumerate() {
2007 command.push_str(quasi.value.raw.as_str());
2008 if idx < template.expressions.len() {
2009 let next = template
2010 .quasis
2011 .get(idx + 1)
2012 .map_or("", |next| next.value.raw.as_str());
2013 if dynamic_template_boundary_splits_static_token(quasi.value.raw.as_str(), next) {
2014 return None;
2015 }
2016 command.push(' ');
2017 }
2018 }
2019
2020 Some(command)
2021}
2022
2023fn dynamic_template_boundary_splits_static_token(before: &str, after: &str) -> bool {
2024 before
2025 .chars()
2026 .next_back()
2027 .is_some_and(is_command_token_char)
2028 && after.chars().next().is_some_and(is_command_token_char)
2029}
2030
2031fn is_command_token_char(ch: char) -> bool {
2032 !ch.is_whitespace() && !matches!(ch, '&' | '|' | ';' | '"' | '\'')
2033}
2034
2035#[derive(Clone, Copy)]
2037enum PathScope<'p> {
2038 Bare,
2040 Program(&'p Program<'p>),
2042 Param { name: &'p str, value: &'p str },
2044}
2045
2046pub(crate) fn expression_to_path_string(expr: &Expression) -> Option<String> {
2048 path_string_in(expr, PathScope::Bare)
2049}
2050
2051fn path_string_in(expr: &Expression, scope: PathScope<'_>) -> Option<String> {
2052 match expr {
2053 Expression::ParenthesizedExpression(paren) => path_string_in(&paren.expression, scope),
2054 Expression::TSAsExpression(ts_as) => path_string_in(&ts_as.expression, scope),
2055 Expression::TSSatisfiesExpression(ts_sat) => path_string_in(&ts_sat.expression, scope),
2056 Expression::StaticMemberExpression(member) if member.property.name == "pathname" => {
2057 path_string_in(&member.object, scope)
2058 }
2059 Expression::CallExpression(call) => call_expression_to_path_string(call, scope),
2060 Expression::NewExpression(new_expr) => new_expression_to_path_string(new_expr, scope),
2061 _ => scoped_string(expr, scope),
2062 }
2063}
2064
2065fn scoped_string(expr: &Expression, scope: PathScope<'_>) -> Option<String> {
2067 match (expr, scope) {
2068 (Expression::Identifier(id), PathScope::Param { name, value }) if id.name == name => {
2069 Some(value.to_string())
2070 }
2071 _ => expression_to_string(expr),
2072 }
2073}
2074
2075fn call_expression_to_path_string(call: &CallExpression, scope: PathScope<'_>) -> Option<String> {
2076 if let PathScope::Program(program) = scope
2077 && let Expression::Identifier(id) = &call.callee
2078 && let Some(path) = local_helper_call_path(program, &id.name, call)
2079 {
2080 return Some(path);
2081 }
2082
2083 if matches!(&call.callee, Expression::Identifier(id) if id.name == "fileURLToPath") {
2084 return call
2085 .arguments
2086 .first()
2087 .and_then(Argument::as_expression)
2088 .and_then(|arg| path_string_in(arg, scope));
2089 }
2090
2091 let callee_name = match &call.callee {
2092 Expression::Identifier(id) => Some(id.name.as_str()),
2093 Expression::StaticMemberExpression(member) => Some(member.property.name.as_str()),
2094 _ => None,
2095 }?;
2096
2097 if !matches!(callee_name, "resolve" | "join") {
2098 return None;
2099 }
2100
2101 let mut segments = Vec::new();
2102 for (index, arg) in call.arguments.iter().enumerate() {
2103 let expr = arg.as_expression()?;
2104
2105 if is_dirname_anchor(expr) {
2106 if index == 0 {
2107 continue;
2108 }
2109 return None;
2110 }
2111
2112 segments.push(scoped_string(expr, scope)?);
2113 }
2114
2115 (!segments.is_empty()).then(|| join_path_segments(&segments))
2116}
2117
2118fn local_helper_call_path(program: &Program, name: &str, call: &CallExpression) -> Option<String> {
2125 let [argument] = call.arguments.as_slice() else {
2126 return None;
2127 };
2128 let value = expression_to_string(argument.as_expression()?)?;
2129 let (param, body) = find_local_path_helper(program, name)?;
2130 path_string_in(
2131 body,
2132 PathScope::Param {
2133 name: param,
2134 value: &value,
2135 },
2136 )
2137}
2138
2139fn find_local_path_helper<'a>(
2143 program: &'a Program<'a>,
2144 name: &str,
2145) -> Option<(&'a str, &'a Expression<'a>)> {
2146 let declared = program.body.iter().find_map(|stmt| {
2147 let func = match stmt {
2148 Statement::FunctionDeclaration(func) => func,
2149 Statement::ExportDeclaration(export) => match &export.declaration {
2150 Declaration::FunctionDeclaration(func) => func,
2151 _ => return None,
2152 },
2153 _ => return None,
2154 };
2155 func.id
2156 .as_ref()
2157 .is_some_and(|id| id.name == name)
2158 .then_some(&**func)
2159 });
2160 if let Some(func) = declared {
2161 return function_helper_body(func);
2162 }
2163 match find_variable_init_expression(program, name)?.without_parentheses() {
2164 Expression::ArrowFunctionExpression(arrow) => {
2165 let param = single_simple_param(&arrow.params)?;
2166 let body = match &arrow.body {
2167 ArrowFunctionBody::FunctionBody(body) => single_returned_expression(body)?,
2168 body => body.as_expression()?,
2169 };
2170 Some((param, body))
2171 }
2172 Expression::FunctionExpression(func) => function_helper_body(func),
2173 _ => None,
2174 }
2175}
2176
2177fn function_helper_body<'a>(func: &'a Function<'a>) -> Option<(&'a str, &'a Expression<'a>)> {
2178 let param = single_simple_param(&func.params)?;
2179 let body = single_returned_expression(func.body.as_ref()?)?;
2180 Some((param, body))
2181}
2182
2183fn single_simple_param<'a>(params: &'a FormalParameters<'a>) -> Option<&'a str> {
2184 let [param] = params.items.as_slice() else {
2185 return None;
2186 };
2187 if params.rest.is_some() || param.initializer.is_some() {
2188 return None;
2189 }
2190 match ¶m.pattern {
2191 BindingPattern::BindingIdentifier(id) => Some(id.name.as_str()),
2192 _ => None,
2193 }
2194}
2195
2196fn single_returned_expression<'a>(body: &'a FunctionBody<'a>) -> Option<&'a Expression<'a>> {
2197 match body.statements.as_slice() {
2198 [Statement::ReturnStatement(ret)] => ret.argument.as_ref(),
2199 _ => None,
2200 }
2201}
2202
2203pub(crate) fn is_dirname_anchor(expr: &Expression) -> bool {
2208 match expr {
2209 Expression::Identifier(id) => id.name == "__dirname",
2210 Expression::StaticMemberExpression(member) => {
2211 member.property.name == "dirname" && is_import_meta_expression(&member.object)
2212 }
2213 _ => false,
2214 }
2215}
2216
2217fn is_import_meta_expression(expr: &Expression) -> bool {
2219 matches!(expr, Expression::ImportMeta(_))
2220}
2221
2222fn new_expression_to_path_string(new_expr: &NewExpression, scope: PathScope<'_>) -> Option<String> {
2223 if !matches!(&new_expr.callee, Expression::Identifier(id) if id.name == "URL") {
2224 return None;
2225 }
2226
2227 let source = new_expr
2228 .arguments
2229 .first()
2230 .and_then(Argument::as_expression)
2231 .and_then(|arg| scoped_string(arg, scope))?;
2232
2233 let base = new_expr
2234 .arguments
2235 .get(1)
2236 .and_then(Argument::as_expression)?;
2237 is_import_meta_url_expression(base).then_some(source)
2238}
2239
2240fn is_import_meta_url_expression(expr: &Expression) -> bool {
2241 if let Expression::StaticMemberExpression(member) = expr {
2242 member.property.name == "url"
2243 && matches!(
2244 member.object,
2245 Expression::ImportMeta(_) | Expression::NewTarget(_)
2246 )
2247 } else {
2248 false
2249 }
2250}
2251
2252fn join_path_segments(segments: &[String]) -> String {
2253 let mut joined = PathBuf::new();
2254 for segment in segments {
2255 joined.push(segment);
2256 }
2257 joined.to_string_lossy().replace('\\', "/")
2258}
2259
2260fn alias_replacement_kinded(expr: &Expression, scope: PathScope<'_>) -> Option<(String, bool)> {
2267 match expr {
2268 Expression::ParenthesizedExpression(paren) => {
2269 alias_replacement_kinded(&paren.expression, scope)
2270 }
2271 Expression::TSAsExpression(ts_as) => alias_replacement_kinded(&ts_as.expression, scope),
2272 Expression::TSSatisfiesExpression(ts_sat) => {
2273 alias_replacement_kinded(&ts_sat.expression, scope)
2274 }
2275 Expression::StringLiteral(s) => {
2276 let value = s.value.text().into_owned();
2277 let is_bare =
2278 !value.starts_with("./") && !value.starts_with("../") && !value.starts_with('/');
2279 Some((value, is_bare))
2280 }
2281 Expression::ArrayExpression(arr) => arr
2285 .elements
2286 .iter()
2287 .find_map(ArrayExpressionElement::as_expression)
2288 .and_then(|element| alias_replacement_kinded(element, scope)),
2289 Expression::Identifier(id) => alias_constant::constant_replacement(id.name.as_str(), scope),
2290 _ => alias_entry::path_value(expr, scope).map(|value| (value, false)),
2291 }
2292}
2293
2294const MAX_ALIAS_RESOLVE_DEPTH: usize = 8;
2300
2301const ALIAS_SIBLING_EXTS: [&str; 6] = ["js", "mjs", "cjs", "ts", "mts", "cts"];
2308
2309fn resolve_alias_pairs_kinded(
2326 program: &Program,
2327 config_path: &Path,
2328 expr: &Expression,
2329 visited: &mut FxHashSet<PathBuf>,
2330 depth: usize,
2331) -> Vec<(String, String, bool)> {
2332 match expr {
2333 Expression::ParenthesizedExpression(paren) => {
2334 resolve_alias_pairs_kinded(program, config_path, &paren.expression, visited, depth)
2335 }
2336 Expression::TSAsExpression(ts_as) => {
2337 resolve_alias_pairs_kinded(program, config_path, &ts_as.expression, visited, depth)
2338 }
2339 Expression::TSSatisfiesExpression(ts_sat) => {
2340 resolve_alias_pairs_kinded(program, config_path, &ts_sat.expression, visited, depth)
2341 }
2342 Expression::ObjectExpression(obj) => {
2343 resolve_object_alias_pairs_kinded(program, config_path, obj, visited, depth)
2344 }
2345 Expression::ArrayExpression(arr) => {
2346 resolve_array_alias_pairs_kinded(program, config_path, arr, visited, depth)
2347 }
2348 Expression::Identifier(id) => {
2349 resolve_identifier_alias_pairs(program, config_path, id.name.as_str(), visited, depth)
2350 }
2351 _ => Vec::new(),
2352 }
2353}
2354
2355fn resolve_object_alias_pairs_kinded(
2358 program: &Program,
2359 config_path: &Path,
2360 obj: &ObjectExpression,
2361 visited: &mut FxHashSet<PathBuf>,
2362 depth: usize,
2363) -> Vec<(String, String, bool)> {
2364 let mut pairs = Vec::new();
2365 for prop in &obj.properties {
2366 match prop {
2367 ObjectPropertyKind::ObjectProperty(prop) => {
2368 if let Some(find) = property_key_to_string(&prop.key)
2369 && let Some((replacement, is_bare)) =
2370 alias_replacement_kinded(&prop.value, PathScope::Program(program))
2371 {
2372 pairs.push((find, replacement, is_bare));
2373 }
2374 }
2375 ObjectPropertyKind::SpreadProperty(spread) => {
2377 pairs.extend(resolve_alias_pairs_kinded(
2378 program,
2379 config_path,
2380 &spread.argument,
2381 visited,
2382 depth,
2383 ));
2384 }
2385 }
2386 }
2387 pairs
2388}
2389
2390fn resolve_array_alias_pairs_kinded(
2393 program: &Program,
2394 config_path: &Path,
2395 arr: &ArrayExpression,
2396 visited: &mut FxHashSet<PathBuf>,
2397 depth: usize,
2398) -> Vec<(String, String, bool)> {
2399 let mut pairs = Vec::new();
2400 for element in &arr.elements {
2401 match element {
2402 ArrayExpressionElement::SpreadElement(spread) => {
2404 pairs.extend(resolve_alias_pairs_kinded(
2405 program,
2406 config_path,
2407 &spread.argument,
2408 visited,
2409 depth,
2410 ));
2411 }
2412 _ => {
2413 if let Some(Expression::ObjectExpression(obj)) = element.as_expression()
2414 && let Some(pair) =
2415 alias_entry::object_alias_pair(obj, PathScope::Program(program))
2416 {
2417 pairs.push(pair);
2418 }
2419 }
2420 }
2421 }
2422 pairs
2423}
2424
2425fn resolve_identifier_alias_pairs(
2428 program: &Program,
2429 config_path: &Path,
2430 name: &str,
2431 visited: &mut FxHashSet<PathBuf>,
2432 depth: usize,
2433) -> Vec<(String, String, bool)> {
2434 if depth >= MAX_ALIAS_RESOLVE_DEPTH {
2435 return Vec::new();
2436 }
2437 if let Some(init) = find_variable_init_expression(program, name) {
2439 return resolve_alias_pairs_kinded(program, config_path, init, visited, depth + 1);
2440 }
2441 let Some((specifier, imported_name)) = find_relative_import_binding(program, name) else {
2443 return Vec::new();
2444 };
2445 resolve_imported_alias_pairs(
2446 config_path,
2447 &specifier,
2448 imported_name.as_deref(),
2449 visited,
2450 depth + 1,
2451 )
2452}
2453
2454fn resolve_imported_alias_pairs(
2457 config_path: &Path,
2458 specifier: &str,
2459 imported_name: Option<&str>,
2460 visited: &mut FxHashSet<PathBuf>,
2461 depth: usize,
2462) -> Vec<(String, String, bool)> {
2463 let Some((sibling_path, sibling_source)) = resolve_sibling_module(config_path, specifier)
2464 else {
2465 return Vec::new();
2466 };
2467 if !visited.insert(sibling_path.clone()) {
2468 return Vec::new();
2469 }
2470 extract_from_source(&sibling_source, &sibling_path, |program| {
2471 let init = find_exported_init(program, imported_name)?;
2472 let pairs = resolve_alias_pairs_kinded(program, &sibling_path, init, visited, depth);
2473 (!pairs.is_empty()).then_some(pairs)
2474 })
2475 .unwrap_or_default()
2476}
2477
2478fn find_variable_init_expression<'a>(
2483 program: &'a Program<'a>,
2484 name: &str,
2485) -> Option<&'a Expression<'a>> {
2486 for decl in top_level_variable_declarations(program) {
2487 for declarator in &decl.declarations {
2488 if let BindingPattern::BindingIdentifier(id) = &declarator.id
2489 && id.name == name
2490 && let Some(init) = &declarator.init
2491 {
2492 return Some(init);
2493 }
2494 }
2495 }
2496 None
2497}
2498
2499pub(crate) fn find_module_export_expression<'a>(
2502 program: &'a Program<'a>,
2503) -> Option<&'a Expression<'a>> {
2504 program.body.iter().find_map(|stmt| match stmt {
2505 Statement::ExportDefaultDeclaration(decl) => decl.declaration.as_expression(),
2506 Statement::ExpressionStatement(expr_stmt) => match &expr_stmt.expression {
2507 Expression::AssignmentExpression(assign) if is_module_exports_target(&assign.left) => {
2508 Some(&assign.right)
2509 }
2510 _ => None,
2511 },
2512 _ => None,
2513 })
2514}
2515
2516pub(crate) fn find_exported_init<'a>(
2521 program: &'a Program<'a>,
2522 name: Option<&str>,
2523) -> Option<&'a Expression<'a>> {
2524 match name {
2525 Some(name) => find_variable_init_expression(program, name),
2526 None => program.body.iter().find_map(|stmt| {
2527 if let Statement::ExportDefaultDeclaration(decl) = stmt {
2528 decl.declaration.as_expression()
2529 } else {
2530 None
2531 }
2532 }),
2533 }
2534}
2535
2536pub(crate) fn find_relative_import_binding(
2541 program: &Program,
2542 name: &str,
2543) -> Option<(String, Option<String>)> {
2544 for stmt in &program.body {
2545 let Statement::ImportDeclaration(decl) = stmt else {
2546 continue;
2547 };
2548 let specifier = &*decl.source.value.text();
2549 if !is_relative_specifier(specifier) {
2550 continue;
2551 }
2552 let Some(specifiers) = &decl.specifiers else {
2553 continue;
2554 };
2555 for spec in specifiers {
2556 match spec {
2557 ImportDeclarationSpecifier::ImportSpecifier(spec) if spec.local.name == name => {
2558 return Some((
2559 specifier.to_string(),
2560 Some(spec.imported.name().to_string()),
2561 ));
2562 }
2563 ImportDeclarationSpecifier::ImportDefaultSpecifier(spec)
2564 if spec.local.name == name =>
2565 {
2566 return Some((specifier.to_string(), None));
2567 }
2568 _ => {}
2569 }
2570 }
2571 }
2572 None
2573}
2574
2575pub(crate) fn is_relative_specifier(specifier: &str) -> bool {
2578 specifier.starts_with("./") || specifier.starts_with("../") || specifier.starts_with('/')
2579}
2580
2581pub(crate) fn resolve_sibling_module(
2586 config_path: &Path,
2587 specifier: &str,
2588) -> Option<(PathBuf, String)> {
2589 let parent = config_path.parent().unwrap_or(config_path);
2590 let (root, read) = (config_project_root(parent), read_project_file);
2591 let direct = parent.join(specifier);
2592 if let Some(source) = read(&root, &direct) {
2593 return Some((direct, source));
2594 }
2595 for ext in ALIAS_SIBLING_EXTS {
2596 let candidate = parent.join(format!("{specifier}.{ext}"));
2597 if let Some(source) = read(&root, &candidate) {
2598 return Some((candidate, source));
2599 }
2600 }
2601 for ext in ALIAS_SIBLING_EXTS {
2602 let candidate = direct.join(format!("index.{ext}"));
2603 if let Some(source) = read(&root, &candidate) {
2604 return Some((candidate, source));
2605 }
2606 }
2607 None
2608}
2609
2610pub(crate) fn lexical_normalize(path: &Path) -> PathBuf {
2611 let mut normalized = PathBuf::new();
2612 for component in path.components() {
2613 match component {
2614 std::path::Component::CurDir => {}
2615 std::path::Component::ParentDir => {
2616 normalized.pop();
2617 }
2618 _ => normalized.push(component.as_os_str()),
2619 }
2620 }
2621
2622 normalized
2623}
2624
2625pub(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
2638pub(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
2651pub(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
2666fn 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
2681pub(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
2717fn 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
2747fn 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
2763pub(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
2807fn 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
2831pub(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
2840fn 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
2870fn 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
2889fn 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
2910pub(crate) fn expression_to_string_or_array(expr: &Expression) -> Vec<String> {
2918 string_or_array_in(expr, PathScope::Bare)
2919}
2920
2921fn 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
2959pub(crate) fn is_require_call(call: &CallExpression) -> bool {
2961 matches!(&call.callee, Expression::Identifier(id) if id.name == "require")
2962}
2963
2964pub(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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 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 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 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 #[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 #[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 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 #[test]
5089 fn static_dir_entries_object_form_exercises_property_string() {
5090 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 #[test]
5109 fn expression_to_path_values_array_form_via_config_path() {
5110 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 #[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 #[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 #[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 let source = r"export default function config() { return 42; }";
5267 assert!(config_default_export_unreachable(source, &js_path()));
5268 }
5269
5270 #[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 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 #[test]
5330 fn aliases_array_form_missing_find_or_replacement_skipped() {
5331 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 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 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 #[test]
5433 fn default_export_array_ts_as_wrapper() {
5434 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 #[test]
5454 fn shallow_strings_object_with_string_values() {
5455 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 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 #[test]
5488 fn shallow_strings_or_object_property_non_array_single_string() {
5489 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 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 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 #[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 #[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 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 #[test]
5656 fn json_config_array_of_arrays_via_shallow_strings() {
5657 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 #[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 #[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 #[test]
5723 fn nested_shallow_strings_non_object_nested_returns_empty() {
5724 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 #[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 #[test]
5755 fn property_strings_deeply_nested_object_values() {
5756 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 #[test]
5778 fn aliases_exported_const_form_resolves() {
5779 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 #[test]
5791 fn aliases_imported_from_sibling_directory_index_file() {
5792 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 #[test]
5814 fn aliases_depth_limit_terminates_deep_chain() {
5815 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 let got = extract_config_aliases(source, &js_path(), &["resolve", "alias"]);
5831 let _ = got; }
5833
5834 #[test]
5837 fn extract_aliases_file_url_to_path_new_url() {
5838 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 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 #[test]
5872 fn truthy_bool_or_object_null_literal_returns_false() {
5873 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 #[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 #[test]
5891 fn object_nested_empty_when_inner_value_is_not_object() {
5892 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 #[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 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 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 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}