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,55 @@
# core_version_guard

## `vp build`

**Exit code:** 1

```
error: Your `vite` alias uses @voidzero-dev/vite-plus-core@<version>.
This Vite+ CLI requires @voidzero-dev/vite-plus-core@<version>.

Choose a fix:
- Update the `vite` alias to npm:@voidzero-dev/vite-plus-core@<version>.
- Run `vp migrate`.

To skip this check, set VP_SKIP_CORE_VERSION_CHECK=1.
```

## `vp test`

**Exit code:** 1

```
error: Your `vite` alias uses @voidzero-dev/vite-plus-core@<version>.
This Vite+ CLI requires @voidzero-dev/vite-plus-core@<version>.

Choose a fix:
- Update the `vite` alias to npm:@voidzero-dev/vite-plus-core@<version>.
- Run `vp migrate`.

To skip this check, set VP_SKIP_CORE_VERSION_CHECK=1.
```

## `vp build app`

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

```
✓ 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>
```
24 changes: 15 additions & 9 deletions packages/cli/binding/index.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -3444,12 +3444,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;
/** Whether the user supplied the global `-C` option. */
explicitChdir?: boolean;
Expand Down Expand Up @@ -3569,10 +3569,16 @@ export declare function getVpDirs(): VpDirsJs;
*/
export declare function hasConfigKey(viteConfigPath: string, configKey: string): boolean;

/** Result returned by JavaScript resolver functions. */
/**
* A command or tagged user error returned by a JavaScript resolver.
* Successful results contain `binPath` and `envs`. User errors contain
* `errorKind` and `errorMessage`.
*/
export interface JsCommandResolvedResult {
binPath: string;
envs: Record<string, string>;
binPath?: string;
envs?: Record<string, string>;
errorKind?: string;
errorMessage?: string;
}

/**
Expand Down
111 changes: 111 additions & 0 deletions packages/cli/binding/src/cli/app_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,79 @@ fn app_command_parts(subcommand: &SynthesizableSubcommand) -> Option<(&'static s
}
}

/// Boolean flags of the Vite CLI (dev/build/preview), from the shipped
/// `vp <command> --help` (snap-tests/command-helper); keep in sync. Under
/// cac/mri parsing every OTHER flag — required-value, optional-value
/// (`--host [host]`), or unknown — consumes a following non-flag token as
/// its value, so only tokens no flag consumes are positional targets.
const VITE_BOOLEAN_FLAGS: &[&str] = &[
"-w",
"--watch",
"--app",
"--clearScreen",
"--cors",
"--emptyOutDir",
"--experimentalBundle",
"--force",
"--profile",
"--strictPort",
];

/// 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 with cac/mri value consumption and scans them all 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())
}

/// Does the workspace root have an intent signal for this app command?
/// This signal selects the root. It does not prove that the command succeeds.
/// The `defaultPackage` lookup passes the config that [`classify`] already
Expand Down Expand Up @@ -423,6 +496,44 @@ mod tests {
}
}

#[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 vite_commands_share_the_source_index_signal() {
let temp = tempfile::tempdir().expect("temporary directory should exist");
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
Loading
Loading