Skip to content
Draft
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
@@ -0,0 +1,6 @@
<!doctype html>
<html>
<body>
<h1>positional root app</h1>
</body>
</html>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!doctype html>
<html>
<body>
<h1>core version guard</h1>
</body>
</html>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "core-version-guard-test",
"private": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# The vendored node_modules/vite/package.json shadows the runner's run-root
# `vite` -> core link with a core at a version the CLI never shipped with,
# simulating a dependency-bot bump of the `vite` alias without the matching
# vite-plus bump (issue #2356). The app/ subdir vendors a real-vite-shaped
# package, so the positional-root step passes only when the guard checks the
# selected root instead of the workspace cwd.
[[case]]
name = "core_version_guard"
vp = "local"
steps = [
{ argv = ["vp", "build"], continue-on-failure = true },
{ argv = ["vp", "test"], continue-on-failure = true },
{ argv = ["vp", "build", "app"], comment = "the guard checks the positional root, where vite is real Vite" },
{ argv = ["vp", "build"], comment = "VP_SKIP_CORE_VERSION_CHECK=1 skips the guard", envs = [["VP_SKIP_CORE_VERSION_CHECK", "1"]] },
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# core_version_guard

## `vp build`

**Exit code:** 1

```
error: Failed to resolve vite command: GenericFailure, Error: The project's `vite` alias resolves to @voidzero-dev/vite-plus-core@<version>, but this vite-plus CLI requires @voidzero-dev/vite-plus-core@<version>: the two packages are published in lockstep and other pairings are untested. A dependency bot usually causes this by updating vite-plus and the `vite` alias in separate PRs. Update the `vite` alias to npm:@voidzero-dev/vite-plus-core@<version> where it is declared (catalog, overrides, resolutions, or dependencies), or run `vp migrate` to realign it. Set VP_SKIP_CORE_VERSION_CHECK=1 to skip this check.
```

## `vp test`

**Exit code:** 1

```
error: Failed to resolve test command: GenericFailure, Error: The project's `vite` alias resolves to @voidzero-dev/vite-plus-core@<version>, but this vite-plus CLI requires @voidzero-dev/vite-plus-core@<version>: the two packages are published in lockstep and other pairings are untested. A dependency bot usually causes this by updating vite-plus and the `vite` alias in separate PRs. Update the `vite` alias to npm:@voidzero-dev/vite-plus-core@<version> where it is declared (catalog, overrides, resolutions, or dependencies), or run `vp migrate` to realign it. Set VP_SKIP_CORE_VERSION_CHECK=1 to skip this check.
```

## `vp build app`

the guard checks the positional root, where vite is real Vite

```
note: `vp build app` sets Vite's root without changing the working directory. To run as if started there, use `vp -C app build`.
✓ 2 modules transformed.
computing gzip size...
app/dist/index.html <size> kB │ gzip: <size> kB

✓ built in <duration>
```

## `VP_SKIP_CORE_VERSION_CHECK=1 vp build`

VP_SKIP_CORE_VERSION_CHECK=1 skips the guard

```
✓ 2 modules transformed.
computing gzip size...
dist/index.html <size> kB │ gzip: <size> kB

✓ built in <duration>
```
12 changes: 6 additions & 6 deletions packages/cli/binding/index.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -3370,12 +3370,12 @@ export interface BatchRewriteResult {

/** Configuration options passed from JavaScript to Rust. */
export interface CliOptions {
lint: (err: Error | null) => Promise<JsCommandResolvedResult>;
fmt: (err: Error | null) => Promise<JsCommandResolvedResult>;
vite: (err: Error | null) => Promise<JsCommandResolvedResult>;
test: (err: Error | null) => Promise<JsCommandResolvedResult>;
pack: (err: Error | null) => Promise<JsCommandResolvedResult>;
doc: (err: Error | null) => Promise<JsCommandResolvedResult>;
lint: (err: Error | null, arg: string) => Promise<JsCommandResolvedResult>;
fmt: (err: Error | null, arg: string) => Promise<JsCommandResolvedResult>;
vite: (err: Error | null, arg: string) => Promise<JsCommandResolvedResult>;
test: (err: Error | null, arg: string) => Promise<JsCommandResolvedResult>;
pack: (err: Error | null, arg: string) => Promise<JsCommandResolvedResult>;
doc: (err: Error | null, arg: string) => Promise<JsCommandResolvedResult>;
cwd?: string;
/** CLI arguments (should be process.argv.slice(2) from JavaScript) */
args?: Array<string>;
Expand Down
94 changes: 94 additions & 0 deletions packages/cli/binding/src/cli/app_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,62 @@ fn classify_args<'a>(command: &str, args: &'a [String]) -> ArgTarget<'a> {
ArgTarget::Bare
}

/// The directory Vite loads the app config from, when the args select one:
/// the parent of an explicit `-c`/`--config` file (which wins over a
/// positional), else the `[root]` positional. `None` means the command's cwd.
/// Walks the args like [`classify_args`] (cac/mri value consumption), but
/// scans them all instead of returning at the first target, because Vite
/// accepts `--config` and `[root]` in either order.
///
/// Used to aim the core-version guard at the copy of `vite` the app's config
/// and plugins will import: Vite keeps the process cwd unchanged and rebases
/// config lookup onto the selected root.
pub(super) fn vite_config_dir(args: &[String], cwd: &AbsolutePath) -> Option<AbsolutePathBuf> {
let mut positional: Option<&str> = None;
let mut config: Option<&str> = None;
let mut iter = args.iter().peekable();
while let Some(arg) = iter.next() {
if !arg.starts_with('-') {
positional.get_or_insert(arg);
continue;
}
// `--` terminates options: the first following token is the
// positional, and nothing after it can be a flag.
if arg == "--" {
if positional.is_none() {
positional = iter.next().map(String::as_str);
}
break;
}
if arg == "-c" || arg == "--config" {
if let Some(next) = iter.peek() {
if !next.starts_with('-') {
config = iter.next().map(String::as_str);
}
}
continue;
}
if let Some(value) = arg.strip_prefix("-c=").or_else(|| arg.strip_prefix("--config=")) {
config = Some(value);
continue;
}
let is_boolean = VITE_BOOLEAN_FLAGS.contains(&arg.as_str()) || arg.starts_with("--no-");
if !is_boolean
&& !arg.contains('=')
&& iter.peek().is_some_and(|next| !next.starts_with('-'))
{
iter.next();
}
}
if let Some(config) = config {
// The config's parent dir, resolved like Vite resolves `--config`
// (relative to cwd). An empty parent means the config sits in cwd.
let parent = std::path::Path::new(config).parent().unwrap_or(std::path::Path::new(""));
return Some(cwd.join(parent).clean());
}
positional.map(|root| cwd.join(root).clean())
}

/// Heuristic ranking signal: does a directory look runnable for `command`?
/// Used for ordering and single-candidate auto-selection, never for hiding.
/// The rules are documented in rfcs/cwd-flag.md ("The likely-runnable
Expand Down Expand Up @@ -513,6 +569,44 @@ pub(super) fn resolve_app_target(
mod tests {
use super::*;

#[test]
fn vite_config_dir_selects_the_app_dir() {
let to_args = |args: &[&str]| args.iter().map(|s| (*s).to_string()).collect::<Vec<_>>();
let root = if cfg!(windows) { "C:\\ws" } else { "/ws" };
let cwd = AbsolutePath::new(root).unwrap();
let dir = |rel: &str| Some(cwd.join(rel).clean());

// No target selection: fall back to the command's cwd.
assert_eq!(vite_config_dir(&to_args(&[]), cwd), None);
assert_eq!(vite_config_dir(&to_args(&["--mode", "production"]), cwd), None);

// The `[root]` positional, wherever cac would see one.
assert_eq!(vite_config_dir(&to_args(&["apps/web"]), cwd), dir("apps/web"));
assert_eq!(
vite_config_dir(&to_args(&["--mode", "production", "apps/web"]), cwd),
dir("apps/web")
);
assert_eq!(vite_config_dir(&to_args(&["-w", "apps/web"]), cwd), dir("apps/web"));
assert_eq!(vite_config_dir(&to_args(&["--", "apps/web"]), cwd), dir("apps/web"));

// An explicit config wins over the positional in either order; its
// parent is where the config's imports resolve from.
assert_eq!(
vite_config_dir(&to_args(&["-c", "apps/web/vite.config.ts"]), cwd),
dir("apps/web")
);
assert_eq!(
vite_config_dir(&to_args(&["apps/web", "--config=conf/vite.config.ts"]), cwd),
dir("conf")
);
assert_eq!(
vite_config_dir(&to_args(&["-c", "conf/vite.config.ts", "apps/web"]), cwd),
dir("conf")
);
// A config in the cwd itself keeps the cwd as the guard dir.
assert_eq!(vite_config_dir(&to_args(&["-c", "vite.config.ts"]), cwd), dir(""));
}

#[test]
fn bare_means_no_positional_target_and_no_help() {
let to_args = |args: &[&str]| args.iter().map(|s| (*s).to_string()).collect::<Vec<_>>();
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/binding/src/cli/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async fn resolve_and_build_command(
cwd: &AbsolutePathBuf,
) -> Result<tokio::process::Command, Error> {
let resolved = resolver
.resolve(subcommand, resolved_vite_config, envs)
.resolve(subcommand, resolved_vite_config, envs, cwd)
.await
.map_err(|e| Error::Anyhow(e))?;

Expand Down
3 changes: 2 additions & 1 deletion packages/cli/binding/src/cli/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ impl CommandHandler for VitePlusCommandHandler {
if super::app_target::needs_elicitation(&subcmd, &command.cwd) {
return Ok(HandledCommand::Verbatim);
}
let resolved = self.resolver.resolve(subcmd, None, &command.envs).await?;
let resolved =
self.resolver.resolve(subcmd, None, &command.envs, &command.cwd).await?;
Ok(HandledCommand::Synthesized(resolved.into_synthetic_plan_request()))
}
CLIArgs::ViteTask(cmd) => Ok(HandledCommand::ViteTaskCommand(cmd)),
Expand Down
49 changes: 40 additions & 9 deletions packages/cli/binding/src/cli/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,25 @@ use super::{
types::{CliOptions, ResolvedSubcommand, ResolvedUniversalViteConfig, SynthesizableSubcommand},
};

/// The directory string handed to the JS `vite` resolver: the Vite app dir
/// selected by a `[root]` positional or an explicit `-c`/`--config` file
/// (where the app's config and plugins resolve `vite` from), falling back to
/// the command's cwd.
fn vite_resolver_dir(
args: &[String],
cwd: &AbsolutePath,
cwd_string: &str,
) -> anyhow::Result<String> {
match super::app_target::vite_config_dir(args, cwd) {
Some(dir) => Ok(dir
.as_path()
.to_str()
.ok_or_else(|| anyhow::anyhow!("vite root is not valid UTF-8"))?
.to_string()),
None => Ok(cwd_string.to_string()),
}
}

/// Resolves synthesizable subcommands to concrete programs and arguments.
/// Used by both direct CLI execution and CommandHandler.
pub struct SubcommandResolver {
Expand Down Expand Up @@ -62,25 +81,34 @@ impl SubcommandResolver {
}

/// Resolve a synthesizable subcommand to a concrete program, args, cache config, and envs.
/// `cwd` is the directory the resolved command will run in (the task cwd
/// for intercepted script commands); it is forwarded to the JS resolvers.
pub(super) async fn resolve(
&self,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePath,
) -> anyhow::Result<ResolvedSubcommand> {
self.resolve_inner(subcommand, resolved_vite_config, envs).await
self.resolve_inner(subcommand, resolved_vite_config, envs, cwd).await
}

async fn resolve_inner(
&self,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePath,
) -> anyhow::Result<ResolvedSubcommand> {
let cwd_string = cwd
.as_path()
.to_str()
.ok_or_else(|| anyhow::anyhow!("command cwd is not valid UTF-8"))?
.to_string();
match subcommand {
SynthesizableSubcommand::Lint { mut args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.lint)().await?;
let resolved = (cli_options.lint)(cwd_string.clone()).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand Down Expand Up @@ -117,7 +145,7 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Fmt { mut args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.fmt)().await?;
let resolved = (cli_options.fmt)(cwd_string.clone()).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand Down Expand Up @@ -153,7 +181,8 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Build { args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.vite)().await?;
let resolved =
(cli_options.vite)(vite_resolver_dir(&args, cwd, &cwd_string)?).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand Down Expand Up @@ -182,7 +211,7 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Test { args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.test)().await?;
let resolved = (cli_options.test)(cwd_string.clone()).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand Down Expand Up @@ -214,7 +243,7 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Pack { args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.pack)().await?;
let resolved = (cli_options.pack)(cwd_string.clone()).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand All @@ -236,7 +265,8 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Dev { args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.vite)().await?;
let resolved =
(cli_options.vite)(vite_resolver_dir(&args, cwd, &cwd_string)?).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand All @@ -254,7 +284,8 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Preview { args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.vite)().await?;
let resolved =
(cli_options.vite)(vite_resolver_dir(&args, cwd, &cwd_string)?).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand All @@ -272,7 +303,7 @@ impl SubcommandResolver {
}
SynthesizableSubcommand::Doc { args } => {
let cli_options = self.cli_options()?;
let resolved = (cli_options.doc)().await?;
let resolved = (cli_options.doc)(cwd_string.clone()).await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
Expand Down
9 changes: 6 additions & 3 deletions packages/cli/binding/src/cli/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,13 @@ pub(super) enum CLIArgs {
Toolchain(ToolchainArgs),
}

/// Type alias for boxed async resolver function
/// Type alias for boxed async resolver function. Takes the directory the
/// resolved command will run in (the task cwd for intercepted script
/// commands), so JS-side checks can resolve against the right package.
/// NOTE: Uses anyhow::Error to avoid NAPI type inference issues
pub type BoxedResolverFn =
Box<dyn Fn() -> Pin<Box<dyn Future<Output = anyhow::Result<ResolveCommandResult>> + 'static>>>;
pub type BoxedResolverFn = Box<
dyn Fn(String) -> Pin<Box<dyn Future<Output = anyhow::Result<ResolveCommandResult>> + 'static>>,
>;

/// Type alias for vite config resolver function (takes package path, returns JSON string)
/// Uses Arc for cloning and Send + Sync for use in UserConfigLoader
Expand Down
Loading
Loading