Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
163 changes: 163 additions & 0 deletions crates/aube-manifest/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,51 @@ impl PackageJson {
out
}

/// pnpm-compatible `npm_package_*` environment pairs for lifecycle
/// scripts. Mirrors what pnpm exports from a manifest: `name`,
/// `version`, plus the deep-flattened `engines`, `config`, and
/// `bin` fields (string `bin` → unsuffixed `npm_package_bin`).
/// Other fields (`description`, `main`, `license`, `author`, …)
/// are intentionally **not** exported — pnpm dropped whole-manifest
/// flattening, and matching its exact allowlist keeps scripts that
/// sniff these vars (`husky`, `node-pre-gyp`, …) behaving
/// identically under aube.
///
/// The `npm_package_json` path is set by the caller, which knows
/// where the manifest lives on disk.
///
/// Keys are "envified" the npm way: every character outside
/// `[A-Za-z0-9_]` becomes `_`, so `config.my-key` →
/// `npm_package_config_my_key`. Returned in a stable order
/// (name, version, then engines/config/bin in key order) so the
/// emitted environment is deterministic.
pub fn npm_package_env(&self) -> Vec<(String, String)> {
let mut out = Vec::new();
if let Some(name) = &self.name {
out.push(("npm_package_name".to_string(), name.clone()));
}
if let Some(version) = &self.version {
out.push(("npm_package_version".to_string(), version.clone()));
}
for (key, value) in &self.engines {
out.push((
format!("npm_package_engines_{}", envify_env_key(key)),
value.clone(),
));
}
if let Some(config) = self.extra.get("config") {
flatten_json_env("npm_package_config", config, &mut out);
}
if let Some(bin) = self.extra.get("bin") {
// Generic flatten, same as `config`: a string `bin` →
// unsuffixed `npm_package_bin`, an object → `npm_package_bin_<key>`.
// This mirrors pnpm exactly (verified against 11.5); npm instead
// normalizes a string `bin` to the package's unscoped name first.
flatten_json_env("npm_package_bin", bin, &mut out);
}
out
}

/// Extract `pnpm.catalog` / `aube.catalog` — a default catalog
/// defined inline in package.json under the `pnpm`/`aube` object.
/// pnpm itself reads catalogs only from `pnpm-workspace.yaml`, but
Expand Down Expand Up @@ -936,6 +981,43 @@ fn push_unique_strs(dst: &mut Vec<String>, arr: &[serde_json::Value]) {
}
}

/// npm/pnpm "envify": replace every character that is not
/// `[A-Za-z0-9_]` with `_`, leaving case untouched. Used to build the
/// `npm_package_*` env-var keys from manifest field names.
fn envify_env_key(key: &str) -> String {
key.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' {
c
} else {
'_'
}
})
.collect()
}

/// Deep-flatten a JSON value into `prefix`-rooted `npm_package_*`
/// pairs, npm-style: objects recurse with `_`-joined keys, arrays
/// index with `_<i>`, scalars stringify, `null` is skipped.
fn flatten_json_env(prefix: &str, value: &serde_json::Value, out: &mut Vec<(String, String)>) {
match value {
serde_json::Value::Object(map) => {
for (k, v) in map {
flatten_json_env(&format!("{prefix}_{}", envify_env_key(k)), v, out);
}
}
serde_json::Value::Array(arr) => {
for (i, v) in arr.iter().enumerate() {
flatten_json_env(&format!("{prefix}_{i}"), v, out);
}
}
serde_json::Value::String(s) => out.push((prefix.to_string(), s.clone())),
serde_json::Value::Number(n) => out.push((prefix.to_string(), n.to_string())),
serde_json::Value::Bool(b) => out.push((prefix.to_string(), b.to_string())),
serde_json::Value::Null => {}
}
}

/// Union of `package.json`'s `{pnpm,aube}.supportedArchitectures.*` and
/// `pnpm-workspace.yaml`'s `supportedArchitectures.*`. pnpm v10 treats
/// the workspace yaml as the canonical home for shared platform
Expand Down Expand Up @@ -1182,6 +1264,87 @@ mod tests {
serde_json::from_str(json).unwrap()
}

/// `npm_package_env` mirrors pnpm's exact flattening: name, version,
/// and deep `engines`/`config`/`bin` — and nothing else.
#[test]
fn npm_package_env_matches_pnpm_allowlist() {
let pkg = parse(
r#"{
"name": "@scope/envprobe",
"version": "4.5.6",
"description": "ignored",
"main": "index.js",
"type": "module",
"private": true,
"os": ["darwin"],
"engines": { "node": ">=18", "npm": ">=9" },
"config": { "port": "8080", "nested": { "deep-key": "x" } },
"bin": { "probe": "./cli.js" }
}"#,
);
let env: std::collections::BTreeMap<String, String> =
pkg.npm_package_env().into_iter().collect();

assert_eq!(
env.get("npm_package_name").map(String::as_str),
Some("@scope/envprobe")
);
assert_eq!(
env.get("npm_package_version").map(String::as_str),
Some("4.5.6")
);
assert_eq!(
env.get("npm_package_engines_node").map(String::as_str),
Some(">=18")
);
assert_eq!(
env.get("npm_package_engines_npm").map(String::as_str),
Some(">=9")
);
assert_eq!(
env.get("npm_package_config_port").map(String::as_str),
Some("8080")
);
// Nested objects flatten with `_`-joined, envified keys.
assert_eq!(
env.get("npm_package_config_nested_deep_key")
.map(String::as_str),
Some("x")
);
assert_eq!(
env.get("npm_package_bin_probe").map(String::as_str),
Some("./cli.js")
);
// Fields pnpm does not export must be absent.
for absent in [
"npm_package_description",
"npm_package_main",
"npm_package_type",
"npm_package_private",
"npm_package_os_0",
] {
assert!(!env.contains_key(absent), "{absent} should not be exported");
}
}

/// A bare-string `bin` flattens to the unsuffixed `npm_package_bin`
/// (pnpm verified against 11.5) — the same generic flattening as
/// `config`, not npm's normalize-to-unscoped-name behavior.
#[test]
fn npm_package_env_string_bin_is_unsuffixed() {
let pkg = parse(r#"{ "name": "@scope/tool", "version": "1.0.0", "bin": "./cli.js" }"#);
let env: std::collections::BTreeMap<String, String> =
pkg.npm_package_env().into_iter().collect();
assert_eq!(
env.get("npm_package_bin").map(String::as_str),
Some("./cli.js")
);
assert!(
!env.keys().any(|k| k.starts_with("npm_package_bin_")),
"string bin must stay unsuffixed: {env:?}"
);
}

/// Pre-npm-2.x publishes (e.g. `extsprintf@1.4.1`, `coffee-script@1.3.3`)
/// ship `"engines": ["node >=0.6.0"]` as an array rather than a map.
/// Modern npm ignores the legacy shape; we do the same rather than
Expand Down
40 changes: 28 additions & 12 deletions crates/aube-runtime/src/discover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,24 +150,30 @@ pub(crate) fn is_executable_file(path: &Path) -> bool {
true
}

/// The platform's `node` executable file name: `node.exe` on Windows,
/// `node` everywhere else. Single source of truth for the spots that
/// build or look up the node binary by name.
pub(crate) const fn node_exe_name() -> &'static str {
if cfg!(windows) { "node.exe" } else { "node" }
}

/// Per-OS layout of a native Node install: unix puts `node` under
/// `bin/`, Windows puts `node.exe` at the root (mise mirrors both).
pub(crate) fn node_paths_in(dir: &Path) -> (PathBuf, PathBuf) {
let exe_name = node_exe_name();
// Windows zips put node.exe at the archive root; mise (and some
// mirror layouts) use bin\node.exe instead. Prefer the root copy
// when it exists, otherwise fall through to the shared bin/ layout
// used on every OS.
if cfg!(windows) {
// Windows zips have node.exe at the archive root, but mise
// (and some mirrors' layouts) use bin\node.exe — accept both.
let root_exe = dir.join("node.exe");
let root_exe = dir.join(exe_name);
if root_exe.is_file() {
return (dir.to_path_buf(), root_exe);
}
let bin = dir.join("bin");
let exe = bin.join("node.exe");
(bin, exe)
} else {
let bin = dir.join("bin");
let exe = bin.join("node");
(bin, exe)
}
let bin = dir.join("bin");
let exe = bin.join(exe_name);
(bin, exe)
}

/// Find `node` on PATH and probe its version (`node --version`).
Expand All @@ -180,7 +186,7 @@ pub fn probe_path_node() -> Option<(node_semver::Version, PathBuf)> {
}

fn probe_path_node_uncached() -> Option<(node_semver::Version, PathBuf)> {
let exe = find_on_path(if cfg!(windows) { "node.exe" } else { "node" })?;
let exe = find_on_path(node_exe_name())?;
let output = std::process::Command::new(&exe)
.arg("--version")
.output()
Expand All @@ -193,6 +199,16 @@ fn probe_path_node_uncached() -> Option<(node_semver::Version, PathBuf)> {
Some((version, exe))
}

/// Locate a `node` executable on `PATH` without spawning it (unlike
/// [`probe_path_node`], which runs `node --version`). Cheap enough to
/// call on the hot install/run path to populate `npm_node_execpath` /
/// `NODE` for lifecycle scripts when no runtime switch is active.
/// Returns the absolute path of the first `node` (`node.exe` on
/// Windows) found in `PATH`.
pub fn node_on_path() -> Option<PathBuf> {
find_on_path(node_exe_name())
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/// Minimal PATH walk (std-only). Returns the first existing,
/// file-typed match.
pub(crate) fn find_on_path(bin_name: &str) -> Option<PathBuf> {
Expand Down Expand Up @@ -231,7 +247,7 @@ mod tests {
dir.join("bin")
};
std::fs::create_dir_all(&bin).unwrap();
let exe = bin.join(if cfg!(windows) { "node.exe" } else { "node" });
let exe = bin.join(node_exe_name());
std::fs::write(&exe, "#!/bin/sh\necho v0.0.0\n").unwrap();
#[cfg(unix)]
{
Expand Down
3 changes: 2 additions & 1 deletion crates/aube-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ mod sources;
mod spec;

pub use discover::{
InstallOrigin, InstalledNode, list_installed, mise_node_installs_dir, probe_path_node,
InstallOrigin, InstalledNode, list_installed, mise_node_installs_dir, node_on_path,
probe_path_node,
};
pub use error::Error;
pub use mise::mise_on_path;
Expand Down
81 changes: 70 additions & 11 deletions crates/aube-scripts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ pub struct ScriptSettings {
/// The resolved node executable, exported as `npm_node_execpath` /
/// `NODE` (npm parity) for every script.
pub node_exe: Option<PathBuf>,
/// The top-level package-manager command, exported as `npm_command`
/// (npm/pnpm parity): `"run-script"` for `aube run`, `"install"`
/// for install lifecycle hooks, `"rebuild"`, `"pack"`, etc. `None`
/// leaves `npm_command` unset.
pub command: Option<String>,
/// Path to a runnable `node-gyp` stand-in, exported as
/// `npm_config_node_gyp` (npm/pnpm parity). npm/pnpm point this at
/// their bundled `node-gyp/bin/node-gyp.js`; aube bootstraps node-gyp
/// lazily, so this is a tiny shim that resolves (and bootstraps on
/// first use) the real node-gyp and forwards argv. `None` leaves
/// `npm_config_node_gyp` unset.
pub node_gyp_js: Option<PathBuf>,
}

/// Native build jail applied to dependency lifecycle scripts.
Expand Down Expand Up @@ -495,6 +507,38 @@ fn apply_script_settings_env(cmd: &mut tokio::process::Command, settings: &Scrip
// spawn time) so it flows through both the jailed and the
// non-jailed paths.
cmd.env("npm_config_user_agent", aube_user_agent());
// `npm_execpath`: the package-manager binary that drove the script.
// Tools (and pnpm's own `$npm_execpath run …` postinstalls) read it
// to re-invoke the *same* PM. `current_exe()` is the aube binary;
// ignore the rare resolution failure rather than abort the script.
if let Ok(exe) = std::env::current_exe() {
cmd.env("npm_execpath", exe);
}
// `npm_node_execpath` / `NODE`: the node binary scripts should use
// — the switched runtime's node, or the ambient `node` on PATH.
// Set here (not at spawn) so it survives the jail's `env_clear`.
if let Some(node_exe) = settings.node_exe.as_deref() {
cmd.env("npm_node_execpath", node_exe).env("NODE", node_exe);
}
// `npm_command`: the top-level PM command (run-script / install / …).
if let Some(command) = settings.command.as_deref() {
cmd.env("npm_command", command);
}
// `npm_config_node_gyp`: path to a runnable node-gyp. npm/pnpm bundle
// node-gyp and point this at its `bin/node-gyp.js`; aube hands out a
// lazy shim that resolves the bootstrapped node-gyp on first use.
// The shim self-resolves via `AUBE_NODE_GYP_EXE` (the aube binary),
// so stamp that too unless a caller (e.g. `aube run`) already set a
// more specific value. `AUBE_NODE_GYP_PROJECT_DIR` is optional — the
// shim falls back to the script's cwd.
if let Some(node_gyp_js) = settings.node_gyp_js.as_deref() {
cmd.env("npm_config_node_gyp", node_gyp_js);
if std::env::var_os("AUBE_NODE_GYP_EXE").is_none()
&& let Ok(exe) = std::env::current_exe()
{
cmd.env("AUBE_NODE_GYP_EXE", exe);
}
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if let Some(node_options) = settings.node_options.as_deref() {
cmd.env("NODE_OPTIONS", node_options);
}
Expand All @@ -509,6 +553,27 @@ fn apply_script_settings_env(cmd: &mut tokio::process::Command, settings: &Scrip
}
}

/// Apply the manifest-derived `npm_package_*` env (name, version,
/// absolute `npm_package_json` path, and the deep-flattened
/// `engines`/`config`/`bin`) plus `npm_lifecycle_script` (the raw
/// script body) to a lifecycle command. Called last in `run_script`
/// so the values land *after* any jail `env_clear` and override a
/// parent aube invocation's leaked `npm_package_*` on the unjailed
/// path. `script_dir` is the directory the script runs in, whose
/// `package.json` is the manifest being executed.
fn apply_npm_manifest_env(
cmd: &mut tokio::process::Command,
manifest: &PackageJson,
script_dir: &Path,
script_cmd: &str,
) {
cmd.env("npm_lifecycle_script", script_cmd);
cmd.env("npm_package_json", script_dir.join("package.json"));
for (key, value) in manifest.npm_package_env() {
cmd.env(key, value);
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

fn safe_jail_env_key(key: &str) -> bool {
const EXACT: &[&str] = &[
"PATH",
Expand Down Expand Up @@ -884,11 +949,6 @@ pub async fn run_script(
.stderr(child_stderr())
.env("PATH", &new_path)
.env("npm_lifecycle_event", script_name);
// Set after the jail's env_clear (builder env calls compose in
// order), so jailed builds see the pinned node too.
if let Some(node_exe) = &settings.node_exe {
cmd.env("npm_node_execpath", node_exe).env("NODE", node_exe);
}

// Pass INIT_CWD the way npm/pnpm do — the directory the user
// invoked the package manager from, *not* the script's own cwd.
Expand All @@ -900,12 +960,6 @@ pub async fn run_script(
cmd.env("INIT_CWD", project_root);
}

if let Some(ref name) = manifest.name {
cmd.env("npm_package_name", name);
}
if let Some(ref version) = manifest.version {
cmd.env("npm_package_version", version);
}
if let (Some(jail), Some(home)) = (jail, jail_home.as_deref()) {
apply_jail_env(
&mut cmd,
Expand All @@ -919,6 +973,11 @@ pub async fn run_script(
apply_script_settings_env(&mut cmd, &settings);
}

// npm-compat manifest env, applied last so it survives the jail's
// `env_clear`: name/version/json plus the deep-flattened
// engines/config/bin, and the raw script body (`npm_lifecycle_script`).
apply_npm_manifest_env(&mut cmd, manifest, script_dir, script_cmd);

tracing::debug!("lifecycle: {script_name} → {script_cmd}");
let status = run_command_killing_descendants(cmd, script_name).await?;

Expand Down
Loading
Loading