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