Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions Cargo.lock

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

14 changes: 14 additions & 0 deletions crates/aube-codes/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ pub const ERR_AUBE_PATCHES_TRACKING_WRITE: &str = "ERR_AUBE_PATCHES_TRACKING_WRI
pub const ERR_AUBE_UNSAFE_SHEBANG_INTERPRETER: &str = "ERR_AUBE_UNSAFE_SHEBANG_INTERPRETER";
pub const ERR_AUBE_EMBED_INVALID_PROJECT: &str = "ERR_AUBE_EMBED_INVALID_PROJECT";
pub const ERR_AUBE_EMBED_INSTALL_FAILED: &str = "ERR_AUBE_EMBED_INSTALL_FAILED";
pub const ERR_AUBE_EMBED_INVALID_SETTING: &str = "ERR_AUBE_EMBED_INVALID_SETTING";
pub const ERR_AUBE_EMBED_ALREADY_INITIALIZED: &str = "ERR_AUBE_EMBED_ALREADY_INITIALIZED";
pub const ERR_AUBE_FFI_INVALID_ARGUMENT: &str = "ERR_AUBE_FFI_INVALID_ARGUMENT";
pub const ERR_AUBE_FFI_UNKNOWN_HANDLE: &str = "ERR_AUBE_FFI_UNKNOWN_HANDLE";
pub const ERR_AUBE_FFI_RUNTIME: &str = "ERR_AUBE_FFI_RUNTIME";
Expand Down Expand Up @@ -579,6 +581,18 @@ pub const ALL: &[CodeMeta] = &[
description: "An in-process embedder could not initialize its host callback or received an install failure without a more specific stable code.",
exit_code: None,
},
CodeMeta {
name: ERR_AUBE_EMBED_INVALID_SETTING,
category: category::MISC_SAFETY,
description: "An in-process embedder passed a setting default whose name is not a canonical aube setting.",
exit_code: None,
},
CodeMeta {
name: ERR_AUBE_EMBED_ALREADY_INITIALIZED,
category: category::MISC_SAFETY,
description: "An in-process embedder tried to register setting defaults after the process already initialized its embedder profile.",
exit_code: None,
},
CodeMeta {
name: ERR_AUBE_FFI_INVALID_ARGUMENT,
category: category::MISC_SAFETY,
Expand Down
1 change: 1 addition & 0 deletions crates/aube-node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ crate-type = ["cdylib"]
aube = { workspace = true }
aube-codes = { workspace = true }
aube-registry = { workspace = true }
aube-settings = { workspace = true }
miette = { workspace = true }
napi = { workspace = true }
napi-derive = { workspace = true }
Expand Down
25 changes: 25 additions & 0 deletions crates/aube-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,31 @@ Rejected promises are `AubeError` objects with a stable `code` and a
human-readable `diagnostic`. Published `ERR_AUBE_*` values follow aube's
[error-code stability policy](https://github.com/jdx/aube/blob/main/docs/error-codes.md).

## Configuration

Register embedder setting defaults before the first `install`:

```ts
import { configure, install } from "@jdxcode/aube-node"

configure({
defaults: {
minimumReleaseAge: "259200", // seconds; 3-day cooldown for fresh releases
},
})
```

Defaults use canonical setting names and sit at the lowest precedence —
environment variables, project files, and user configuration all override
them. Registration is process-global and first-write-wins: calling
`configure` after an install (or a second time) rejects with
`ERR_AUBE_EMBED_ALREADY_INITIALIZED`, and unknown setting names reject with
`ERR_AUBE_EMBED_INVALID_SETTING`. Without a `configure` call the addon
applies its built-in defaults (`nodeLinker=hoisted`, `minimumReleaseAge=0`).

Per-install, `osvTransitiveCheck: true` forces a live transitive OSV check
even when resolution reused every version from the existing lockfile.

## Compiled Bun executables

Add `bunPlugin({ os, arch, libc })` from `@jdxcode/aube-node/bun-plugin` to each
Expand Down
15 changes: 15 additions & 0 deletions crates/aube-node/npm/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,19 @@ export interface AubeError extends Error {
diagnostic: string
}

export type ConfigureInput = {
/**
* Embedder setting defaults by canonical setting name (e.g.
* `minimumReleaseAge`). Lowest precedence: environment variables, project
* files, and user configuration all override them.
*/
defaults?: Record<string, string>
}
export type InstallInput = {
add?: { name: string; version?: string; dev?: boolean }[]
force?: boolean
offline?: boolean
osvTransitiveCheck?: boolean
onEvent?: (event: InstallEvent) => void
signal?: AbortSignal
}
Expand All @@ -31,4 +40,10 @@ export type InstallResult = {
downloaded: number
durationMs: number
}
/**
* Register embedder setting defaults for this process. Call before the first
* `install`; later (or repeated) calls throw `ERR_AUBE_EMBED_ALREADY_INITIALIZED`,
* and unknown setting names throw `ERR_AUBE_EMBED_INVALID_SETTING`.
*/
export function configure(input?: ConfigureInput): void
export function install(projectDir: string, input?: InstallInput): Promise<InstallResult>
1 change: 1 addition & 0 deletions crates/aube-node/npm/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ function load() {
}

const addon = load()
exports.configure = addon.configure
exports.install = addon.install
5 changes: 4 additions & 1 deletion crates/aube-node/npm/typecheck.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { install, type AubeError, type InstallEvent } from "@jdxcode/aube-node"
import { configure, install, type AubeError, type InstallEvent } from "@jdxcode/aube-node"

function handleEvent(event: InstallEvent) {
switch (event.kind) {
Expand All @@ -15,8 +15,11 @@ function handleEvent(event: InstallEvent) {
}
}

configure({ defaults: { minimumReleaseAge: "259200" } })

const controller = new AbortController()
install(".", {
osvTransitiveCheck: true,
add: [{ name: "typescript", version: "latest", dev: true }],
signal: controller.signal,
onEvent: handleEvent,
Expand Down
166 changes: 157 additions & 9 deletions crates/aube-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ use napi::bindgen_prelude::{
use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode};
use napi::{Env, Status};
use napi_derive::napi;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;

Expand Down Expand Up @@ -47,6 +49,87 @@ static NODE_HOST: embed::Host = embed::Host {
self_update_enabled: false,
};

/// Whether this process has registered its embedder profile and setting
/// defaults. `configure` and the first `install` race for it; registration is
/// process-global and first-write-wins, so a `configure` that loses the race
/// must fail loudly rather than silently not apply.
static EMBEDDER_INITIALIZED: AtomicBool = AtomicBool::new(false);

fn builtin_defaults() -> Vec<(String, String)> {
vec![
("nodeLinker".to_string(), "hoisted".to_string()),
("minimumReleaseAge".to_string(), "0".to_string()),
]
}

fn merged_defaults(overrides: Vec<(String, String)>) -> Vec<(String, String)> {
let mut merged = builtin_defaults();
for (key, value) in overrides {
match merged.iter_mut().find(|(name, _)| *name == key) {
Some(existing) => existing.1 = value,
None => merged.push((key, value)),
}
}
merged
}

fn validate_defaults(defaults: HashMap<String, String>) -> Result<Vec<(String, String)>, String> {
let mut overrides = defaults.into_iter().collect::<Vec<_>>();
// HashMap iteration order is random; keep registration deterministic.
overrides.sort();
for (key, _) in &overrides {
if aube_settings::find(key).is_none() {
return Err(key.clone());
}
}
Ok(overrides)
}

#[napi(object)]
pub struct ConfigureInput {
/// Embedder setting defaults by canonical setting name (e.g.
/// `minimumReleaseAge`). They sit at the lowest precedence, below
/// environment variables, project files, and user configuration.
pub defaults: Option<HashMap<String, String>>,
}

/// Register embedder setting defaults for this process.
///
/// Call before the first `install`; registration is process-global and
/// first-write-wins, so calling after an install (or a second time) rejects
/// with `ERR_AUBE_EMBED_ALREADY_INITIALIZED`. Unknown setting names reject
/// with `ERR_AUBE_EMBED_INVALID_SETTING`.
#[napi(catch_unwind)]
pub fn configure(env: &Env, input: Option<ConfigureInput>) -> NodeResult<()> {
let defaults = input.and_then(|input| input.defaults).unwrap_or_default();
let overrides = validate_defaults(defaults).map_err(|key| {
into_napi_error(
env,
InstallFailure {
code: aube_codes::errors::ERR_AUBE_EMBED_INVALID_SETTING.to_string(),
message: format!("unknown setting {key:?}"),
diagnostic: format!(
"{key:?} is not a canonical aube setting name; see https://aube.jdx.dev/settings"
),
},
)
})?;
if EMBEDDER_INITIALIZED.swap(true, Ordering::SeqCst) {
return Err(into_napi_error(
env,
InstallFailure {
code: aube_codes::errors::ERR_AUBE_EMBED_ALREADY_INITIALIZED.to_string(),
message: "configure must be called before the first install".to_string(),
diagnostic: "embedder defaults are process-global and first-write-wins; this \
process already registered them"
.to_string(),
},
));
}
embed::initialize(&NODE_HOST, merged_defaults(overrides));
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Ok(())
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

#[napi(object)]
pub struct PackageToAdd {
pub name: String,
Expand All @@ -59,6 +142,7 @@ pub struct InstallInput {
pub add: Option<Vec<PackageToAdd>>,
pub force: Option<bool>,
pub offline: Option<bool>,
pub osv_transitive_check: Option<bool>,
pub on_event: Option<Function<'static, FnArgs<(InstallEventPayload,)>, ()>>,
pub signal: Option<Object<'static>>,
}
Expand Down Expand Up @@ -136,12 +220,14 @@ pub fn install<'env>(
add,
force,
offline,
osv_transitive_check,
on_event,
signal,
} = input.unwrap_or(InstallInput {
add: None,
force: None,
offline: None,
osv_transitive_check: None,
on_event: None,
signal: None,
});
Expand Down Expand Up @@ -195,11 +281,21 @@ pub fn install<'env>(
.collect::<Vec<_>>();
let force = force.unwrap_or(false);
let offline = offline.unwrap_or(false);
let osv_transitive_check = osv_transitive_check.unwrap_or(false);

env.spawn_future_with_callback(
async move {
Ok::<_, napi::Error>(
run_install(project_dir, packages, force, offline, control, stats).await,
run_install(
project_dir,
packages,
force,
offline,
osv_transitive_check,
control,
stats,
)
.await,
)
},
|env, result| match result {
Expand All @@ -214,6 +310,7 @@ async fn run_install(
packages: Vec<(String, bool)>,
force: bool,
offline: bool,
osv_transitive_check: bool,
control: InstallControl,
stats: Arc<Mutex<InstallStats>>,
) -> Result<InstallResult, InstallFailure> {
Expand Down Expand Up @@ -244,7 +341,7 @@ async fn run_install(
dangerously_allow_all_builds: false,
offline,
dep_selection,
osv_transitive_check: false,
osv_transitive_check,
control: control.clone(),
},
)
Expand All @@ -256,6 +353,7 @@ async fn run_install(
options.ignore_scripts = true;
options.force = force;
options.dep_selection = dep_selection;
options.osv_transitive_check = osv_transitive_check;
options.control = control;
if offline {
options.network_mode = NetworkMode::Offline;
Expand Down Expand Up @@ -296,13 +394,10 @@ fn npmrc_dep_selection(project_dir: &Path) -> DepSelection {
}

fn initialize_embedder() {
embed::initialize(
&NODE_HOST,
vec![
("nodeLinker".to_string(), "hoisted".to_string()),
("minimumReleaseAge".to_string(), "0".to_string()),
],
);
if EMBEDDER_INITIALIZED.swap(true, Ordering::SeqCst) {
return;
}
embed::initialize(&NODE_HOST, builtin_defaults());
}

async fn prepare_project_dir(project_dir: &Path) -> Result<PathBuf, InstallFailure> {
Expand Down Expand Up @@ -442,3 +537,56 @@ fn level_name(level: InstallOutputLevel) -> &'static str {
InstallOutputLevel::Error => "error",
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn merged_defaults_lets_overrides_replace_builtins() {
let merged = merged_defaults(vec![(
"minimumReleaseAge".to_string(),
"259200".to_string(),
)]);
assert!(merged.contains(&("minimumReleaseAge".to_string(), "259200".to_string())));
assert!(merged.contains(&("nodeLinker".to_string(), "hoisted".to_string())));
assert_eq!(
merged
.iter()
.filter(|(key, _)| key == "minimumReleaseAge")
.count(),
1
);
}

#[test]
fn merged_defaults_appends_settings_without_builtin_values() {
let merged = merged_defaults(vec![("paranoid".to_string(), "true".to_string())]);
assert!(merged.contains(&("paranoid".to_string(), "true".to_string())));
assert_eq!(merged.len(), builtin_defaults().len() + 1);
}

#[test]
fn validate_defaults_rejects_unknown_setting_names() {
let defaults = HashMap::from([("minimumRelaseAge".to_string(), "259200".to_string())]);
assert_eq!(
validate_defaults(defaults),
Err("minimumRelaseAge".to_string())
);
}

#[test]
fn validate_defaults_sorts_canonical_names() {
let defaults = HashMap::from([
("nodeLinker".to_string(), "hoisted".to_string()),
("minimumReleaseAge".to_string(), "259200".to_string()),
]);
assert_eq!(
validate_defaults(defaults),
Ok(vec![
("minimumReleaseAge".to_string(), "259200".to_string()),
("nodeLinker".to_string(), "hoisted".to_string()),
])
);
}
}
Loading
Loading