Skip to content
13 changes: 13 additions & 0 deletions src/install/PackageManager/PackageManagerEnqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2390,6 +2390,19 @@ fn get_or_put_resolved_package(

let find_result_opt: Option<Npm::FindResult> = match version_result {
Npm::FindVersionResult::Found(result) => Some(result),
Npm::FindVersionResult::FoundLatestFallback(result) => {
let package_name = this.lockfile.str(&name);
this.log_mut().add_warning_fmt(
None,
bun_ast::Loc::EMPTY,
format_args!(
"\"{}\" dist-tags.latest does not match a published version, falling back to {}",
bstr::BStr::new(package_name),
result.version.fmt(&manifest.string_buf),
),
);
Some(result)
}
Npm::FindVersionResult::FoundWithFilter {
result,
newest_filtered,
Expand Down
58 changes: 58 additions & 0 deletions src/install/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1535,6 +1535,40 @@ impl PackageManifest {
None
}

/// Highest release, or highest prerelease if there are no releases.
/// Both lists are sorted ascending at serialization time.
Comment thread
robobun marked this conversation as resolved.
Resolved
fn find_highest_version(
&self,
min_age_ms: Option<f64>,
had_too_recent: &mut bool,
) -> Option<FindResult<'_>> {
for list in [&self.pkg.releases, &self.pkg.prereleases] {
let keys = list.keys.get(&self.versions);
if keys.is_empty() {
continue;
}
let values = list.values.get(&self.package_versions);
let mut i = keys.len();
while i > 0 {
i -= 1;
let package = &values[i];
if let Some(min_age_ms) = min_age_ms {
if Self::is_package_version_too_recent(package, min_age_ms) {
*had_too_recent = true;
continue;
}
}
return Some(FindResult {
version: keys[i],
package,
});
}
// every release is age-gated; do not fall through to prereleases
return None;
}
None
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

pub(crate) fn should_exclude_from_age_filter(&self, exclusions: Option<&[&[u8]]>) -> bool {
if let Some(excl) = exclusions {
let pkg_name = self.name();
Expand Down Expand Up @@ -1644,6 +1678,9 @@ pub enum FindVersionResult<'a> {
result: FindResult<'a>,
newest_filtered: Option<Semver::Version>,
},
/// `dist-tags.latest` did not resolve to a known version; fell back to the
/// highest published version.
Comment thread
robobun marked this conversation as resolved.
Resolved
FoundLatestFallback(FindResult<'a>),
Comment thread
robobun marked this conversation as resolved.
Resolved
Err(FindVersionError),
}

Expand All @@ -1652,6 +1689,7 @@ impl<'a> FindVersionResult<'a> {
match self {
FindVersionResult::Found(result) => Some(result),
FindVersionResult::FoundWithFilter { result, .. } => Some(result),
FindVersionResult::FoundLatestFallback(result) => Some(result),
FindVersionResult::Err(_) => None,
}
}
Expand All @@ -1676,6 +1714,26 @@ impl PackageManifest {
exclusions: Option<&[&[u8]]>,
) -> FindVersionResult<'_> {
let Some(dist_result) = self.find_by_dist_tag(tag) else {
// https://github.com/oven-sh/bun/issues/12041: match npm and let
// `latest` fall back to the highest published version when the
// manifest's `dist-tags.latest` is stale or missing.
Comment thread
robobun marked this conversation as resolved.
Resolved
if tag == b"latest" {
let min_age_gate_ms = match minimum_release_age_ms {
Some(min_age_ms) if !self.should_exclude_from_age_filter(exclusions) => {
Some(min_age_ms)
}
_ => None,
};
Comment thread
robobun marked this conversation as resolved.
Resolved
let mut had_too_recent = false;
if let Some(highest) =
self.find_highest_version(min_age_gate_ms, &mut had_too_recent)
{
return FindVersionResult::FoundLatestFallback(highest);
}
if had_too_recent {
return FindVersionResult::Err(FindVersionError::AllVersionsTooRecent);
}
}
return FindVersionResult::Err(FindVersionError::NotFound);
};
let min_age_gate_ms = match minimum_release_age_ms {
Expand Down
5 changes: 4 additions & 1 deletion src/runtime/cli/outdated_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,10 @@ impl OutdatedCommand {
continue;
};

let Some(actual_latest) = manifest.find_by_dist_tag(b"latest") else {
let Some(actual_latest) = manifest
.find_by_dist_tag_with_filter(b"latest", None, None)
.unwrap()
else {
Comment thread
robobun marked this conversation as resolved.
Resolved
continue;
};

Expand Down
180 changes: 180 additions & 0 deletions test/cli/install/bun-update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -527,3 +527,183 @@ it("should print UTF-8 arrows correctly with colors enabled", async () => {
expect(out).not.toContain("â†");
expect(await exited2).toBe(0);
});

// https://github.com/oven-sh/bun/issues/12041
// Registry mirrors/CDNs can briefly serve a manifest whose `dist-tags.latest`
// points at a version that has not yet propagated into `versions`. `bun update
// --latest` should fall back to the highest published version rather than
// aborting the whole update.
it("should fall back to the highest version when dist-tags.latest is not in versions", async () => {
const urls: string[] = [];
// dist-tags.latest = 0.0.7 but only 0.0.3 and 0.0.5 are in `versions`
setHandler(
dummyRegistry(urls, {
"0.0.3": { bin: { "baz-run": "index.js" } },
"0.0.5": { bin: { "baz-exec": "index.js" } },
latest: "0.0.7",
}),
);
await writeFile(
join(package_dir, "package.json"),
JSON.stringify({
name: "foo",
dependencies: { baz: "0.0.3" },
}),
);

const install = spawn({
cmd: [bunExe(), "install", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [, installErr, installExit] = await Promise.all([
new Response(install.stdout).text(),
new Response(install.stderr).text(),
install.exited,
]);
expect(installErr).not.toContain("error:");
expect(installExit).toBe(0);

const { stdout, stderr, exited } = spawn({
cmd: [bunExe(), "update", "--latest", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [out, err, exitCode] = await Promise.all([new Response(stdout).text(), new Response(stderr).text(), exited]);

expect(err).not.toContain('with tag "latest" not found');
expect(err).not.toContain("failed to resolve");
expect(err).toContain("warn:");
expect(err).toContain("falling back to 0.0.5");
expect(out).toContain("baz 0.0.3 -> 0.0.5");
expect(exitCode).toBe(0);

expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toMatchObject({
name: "baz",
version: "0.0.5",
});
});

it("should fall back to the highest version when the manifest has no dist-tags", async () => {
const urls: string[] = [];
setHandler(async request => {
urls.push(request.url);
const url = request.url.replaceAll("%2f", "/");
if (url.endsWith(".tgz")) {
return new Response(file(join(import.meta.dir, "baz-0.0.3.tgz")));
}
const name = url.slice(url.indexOf("/", root_url.length) + 1);
return new Response(
JSON.stringify({
name,
versions: {
"0.0.3": {
name,
version: "0.0.3",
bin: { "baz-run": "index.js" },
dist: { tarball: `${root_url}/${name}-0.0.3.tgz` },
},
},
// no "dist-tags"
}),
);
});
await writeFile(
join(package_dir, "package.json"),
JSON.stringify({
name: "foo",
dependencies: { baz: "0.0.3" },
}),
);

const install = spawn({
cmd: [bunExe(), "install", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [, installErr, installExit] = await Promise.all([
new Response(install.stdout).text(),
new Response(install.stderr).text(),
install.exited,
]);
expect(installErr).not.toContain("error:");
expect(installExit).toBe(0);

const { stdout, stderr, exited } = spawn({
cmd: [bunExe(), "update", "--latest", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [out, err, exitCode] = await Promise.all([new Response(stdout).text(), new Response(stderr).text(), exited]);

expect(err).not.toContain('with tag "latest" not found');
expect(err).not.toContain("failed to resolve");
expect(exitCode).toBe(0);

expect(await file(join(package_dir, "node_modules", "baz", "package.json")).json()).toMatchObject({
name: "baz",
version: "0.0.3",
});
Comment thread
robobun marked this conversation as resolved.
Resolved
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

it("should fall back to the highest prerelease when the manifest has no releases and no dist-tags", async () => {
setHandler(async request => {
const url = request.url.replaceAll("%2f", "/");
if (url.endsWith(".tgz")) {
return new Response(file(join(import.meta.dir, "baz-0.0.3.tgz")));
}
const name = url.slice(url.indexOf("/", root_url.length) + 1);
const pre = (v: string) => ({ name, version: v, dist: { tarball: `${root_url}/${name}-${v}.tgz` } });
return new Response(
JSON.stringify({
name,
versions: {
"1.0.0-beta.1": pre("1.0.0-beta.1"),
"1.0.0-beta.2": pre("1.0.0-beta.2"),
},
// no "dist-tags", no stable releases
}),
);
});
await writeFile(
join(package_dir, "package.json"),
JSON.stringify({ name: "foo", dependencies: { baz: "1.0.0-beta.1" } }),
);

const install = spawn({
cmd: [bunExe(), "install", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [, installErr, installExit] = await Promise.all([
new Response(install.stdout).text(),
new Response(install.stderr).text(),
install.exited,
]);
expect(installErr).not.toContain("error:");
expect(installExit).toBe(0);

const { stdout, stderr, exited } = spawn({
cmd: [bunExe(), "update", "--latest", "--linker=hoisted"],
cwd: package_dir,
stdout: "pipe",
stderr: "pipe",
env,
});
const [, err, exitCode] = await Promise.all([new Response(stdout).text(), new Response(stderr).text(), exited]);

expect(err).not.toContain('with tag "latest" not found');
expect(err).not.toContain("failed to resolve");
expect(err).toContain("falling back to 1.0.0-beta.2");
expect(exitCode).toBe(0);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
Loading