Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ steps = [
{ argv = ["vp", "run", "check"], comment = "second run should be cache hit", continue-on-failure = true },
{ argv = ["vpt", "write-file", "src/foo.js", "export const foo = 1;\n"], continue-on-failure = true },
{ argv = ["vp", "run", "check"], comment = "third run should be cache miss after new file added", continue-on-failure = true },
{ argv = ["vp", "run", "check"], envs = [["VP_SKIP_STATIC_CONFIG", "1"]], comment = "changing VP_SKIP_STATIC_CONFIG should be a cache miss", continue-on-failure = true },
]
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,13 @@ $ vp check ○ cache miss: 'foo.js' added in 'src', executing
pass: All 4 files are correctly formatted (<duration>, <n> threads)
pass: Found no warnings or lint errors in 3 files (<duration>, <n> threads)
```

## `VP_SKIP_STATIC_CONFIG=1 vp run check`

changing VP_SKIP_STATIC_CONFIG should be a cache miss

```
$ vp check ○ cache miss: env 'VP_SKIP_STATIC_CONFIG' changed, executing
pass: All 4 files are correctly formatted (<duration>, <n> threads)
pass: Found no warnings or lint errors in 3 files (<duration>, <n> threads)
```
8 changes: 8 additions & 0 deletions crates/vp_shared/src/env_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ pub struct EnvConfig {
/// Emergency bypass of the global CLI installation lockfile, enabled only by `1`.
pub setup_skip_install_lockfile: bool,

/// Load the Vite config through Vite instead of reading it statically,
/// enabled only by `1`.
///
/// Env: `VP_SKIP_STATIC_CONFIG`
pub skip_static_config: bool,

/// Override package manager and version.
///
/// Env: `VP_PACKAGE_MANAGER`
Expand Down Expand Up @@ -283,6 +289,8 @@ impl EnvConfig {
setup_skip_install_lockfile: std::env::var(env_vars::VP_SETUP_SKIP_INSTALL_LOCKFILE)
.as_deref()
== Ok("1"),
skip_static_config: std::env::var(env_vars::VP_SKIP_STATIC_CONFIG).as_deref()
== Ok("1"),
package_manager: std::env::var(env_vars::VP_PACKAGE_MANAGER).ok(),
npm_version: std::env::var(env_vars::VP_NPM_VERSION).ok(),
pnpm_version: std::env::var(env_vars::VP_PNPM_VERSION).ok(),
Expand Down
3 changes: 3 additions & 0 deletions crates/vp_shared/src/env_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ pub const VP_SETUP_NODE_VERSION_FILE: &str = "VP_SETUP_NODE_VERSION_FILE";
/// Resolve global CLI dependencies without the installation lockfile when set to `1`.
pub const VP_SETUP_SKIP_INSTALL_LOCKFILE: &str = "VP_SETUP_SKIP_INSTALL_LOCKFILE";

/// Load the Vite config through Vite instead of reading it statically when set to `1`.
pub const VP_SKIP_STATIC_CONFIG: &str = "VP_SKIP_STATIC_CONFIG";

/// Override package manager and version for vp commands (for example, `pnpm@10.18.0`).
/// Direct package-manager shims use their own version overrides instead.
pub const VP_PACKAGE_MANAGER: &str = "VP_PACKAGE_MANAGER";
Expand Down
94 changes: 80 additions & 14 deletions crates/vp_static_config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use oxc_allocator::Allocator;
use oxc_ast::{
StaticPropertyName,
ast::{
BindingPattern, Expression, ImportDeclarationSpecifier, ImportOrExportKind,
ObjectPropertyKind, Program, Statement, VariableDeclarationKind,
AssignmentOperator, BindingPattern, Expression, ImportDeclarationSpecifier,
ImportOrExportKind, ObjectPropertyKind, Program, Statement, VariableDeclarationKind,
},
};
use oxc_parser::Parser;
Expand Down Expand Up @@ -47,22 +47,33 @@ pub enum FieldValue {
/// values). Absent keys may exist via the spread and are treated as
/// [`FieldValue::NonStatic`] by [`FieldMap::get`], but not by
/// [`FieldMap::get_declared`].
///
/// `overwritable` marks a map whose declared values later code may change, so
/// only [`FieldMap::get_declared`] reports them.
pub struct FieldMap {
map: FxHashMap<Box<str>, FieldValue>,
open: bool,
overwritable: bool,
config_path: Option<vt_path::AbsolutePathBuf>,
}

impl FieldMap {
/// Returns an open empty map — used when the config is not analyzable.
/// `get()` returns `Some(NonStatic)` for any key, triggering NAPI fallback.
fn unanalyzable() -> Self {
Self { map: FxHashMap::default(), open: true }
Self { map: FxHashMap::default(), open: true, overwritable: false, config_path: None }
}

/// Returns a closed empty map — used when no config file exists.
/// `get()` returns `None` for any key (field definitively absent).
fn no_config() -> Self {
Self { map: FxHashMap::default(), open: false }
Self { map: FxHashMap::default(), open: false, overwritable: false, config_path: None }
}

/// The config file these fields came from, or `None` when the directory has none.
#[must_use]
pub fn config_path(&self) -> Option<&AbsolutePath> {
self.config_path.as_deref()
}

/// Look up a field by name.
Expand All @@ -72,8 +83,12 @@ impl FieldMap {
/// - open map: returns the stored value if explicitly declared after the
/// last spread/computed key, or `Some(NonStatic)` for any other key (it
/// may exist in the spread).
/// - overwritable map: returns `Some(NonStatic)` for every key.
#[must_use]
pub fn get(&self, key: &str) -> Option<FieldValue> {
if self.overwritable {
return Some(FieldValue::NonStatic);
}
self.map.get(key).cloned().or_else(|| self.open.then_some(FieldValue::NonStatic))
}

Expand Down Expand Up @@ -132,13 +147,16 @@ pub fn resolve_static_config(dir: &AbsolutePath) -> FieldMap {
// No config file found — closed empty map; get() returns None for any key.
return FieldMap::no_config();
};
let Ok(source) = std::fs::read_to_string(&config_path) else {
return FieldMap::unanalyzable();
let mut fields = match std::fs::read_to_string(&config_path) {
Ok(source) => {
let extension =
config_path.as_path().extension().and_then(|e| e.to_str()).unwrap_or("");
parse_js_ts_config(&source, extension)
}
Err(_) => FieldMap::unanalyzable(),
};

let extension = config_path.as_path().extension().and_then(|e| e.to_str()).unwrap_or("");

parse_js_ts_config(&source, extension)
fields.config_path = Some(config_path);
fields
}

/// Parse a JS/TS config file, extracting the default export object's fields.
Expand All @@ -165,13 +183,13 @@ fn parse_js_ts_config(source: &str, extension: &str) -> FieldMap {
/// 1. `export default defineConfig({ ... })` with `defineConfig` from a trusted package
/// 2. `export default { ... }`
/// 3. `module.exports = defineConfig({ ... })` with `defineConfig` from a trusted package
/// 4. `module.exports = { ... }`
/// 4. `module.exports = { ... }`, overwritable unless it is the last top-level statement
fn extract_config_fields(program: &Program<'_>) -> FieldMap {
let has_trusted_define_config_binding = program.body.iter().any(|stmt| {
is_trusted_define_config_import(stmt) || has_trusted_define_config_cjs_binding(stmt)
});

for stmt in &program.body {
for (index, stmt) in program.body.iter().enumerate() {
// ESM: export default ...
if let Statement::ExportDefaultDeclaration(decl) = stmt {
let Some(expr) = decl.declaration.as_expression() else {
Expand All @@ -189,14 +207,20 @@ fn extract_config_fields(program: &Program<'_>) -> FieldMap {
}

// CJS: module.exports = ...
// Compound assignments such as `||=` may skip their right side at runtime.
if let Statement::ExpressionStatement(expr_stmt) = stmt
&& let Expression::AssignmentExpression(assign) = &expr_stmt.expression
&& assign.operator == AssignmentOperator::Assign
&& assign.left.as_member_expression().is_some_and(|m| {
m.object().is_specific_id("module")
&& m.static_property_name().is_some_and(|name| name == "exports")
})
{
return extract_config_from_expr(&assign.right, has_trusted_define_config_binding);
let mut fields =
extract_config_from_expr(&assign.right, has_trusted_define_config_binding);
// Later statements can mutate `module.exports`, so only a final assignment is exhaustive.
fields.overwritable = index + 1 != program.body.len();
return fields;
}
}

Expand Down Expand Up @@ -495,7 +519,7 @@ fn extract_object_fields(obj: &oxc_ast::ast::ObjectExpression<'_>) -> FieldMap {
map.insert(Box::from(key), value);
}

FieldMap { map, open }
FieldMap { map, open, overwritable: false, config_path: None }
}

/// Convert an f64 to a JSON value following `JSON.stringify` semantics.
Expand Down Expand Up @@ -857,6 +881,48 @@ mod tests {
assert_json(&result, "run", serde_json::json!({ "cache": true }));
}

#[test]
fn module_exports_mutated_later_is_non_static() {
let result = parse_js_ts_config(
r"
module.exports = {
check: { lint: false },
lint: { rules: { 'no-debugger': 'error' } },
};
if (process.env.CI) module.exports.check.lint = true;
",
"cjs",
);
assert_non_static(&result, "check");
}

#[test]
fn module_exports_followed_by_code_keeps_declared_fields() {
let result = parse_js_ts_config(
"module.exports = { defaultPackage: './web' };\nfunction helper() {}",
"cjs",
);
assert_non_static(&result, "defaultPackage");
assert_non_static(&result, "run");
assert_eq!(
result.get_declared("defaultPackage"),
Some(FieldValue::Json(serde_json::json!("./web")))
);
assert_eq!(result.get_declared("run"), None);
}

#[test]
fn module_exports_compound_assignment_is_non_static() {
for source in [
"module.exports ||= { check: { lint: false } };",
"module.exports ??= { check: { lint: false } };",
] {
let result = parse_js_ts_config(source, "cjs");
assert_non_static(&result, "check");
assert_eq!(result.get_declared("check"), None);
}
}

#[test]
fn module_exports_define_config_destructured_require() {
let result = parse_js_ts_config(
Expand Down
8 changes: 8 additions & 0 deletions docs/guide/check.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,11 @@ export default defineConfig({
```

These options only affect `vp check`; standalone `vp fmt` and `vp lint` still run normally. A step is skipped if it is disabled in config or the matching `--no-fmt` / `--no-lint` flag is passed. Because the defaults apply to every `vp check` run, a pre-commit hook that calls `vp check` will skip the disabled step too. See [Check Config](/config/check) for the full reference.

### Reading the config

`vp check` reads the `lint`, `fmt`, and `check` blocks without running `vite.config.*` when it can, and otherwise loads the config through Vite. If `vp check` does not pick up your settings, set `VP_SKIP_STATIC_CONFIG=1` to always load the config through Vite:

```bash
VP_SKIP_STATIC_CONFIG=1 vp check
```
7 changes: 6 additions & 1 deletion packages/cli/binding/src/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ use crate::cli::{
resolve_and_capture_output,
};

/// The config blocks `vp check` reads. `plugins` is listed only so that a config
/// with plugins falls back to Vite, because a plugin's `config` hook can add the
/// other blocks.
pub(crate) const CHECK_CONFIG_FIELDS: &[&str] = &["lint", "fmt", "check", "plugins"];

/// Execute the `vp check` composite command (fmt + lint + optional type checks).
pub(crate) async fn execute_check(
resolver: &SubcommandResolver,
Expand All @@ -42,7 +47,7 @@ pub(crate) async fn execute_check(
let suppress_unmatched = no_error_on_unmatched_pattern || (fix && has_paths);
let mut fmt_fix_started: Option<Instant> = None;
let mut deferred_lint_pass: Option<(String, String)> = None;
let resolved_vite_config = resolver.resolve_universal_vite_config().await?;
let resolved_vite_config = resolver.resolve_universal_vite_config(CHECK_CONFIG_FIELDS).await?;

// Keep package runs on the root settings selected by `vp check`.
// Direct `vp lint` and `vp fmt` leave config discovery to the tools.
Expand Down
53 changes: 9 additions & 44 deletions packages/cli/binding/src/cli/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use vt_path::AbsolutePath;
use vt_str::Str;

use super::{
resolver::{SubcommandResolver, check_cache_inputs},
types::{CLIArgs, ResolvedUniversalViteConfig, SynthesizableSubcommand, ViteConfigResolverFn},
resolver::{SubcommandResolver, check_cache_inputs, resolve_vite_config_fields},
types::{CLIArgs, SynthesizableSubcommand, ViteConfigResolverFn},
};

/// CommandHandler implementation for vite-plus.
Expand Down Expand Up @@ -83,7 +83,10 @@ impl CommandHandler for VitePlusCommandHandler {
// Check is a composite command (fmt + lint) — run as a subprocess in task scripts
Ok(HandledCommand::Synthesized(command.to_synthetic_plan_request(
UserCacheConfig::with_config(EnabledCacheConfig {
env: Some(Box::new([Str::from("OXLINT_TSGOLINT_PATH")])),
env: Some(Box::new([
Str::from("OXLINT_TSGOLINT_PATH"),
Str::from(vp_shared::env_vars::VP_SKIP_STATIC_CONFIG),
Comment thread
fengmk2 marked this conversation as resolved.
Resolved
])),
untracked_env: None,
input: Some(check_cache_inputs()),
output: None,
Expand Down Expand Up @@ -164,46 +167,8 @@ impl UserConfigLoader for VitePlusConfigLoader {
&self,
package_path: &AbsolutePath,
) -> anyhow::Result<Option<UserRunConfig>> {
// Try static config extraction first (no JS runtime needed)
let static_fields = vp_static_config::resolve_static_config(package_path);
match static_fields.get("run") {
Some(vp_static_config::FieldValue::Json(run_value)) => {
tracing::debug!(
"Using statically extracted run config for {}",
package_path.as_path().display()
);
let run_config: UserRunConfig = serde_json::from_value(run_value)?;
return Ok(Some(run_config));
}
Some(vp_static_config::FieldValue::NonStatic) => {
// `run` field exists (or may exist via a spread) — fall back to NAPI
tracing::debug!(
"run config is not statically analyzable for {}, falling back to NAPI",
package_path.as_path().display()
);
}
None => {
// Config was analyzed successfully and `run` field is definitively absent
return Ok(None);
}
}

// Fall back to NAPI-based config resolution
let package_path_str = package_path
.as_path()
.to_str()
.ok_or_else(|| anyhow::anyhow!("package path is not valid UTF-8"))?;

let config_json = (self.resolve_fn)(package_path_str.to_string()).await?;
let resolved: ResolvedUniversalViteConfig = serde_json::from_str(&config_json)
.inspect_err(|_| {
tracing::error!("Failed to parse vite config: {config_json}");
})?;

let run_config = match resolved.run {
Some(run) => serde_json::from_value(run)?,
None => UserRunConfig::default(),
};
Ok(Some(run_config))
// The task graph reads an absent config as the default, so `None` covers both.
let config = resolve_vite_config_fields(package_path, &["run"], &self.resolve_fn).await?;
Ok(config.run.map(serde_json::from_value).transpose()?)
}
}
Loading
Loading