fallow_engine/mutation/mod.rs
1//! The static half of mutation testing: select, map, prune and rank mutants.
2//!
3//! The plan reads only facts that the dead-code analysis already has: the
4//! module graph with its test reachability (including the `vi.mock`
5//! replacement masks), the dead-code results, the function complexity of each
6//! module, and the captured security sink sites. It reads the source text of
7//! each selected file one time to instrument it, and it holds the
8//! instrumented code in memory. It never writes a file and never runs user
9//! code.
10//!
11//! Each mutant gets one disposition:
12//!
13//! - `planned`: a test file reaches the file, and no static rule prunes the
14//! mutant. The runner executes these mutants in rank order.
15//! - `pending`: a planned mutant after the `max_mutants` limit.
16//! - `no-coverage`: no test file reaches the file in the graph. A test that
17//! replaces the module with `vi.mock` does not reach it.
18//! - `pruned`: a static rule removes the mutant (see [`PruneReason`](crate::mutation::PruneReason)).
19
20mod build_tool;
21mod constant_condition;
22mod database_write;
23mod function_scope;
24mod layout;
25mod plan;
26mod reach;
27mod sampling;
28mod skipped_tests;
29#[cfg(test)]
30mod tests;
31mod unmatched;
32
33use std::collections::{BTreeMap, BTreeSet};
34use std::path::{Path, PathBuf};
35
36use serde::Serialize;
37
38pub use fallow_mutation::{
39 FunctionRef, Mutant, MutantChange, MutantId, MutationError, MutationOptions, Operator,
40 RESERVED_PREFIX, SourceKind,
41};
42pub use fallow_output::DiffIndex;
43pub use layout::{export_containing, instrument_source, is_component_file};
44pub use skipped_tests::{SkipKind, SkippedTest};
45
46use crate::EngineError;
47use crate::module_graph::{ExportTestReach, RetainedModuleGraph};
48use crate::session::AnalysisSession;
49use crate::source::ModuleInfo;
50use fallow_types::results::AnalysisResults;
51
52/// The runner config modules at the project root. Each test run loads them,
53/// so they and the files that they reach through static imports are in
54/// [`MutationPlan::support_files`].
55pub const RUNNER_CONFIG_MODULES: [&str; 18] = [
56 "vitest.config.ts",
57 "vitest.config.mts",
58 "vitest.config.cts",
59 "vitest.config.js",
60 "vitest.config.mjs",
61 "vitest.config.cjs",
62 "vite.config.ts",
63 "vite.config.mts",
64 "vite.config.cts",
65 "vite.config.js",
66 "vite.config.mjs",
67 "vite.config.cjs",
68 "vitest.workspace.ts",
69 "vitest.workspace.mts",
70 "vitest.workspace.cts",
71 "vitest.workspace.js",
72 "vitest.workspace.mjs",
73 "vitest.workspace.cjs",
74];
75
76/// The files and lines that a plan mutates.
77#[derive(Debug, Clone)]
78pub enum MutationScope {
79 /// The added lines of a diff against the base ref. Build the index with
80 /// the mutation diff machinery (`changed_files::try_get_mutation_diff`,
81 /// `DiffIndex::from_unified_diff` and `diff_source::place_diff`). Only
82 /// mutants that overlap an added line are kept.
83 ChangedSinceBase(DiffIndex),
84 /// Each source file of the project.
85 All,
86 /// The files at these paths, or below these directories. A relative path
87 /// is relative to the project root.
88 Paths(Vec<PathBuf>),
89}
90
91/// What to plan.
92#[derive(Debug, Clone)]
93pub struct MutationPlanRequest {
94 /// The files and lines to mutate.
95 pub scope: MutationScope,
96 /// The operators to use. `None` uses the default set
97 /// (`Operator::DEFAULT`).
98 pub operators: Option<Vec<Operator>>,
99 /// Keep the mutants in functions that call a file system, child process,
100 /// network or database sink. The default prunes them, because a mutant
101 /// can turn a guarded side effect into an unguarded one.
102 pub allow_side_effects: bool,
103 /// The maximum number of planned mutants. The mutants after this limit,
104 /// in rank order, become `pending`.
105 pub max_mutants: Option<usize>,
106 /// The maximum number of planned mutants on one source line. The plan
107 /// keeps the most productive mutants of the line and marks the others
108 /// [`MutantDisposition::SampledOut`]. `None` keeps each mutant.
109 pub mutants_per_line: Option<usize>,
110 /// Widen each changed line of [`MutationScope::ChangedSinceBase`] to the
111 /// whole innermost function that holds it, so that a change to a
112 /// parameter or a signature selects the mutants of the function. The
113 /// other scopes ignore it.
114 pub function_scope: bool,
115 /// Leave each Vue, Svelte and Astro component file out of the plan,
116 /// with the skip reason [`SkipReason::RunnerCannotLoad`]. Set it when
117 /// the test runner has no loader for a component file.
118 pub skip_component_files: bool,
119 /// Run only the mutants with these ids. Each other mutant is pruned with
120 /// [`PruneReason::NotSelected`]. It stays in the plan, because the
121 /// instrumented file still holds its switch. `None` selects each mutant.
122 pub mutant_ids: Option<BTreeSet<String>>,
123 /// Wrap each exported function that holds a planned mutant, so that a
124 /// recording dry run can record its arguments.
125 pub record_exports: bool,
126}
127
128impl MutationPlanRequest {
129 /// A request with the default options for `scope`.
130 #[must_use]
131 pub const fn new(scope: MutationScope) -> Self {
132 Self {
133 scope,
134 operators: None,
135 allow_side_effects: false,
136 max_mutants: None,
137 mutants_per_line: None,
138 function_scope: false,
139 skip_component_files: false,
140 mutant_ids: None,
141 record_exports: false,
142 }
143 }
144}
145
146/// Framework config exports, by root-relative file path.
147///
148/// A framework plugin marks some exports as used by the framework, for
149/// example `export const revalidate = 60` in a Next.js page. A mutant in such
150/// an export changes framework config, not tested logic, so the plan prunes
151/// it. Mutants inside a function in the export are not pruned.
152#[derive(Debug, Clone, Default, PartialEq, Eq)]
153pub struct FrameworkConfigExports {
154 files: BTreeMap<String, BTreeSet<String>>,
155 config_files: BTreeSet<String>,
156}
157
158impl FrameworkConfigExports {
159 /// Records that the framework uses `export` of the root-relative `file`.
160 pub fn insert(&mut self, file: impl Into<String>, export: impl Into<String>) {
161 self.files
162 .entry(file.into())
163 .or_default()
164 .insert(export.into());
165 }
166
167 /// Records that the root-relative `file` is a tool config file. The tool
168 /// reads its default export, and a top-level `module.exports = ...`
169 /// statement counts as that default export.
170 fn insert_config_file(&mut self, file: impl Into<String>) {
171 let file = file.into();
172 self.insert(file.clone(), DEFAULT_EXPORT);
173 self.config_files.insert(file);
174 }
175
176 /// True when [`Self::insert_config_file`] recorded the root-relative
177 /// `file`.
178 #[must_use]
179 fn is_config_file(&self, file: &str) -> bool {
180 self.config_files.contains(file)
181 }
182
183 /// The framework config export names of one root-relative file.
184 #[must_use]
185 fn exports_for(&self, file: &str) -> Option<&BTreeSet<String>> {
186 self.files.get(file)
187 }
188}
189
190/// The analysis facts that a plan reads.
191#[derive(Clone, Copy)]
192pub struct MutationPlanInputs<'a> {
193 /// The project root.
194 pub root: &'a Path,
195 /// The module graph of the analysis.
196 pub graph: &'a RetainedModuleGraph,
197 /// The parsed modules, with complexity.
198 pub modules: &'a [ModuleInfo],
199 /// The dead-code results of the analysis.
200 pub results: &'a AnalysisResults,
201 /// The framework config exports. `None` when the caller has no plugin
202 /// facts. The plan then prunes no `framework-config` and no
203 /// `build-tool-only` mutants and sets
204 /// [`MutationPlan::framework_config_checked`] to false.
205 pub framework_config_exports: Option<&'a FrameworkConfigExports>,
206 /// The setup files of the test runner config, absolute or relative to
207 /// the root, with or without an extension. They fill
208 /// [`MutationPlan::support_files`], with the runner config modules at the
209 /// root.
210 pub setup_files: &'a [PathBuf],
211 /// The ignore globs of the config. They give the reason of an unmatched
212 /// path. `None` when the caller has no config.
213 pub ignore_patterns: Option<&'a fallow_config::IgnorePatternSet>,
214}
215
216/// Why a static rule removes a mutant.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
218#[serde(rename_all = "kebab-case")]
219pub enum PruneReason {
220 /// The file is unused: no entry point reaches it.
221 DeadCode,
222 /// The file is generated code.
223 Generated,
224 /// The enclosing function calls a file system, child process, network or
225 /// database sink of the security catalogue. A mutant outside each
226 /// function gets this reason when the module calls such a sink outside
227 /// each function, because that sink runs on each import of the module.
228 /// A sink that only shapes a response or a navigation (a redirect, a
229 /// header, a cookie, a CORS policy) does not count.
230 SideEffectSink,
231 /// The mutant is in an export that a framework reads as config.
232 FrameworkConfig,
233 /// Only tool config files reach the file, for example a Vite plugin
234 /// module that only `vite.config.ts` imports. The code runs in the dev
235 /// server or the build, and no test or application entry reaches it.
236 BuildToolOnly,
237 /// The request selects other mutants by id
238 /// ([`MutationPlanRequest::mutant_ids`]).
239 NotSelected,
240}
241
242/// The status of a mutant in a plan.
243#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
244#[serde(tag = "status", content = "reason", rename_all = "kebab-case")]
245pub enum MutantDisposition {
246 /// The runner executes the mutant.
247 Planned,
248 /// A planned mutant after the `max_mutants` limit.
249 Pending,
250 /// A planned mutant that the `mutants_per_line` limit left out. It has
251 /// no rank, and the scheduler never runs it.
252 SampledOut,
253 /// No test file reaches the file of the mutant.
254 NoCoverage,
255 /// A static rule removes the mutant.
256 Pruned(PruneReason),
257}
258
259/// The facts of the function that contains a mutant.
260#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
261pub struct FunctionFacts {
262 /// The function name. The complexity name wins over the syntax name, so
263 /// that the name is the same as in `health` output.
264 pub name: Option<String>,
265 /// The byte span of the function.
266 pub span: (u32, u32),
267 /// The 1-based first line of the function.
268 pub line: u32,
269 /// The 1-based last line of the function.
270 pub end_line: u32,
271 /// The cyclomatic complexity, when the analysis measured the function.
272 pub cyclomatic: Option<u16>,
273 /// True when an added line of the diff is in the function.
274 pub in_diff: bool,
275}
276
277/// One mutant of the plan.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
279pub struct PlannedMutant {
280 /// The mutant.
281 pub mutant: Mutant,
282 /// The root-relative path of the file, with forward slashes.
283 pub file: String,
284 /// The 1-based execution rank of a planned or pending mutant.
285 pub rank: Option<u32>,
286 /// The status of the mutant.
287 pub disposition: MutantDisposition,
288 /// The function that contains the mutant.
289 pub function: Option<FunctionFacts>,
290 /// How tests reach the code of the mutant in the module graph. `None`
291 /// for a pruned mutant.
292 pub test_reach: Option<MutantTestReach>,
293 /// True for a `negate-condition` mutant that sets a parameter test to
294 /// the value that each visible call gives it. A survivor gets the
295 /// `constant-parameter` hint. The plan document does not hold it.
296 #[serde(skip)]
297 pub constant_parameter: bool,
298}
299
300/// How tests reach the code of one mutant, from the module graph.
301///
302/// A mutant in the top-level statement that declares a value export gets the
303/// class of that export. A mutant outside each such statement gets the class
304/// of its file: `none-file` when no test loads the file, `mocked-only` when no
305/// test loads the file and a mock explains an export of the file, and `none`
306/// when a test loads the file.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
308pub struct MutantTestReach {
309 /// The reach class.
310 pub reach: ExportTestReach,
311 /// The export whose declaration holds the mutant. `None` for a mutant
312 /// outside each value export declaration.
313 pub export_name: Option<String>,
314 /// For `mocked-only`: the test files whose references a mock removed,
315 /// sorted.
316 pub tests: Vec<String>,
317 /// Static test-file reach for this exported declaration. Internal plan
318 /// evidence only. This is not per-test runtime export coverage.
319 #[serde(skip)]
320 pub export_test_files: Vec<String>,
321 /// For `mocked-only`: the mocked modules on the reference paths, sorted.
322 pub mocked_targets: Vec<String>,
323}
324
325/// One file that the runner loads in its instrumented form.
326#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
327pub struct PlannedFile {
328 /// The root-relative path, with forward slashes.
329 pub path: String,
330 /// The SHA-256 digest of the file bytes, as lowercase hex.
331 pub source_sha256: String,
332 /// The instrumented source text.
333 pub instrumented_code: String,
334 /// The test files that reach the file through imports, sorted. A test
335 /// that replaces the file, or a module on each import path to it, with
336 /// `vi.mock` is not in the list.
337 pub static_test_files: Vec<String>,
338}
339
340/// Why the plan did not instrument a selected file.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
342#[serde(rename_all = "kebab-case")]
343pub enum SkipReason {
344 /// The file could not be read.
345 Unreadable,
346 /// The file changed after the analysis parsed it.
347 Stale,
348 /// The file does not parse.
349 Parse,
350 /// The file declares a name that the instrumentation reserves.
351 ReservedName,
352 /// The file is larger than 4 GiB.
353 TooLarge,
354 /// The module graph has the file, but the analysis kept no module facts
355 /// for it, for example because extraction could not read it.
356 NotAnalyzed,
357 /// The test runner cannot load the file: a component file under a runner
358 /// with no component loader.
359 RunnerCannotLoad,
360}
361
362/// Why a path of a `Paths` scope selects no source file.
363#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
364#[serde(rename_all = "kebab-case")]
365pub enum UnmatchedReason {
366 /// The path does not exist.
367 NotFound,
368 /// The `ignorePatterns` of the config, or a built-in ignore, exclude the
369 /// path or a file under it.
370 Ignored,
371 /// The path exists, but it holds only test code, declaration files or
372 /// files outside the module graph.
373 NoSourceFile,
374}
375
376/// A path of a `Paths` scope that selects no source file.
377#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
378pub struct UnmatchedPath {
379 /// The path as given, with forward slashes.
380 pub path: String,
381 /// Why the path selects no source file.
382 pub reason: UnmatchedReason,
383}
384
385/// A selected file that the plan did not instrument.
386#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
387pub struct SkippedFile {
388 /// The root-relative path, with forward slashes.
389 pub path: String,
390 /// Why the plan skipped the file.
391 pub reason: SkipReason,
392}
393
394/// The number of pruned mutants for each reason.
395#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
396pub struct PruneCounts {
397 /// Mutants in unused files.
398 pub dead_code: usize,
399 /// Mutants in generated files.
400 pub generated: usize,
401 /// Mutants in functions that call a side-effect sink, and top-level
402 /// mutants of a module with a top-level side-effect sink.
403 pub side_effect_sink: usize,
404 /// Mutants in framework config exports.
405 pub framework_config: usize,
406 /// Mutants in files that only tool config files reach.
407 pub build_tool_only: usize,
408 /// Mutants that the request did not select by id. A plan document never
409 /// selects by id, so its output has no such count.
410 #[serde(skip)]
411 pub not_selected: usize,
412}
413
414/// The number of mutants for each disposition.
415#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
416pub struct MutationPlanCounts {
417 /// Each mutant of the plan.
418 pub total: usize,
419 /// Planned mutants.
420 pub planned: usize,
421 /// Planned mutants after the `max_mutants` limit.
422 pub pending: usize,
423 /// Planned mutants that the `mutants_per_line` limit left out. They are
424 /// not part of `pending`.
425 pub sampled_out: usize,
426 /// Mutants that no test file reaches.
427 pub no_coverage: usize,
428 /// Pruned mutants, by reason.
429 pub pruned: PruneCounts,
430}
431
432/// The static mutation plan.
433#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
434pub struct MutationPlan {
435 /// The files with a planned or pending mutant, sorted by path.
436 pub files: Vec<PlannedFile>,
437 /// Each mutant. Ranked mutants come first in rank order, then the other
438 /// mutants by file, span and id.
439 pub mutants: Vec<PlannedMutant>,
440 /// The union of the static test files of `files`, sorted.
441 pub test_files: Vec<String>,
442 /// The skipped and todo tests in the runner test files that the diff of a
443 /// changed-code scope changes, sorted by file and line. A test file
444 /// counts when the diff adds, removes or changes a line in it, also when
445 /// it reaches no changed source. A scan of the syntax tree finds the
446 /// tests, so no runner starts. Empty for the other scopes.
447 #[serde(skip)]
448 pub skipped_tests: Vec<SkippedTest>,
449 /// The files that the test files reach through static imports, sorted.
450 /// [`MutationPlan::test_file_reach`] indexes into this list.
451 #[serde(skip)]
452 pub reach_files: Vec<String>,
453 /// The files that each test file of `test_files` reaches through static
454 /// imports, as sorted indices into `reach_files`. The list leaves out the
455 /// test file itself and ignores `vi.mock`, so it is a superset of the
456 /// files that the test loads. The result cache of a run keys on the
457 /// content of these files.
458 #[serde(skip)]
459 pub test_file_reach: BTreeMap<String, Vec<u32>>,
460 /// The setup files of the test runner, the runner config modules at the
461 /// root ([`RUNNER_CONFIG_MODULES`]), and the files that they reach through
462 /// static imports, sorted. Each test loads them, so the result cache keys
463 /// on their content for each mutant.
464 #[serde(skip)]
465 pub support_files: Vec<String>,
466 /// The number of mutants for each disposition.
467 pub counts: MutationPlanCounts,
468 /// True when the project has no test files. Each mutant is then
469 /// `no-coverage`, and a report shows this one fact instead of one line
470 /// for each mutant.
471 pub no_test_files: bool,
472 /// True when the plan applied the `framework-config` and
473 /// `build-tool-only` prune rules. False when the caller gave no framework
474 /// config exports, so that a mutant in such an export or in a module that
475 /// only a tool config file imports can be `planned`.
476 pub framework_config_checked: bool,
477 /// The selected files that the plan did not instrument, sorted by path.
478 pub skipped_files: Vec<SkippedFile>,
479 /// The paths of a `Paths` scope that select no source file, sorted by
480 /// path, each with the reason.
481 pub unmatched_paths: Vec<UnmatchedPath>,
482}
483
484#[cfg(test)]
485impl MutationPlan {
486 /// The files that `test_file` reaches through static imports, sorted.
487 /// Empty for a file that is not a test file of the plan.
488 fn test_file_reach_paths<'a>(&'a self, test_file: &str) -> impl Iterator<Item = &'a str> {
489 self.test_file_reach
490 .get(test_file)
491 .into_iter()
492 .flatten()
493 .filter_map(|&index| self.reach_files.get(index as usize))
494 .map(String::as_str)
495 }
496}
497
498/// An error from [`plan_mutations_for_session`].
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub enum MutationPlanError {
501 /// The analysis failed.
502 Analysis(EngineError),
503 /// The analysis did not keep an artifact that the plan reads.
504 MissingArtifact(&'static str),
505 /// The plugin stage failed, so the plan cannot read the framework config
506 /// exports.
507 Plugins(String),
508}
509
510impl std::fmt::Display for MutationPlanError {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 match self {
513 Self::Analysis(error) => write!(f, "the analysis failed: {error}"),
514 Self::MissingArtifact(name) => {
515 write!(
516 f,
517 "the analysis did not keep the {name} for the mutation plan"
518 )
519 }
520 Self::Plugins(message) => write!(f, "the plugin stage failed: {message}"),
521 }
522 }
523}
524
525impl std::error::Error for MutationPlanError {}
526
527impl From<EngineError> for MutationPlanError {
528 fn from(error: EngineError) -> Self {
529 Self::Analysis(error)
530 }
531}
532
533/// Builds the mutation plan from the facts of one analysis.
534#[must_use]
535fn plan_mutations(inputs: &MutationPlanInputs<'_>, request: &MutationPlanRequest) -> MutationPlan {
536 plan::build(inputs, request)
537}
538
539/// Runs the dead-code analysis of `session` with complexity and the graph,
540/// then builds the mutation plan.
541///
542/// The framework config exports come from the plugin used-export rules of
543/// the session, the same rules that the unused-export analysis reads. The
544/// plugin stage runs one more time for them.
545///
546/// # Errors
547///
548/// Returns an error when the analysis or the plugin stage fails.
549pub fn plan_mutations_for_session(
550 session: &AnalysisSession,
551 request: &MutationPlanRequest,
552) -> Result<MutationPlan, MutationPlanError> {
553 plan_mutations_for_session_with(session, request, |_| false)
554}
555
556/// Like [`plan_mutations_for_session`], but `skip_components` reads the
557/// first plan and decides if the component files leave the plan. The test
558/// runner can depend on the test files of the plan, so the caller decides
559/// after the first plan. When the first plan has a component mutant and
560/// `skip_components` returns true, the plan is built again from the same
561/// analysis with [`MutationPlanRequest::skip_component_files`] set.
562///
563/// # Errors
564///
565/// Returns an error when the analysis or the plugin stage fails.
566pub fn plan_mutations_for_session_with(
567 session: &AnalysisSession,
568 request: &MutationPlanRequest,
569 skip_components: impl FnOnce(&MutationPlan) -> bool,
570) -> Result<MutationPlan, MutationPlanError> {
571 let artifacts = session.analyze_dead_code_with_artifacts(true, true)?;
572 let graph = artifacts
573 .graph
574 .as_ref()
575 .ok_or(MutationPlanError::MissingArtifact("module graph"))?;
576 let modules = artifacts
577 .modules
578 .as_deref()
579 .ok_or(MutationPlanError::MissingArtifact("parsed modules"))?;
580 let inventory = crate::list_inventory::collect_listing_inventory(session, false)
581 .map_err(|error| MutationPlanError::Plugins(error.message().to_owned()))?;
582 let framework_config_exports = framework_config_exports(session, graph, &inventory);
583 let mut setup_files = inventory.plugins.backend().setup_files();
584 setup_files.extend(crate::core_backend::bun_preload_files(session.root()));
585 let inputs = MutationPlanInputs {
586 root: session.root(),
587 graph,
588 modules,
589 results: &artifacts.results,
590 framework_config_exports: Some(&framework_config_exports),
591 setup_files: &setup_files,
592 ignore_patterns: Some(&session.config().ignore_patterns),
593 };
594 let plan = plan_mutations(&inputs, request);
595 let has_component = plan
596 .mutants
597 .iter()
598 .any(|mutant| is_component_file(&mutant.file));
599 if request.skip_component_files || !has_component || !skip_components(&plan) {
600 return Ok(plan);
601 }
602 let request = MutationPlanRequest {
603 skip_component_files: true,
604 ..request.clone()
605 };
606 Ok(plan_mutations(&inputs, &request))
607}
608
609/// The plugin used-export names of each module of the graph. A tool reads
610/// the default export of its config file, so the default export of each file
611/// that a tool config glob of an active plugin matches is framework config
612/// too.
613fn framework_config_exports(
614 session: &AnalysisSession,
615 graph: &RetainedModuleGraph,
616 inventory: &crate::list_inventory::ListingInventory,
617) -> FrameworkConfigExports {
618 let backend = inventory.plugins.backend();
619 let names = backend.used_export_names();
620 let active = backend.active_plugins();
621 let external = session
622 .config()
623 .external_plugins
624 .iter()
625 .filter(|plugin| active.contains(&plugin.name))
626 .flat_map(|plugin| {
627 plugin
628 .config_patterns
629 .iter()
630 .chain(&plugin.always_used)
631 .cloned()
632 });
633 // Some plugins list their config file as always used, not as a config
634 // glob. The tool config name filter keeps the other always-used files
635 // out.
636 let patterns: Vec<String> = backend
637 .config_patterns()
638 .into_iter()
639 .chain(backend.always_used_patterns())
640 .chain(external)
641 .collect();
642 let config_files = config_file_globs(&patterns);
643 let mut exports = FrameworkConfigExports::default();
644 for node in &graph.as_graph().modules {
645 let rel = crate::module_graph::relative_key_path(&node.path, session.root());
646 for name in names.names_for(&rel) {
647 exports.insert(rel.clone(), name);
648 }
649 if config_files.is_match(&rel) {
650 exports.insert_config_file(rel);
651 }
652 }
653 exports
654}
655
656/// The export name of `export default` and of `module.exports = ...`.
657const DEFAULT_EXPORT: &str = "default";
658
659/// The word in a file name that marks a tool config file, as in
660/// `vite.config.ts`, `stryker.conf.js` or `tsconfig.json`.
661const CONFIG_NAME_MARKERS: [&str; 2] = ["config", ".conf."];
662
663/// True when the file name part of a plugin config glob names a tool config
664/// file: it holds `config` or `.conf.`, or an `rc` suffix as in
665/// `.eslintrc.js`. Some plugins also list application files as config, for
666/// example `codegen*.ts`, `src/module.ts` or `app/routes.ts`. Tests can load
667/// those files, so their default export stays in the plan.
668fn is_tool_config_glob(pattern: &str) -> bool {
669 let name = pattern
670 .rsplit('/')
671 .next()
672 .unwrap_or(pattern)
673 .to_ascii_lowercase();
674 if CONFIG_NAME_MARKERS
675 .iter()
676 .any(|marker| name.contains(marker))
677 {
678 return true;
679 }
680 let stem = name.split(['.', '{']).find(|part| !part.is_empty());
681 stem.is_some_and(|stem| stem.ends_with("rc"))
682}
683
684/// The tool config globs, each also tried under `**/`, because a glob is
685/// relative to the directory that the plugin searches, for example a
686/// workspace package.
687fn config_file_globs(patterns: &[String]) -> globset::GlobSet {
688 let mut builder = globset::GlobSetBuilder::new();
689 for pattern in patterns
690 .iter()
691 .filter(|pattern| is_tool_config_glob(pattern))
692 {
693 let anywhere = if pattern.starts_with("**/") {
694 pattern.clone()
695 } else {
696 format!("**/{pattern}")
697 };
698 for candidate in [pattern.as_str(), anywhere.as_str()] {
699 if let Ok(glob) = globset::Glob::new(candidate) {
700 builder.add(glob);
701 }
702 }
703 }
704 builder
705 .build()
706 .unwrap_or_else(|_| globset::GlobSet::empty())
707}