diff --git a/src/install/NetworkTask.rs b/src/install/NetworkTask.rs index 0deecd3fa898..c7b58bde8c2c 100644 --- a/src/install/NetworkTask.rs +++ b/src/install/NetworkTask.rs @@ -117,6 +117,7 @@ pub enum Callback { #[derive(Default, Clone, Copy)] pub struct DedupeMapEntry { + /// Once `failed`, this says whether the failure was an error or a warning, and stays. pub(crate) is_required: bool, /// Set once the download/extract for this task id has terminally failed so a /// later `enqueue_*_for_download` can observe the failure instead of diff --git a/src/install/PackageInstaller.rs b/src/install/PackageInstaller.rs index a73884b9ccba..c23d2d6cb369 100644 --- a/src/install/PackageInstaller.rs +++ b/src/install/PackageInstaller.rs @@ -91,6 +91,7 @@ pub struct PackageInstaller<'a> { pub(crate) destination_dir_subpath_buf: PathBuffer, pub(crate) folder_path_buf: PathBuffer, pub(crate) successfully_installed: Bitset, + pub(crate) required_packages: lockfile::tree::RequiredPackages<'a>, pub(crate) command_ctx: Command::Context<'a>, pub(crate) current_tree_id: lockfile::tree::Id, /// Trees that live under a self-contained workspace: packages there are copied @@ -1604,6 +1605,9 @@ impl<'a> PackageInstaller<'a> { } else { patch_name_and_version_hash }; + let is_required = + self.required_packages + .contains(self.manager(), dependency_id, package_id); match resolution.tag { resolution::Tag::Git => { if package_manager::enqueue_git_for_checkout( @@ -1613,6 +1617,7 @@ impl<'a> PackageInstaller<'a> { resolution, context, download_patch_hash, + is_required, ) == package_manager::GitEnqueueResult::OfflineMiss { self.increment_tree_install_count( @@ -1632,6 +1637,7 @@ impl<'a> PackageInstaller<'a> { &url, context, download_patch_hash, + is_required, ) { Ok(()) => {} Err(ForTarballError::OutOfMemory) => bun_core::out_of_memory(), @@ -1664,6 +1670,7 @@ impl<'a> PackageInstaller<'a> { resolution.remote_tarball().slice(string_buf!()), context, download_patch_hash, + is_required, ) { Ok(()) => {} Err(ForTarballError::OutOfMemory) => bun_core::out_of_memory(), @@ -1702,6 +1709,7 @@ impl<'a> PackageInstaller<'a> { npm.url.slice(string_buf!()), context, download_patch_hash, + is_required, ) { Ok(()) => {} Err(ForTarballError::OutOfMemory) => bun_core::out_of_memory(), diff --git a/src/install/PackageManager/PackageManagerEnqueue.rs b/src/install/PackageManager/PackageManagerEnqueue.rs index ea9ec05aa566..74e6c625ee6f 100644 --- a/src/install/PackageManager/PackageManagerEnqueue.rs +++ b/src/install/PackageManager/PackageManagerEnqueue.rs @@ -146,6 +146,7 @@ pub fn enqueue_dependency_list( this.drain_dependency_list(); } +/// `is_required` is `RequiredPackages::contains`, not the behavior of `dependency_id` alone. pub fn enqueue_tarball_for_download( this: &mut PackageManager, dependency_id: DependencyID, @@ -153,15 +154,13 @@ pub fn enqueue_tarball_for_download( url: &[u8], task_context: TaskCallbackContext, patch_name_and_version_hash: Option, + is_required: bool, ) -> Result<(), EnqueueTarballForDownloadError> { let task_id = Task::Id::for_tarball(url); - if this.network_task_has_failed(task_id) { + if download_already_failed(this, task_id, is_required) { return Err(EnqueueTarballForDownloadError::AlreadyFailed); } if this.options.offline == crate::package_manager_real::options::OfflineMode::Offline { - let is_required = this.lockfile.buffers.dependencies[dependency_id as usize] - .behavior - .is_required(); let name = this .lockfile .str(&this.lockfile.packages.get(package_id as usize).name) @@ -181,9 +180,6 @@ pub fn enqueue_tarball_for_download( return Ok(()); } - let is_required = this.lockfile.buffers.dependencies[dependency_id as usize] - .behavior - .is_required(); let package = *this.lockfile.packages.get(package_id as usize); if let Some(task) = run_tasks::generate_network_task_for_tarball( this, @@ -261,6 +257,7 @@ pub enum GitEnqueueResult { OfflineMiss, } +/// `is_required`: see `enqueue_tarball_for_download`. pub fn enqueue_git_for_checkout( this: &mut PackageManager, dependency_id: DependencyID, @@ -268,6 +265,7 @@ pub fn enqueue_git_for_checkout( resolution: &Resolution, task_context: TaskCallbackContext, patch_name_and_version_hash: Option, + is_required: bool, ) -> GitEnqueueResult { // SAFETY: caller passes `resolution.tag == Git`; the `git` arm is the // active union field. Copy out so the value no longer borrows @@ -285,13 +283,10 @@ pub fn enqueue_git_for_checkout( let checkout_id = Task::Id::for_git_checkout(url, resolved); // --offline: decide before any queue registration, so an optional miss leaves // nothing behind and a later required edge still reaches the report - if this.git_repositories.get(&clone_id).is_none() { - let is_required = this.lockfile.buffers.dependencies[dependency_id as usize] - .behavior - .is_required(); - if offline_git_miss(this, clone_id, alias, is_required) { - return GitEnqueueResult::OfflineMiss; - } + if this.git_repositories.get(&clone_id).is_none() + && offline_git_miss(this, clone_id, alias, is_required) + { + return GitEnqueueResult::OfflineMiss; } let checkout_queue = this .task_queue @@ -340,6 +335,28 @@ pub fn enqueue_git_for_checkout( GitEnqueueResult::Queued } +/// An optional-only failure was reported as a warning, so a required request downloads again. +fn download_already_failed( + this: &mut PackageManager, + task_id: Task::Id, + is_required: bool, +) -> bool { + let Some(entry) = this.network_dedupe_map.get_mut(&task_id) else { + return false; + }; + if !entry.failed { + entry.is_required |= is_required; + return false; + } + if entry.is_required || !is_required { + return true; + } + let _ = this.network_dedupe_map.remove(&task_id); + // No task runs for this id, so nothing would call the callbacks left in its queue. + let _ = this.task_queue.remove(&task_id); + false +} + /// Under `--offline`, an install-phase request for a package that is not in the cache /// (these helpers are only reached after the cache lookup missed): report it once if /// required, skip if optional, and never register a task nobody will complete. @@ -452,6 +469,7 @@ pub unsafe fn enqueue_parse_npm_package( unsafe { &raw mut (*task.as_ptr()).threadpool_task } } +/// `is_required`: see `enqueue_tarball_for_download`. pub fn enqueue_package_for_download( this: &mut PackageManager, name: &[u8], @@ -461,18 +479,14 @@ pub fn enqueue_package_for_download( url: &[u8], task_context: TaskCallbackContext, patch_name_and_version_hash: Option, + is_required: bool, ) -> Result<(), EnqueuePackageForDownloadError> { let task_id = Task::Id::for_npm_package(name, version); - if this.network_task_has_failed(task_id) { + if download_already_failed(this, task_id, is_required) { return Err(EnqueuePackageForDownloadError::AlreadyFailed); } - { - let is_required = this.lockfile.buffers.dependencies[dependency_id as usize] - .behavior - .is_required(); - if offline_tarball_miss(this, task_id, name, is_required) { - return Err(EnqueuePackageForDownloadError::Offline); - } + if offline_tarball_miss(this, task_id, name, is_required) { + return Err(EnqueuePackageForDownloadError::Offline); } let task_queue = this.task_queue.get_or_put(task_id)?; if !task_queue.found_existing { @@ -485,9 +499,6 @@ pub fn enqueue_package_for_download( return Ok(()); } - let is_required = this.lockfile.buffers.dependencies[dependency_id as usize] - .behavior - .is_required(); let package = *this.lockfile.packages.get(package_id as usize); if let Some(task) = run_tasks::generate_network_task_for_tarball( @@ -3201,6 +3212,7 @@ impl PackageManager { url: &[u8], task_context: TaskCallbackContext, patch_name_and_version_hash: Option, + is_required: bool, ) -> Result<(), EnqueueTarballForDownloadError> { enqueue_tarball_for_download( self, @@ -3209,6 +3221,7 @@ impl PackageManager { url, task_context, patch_name_and_version_hash, + is_required, ) } @@ -3239,6 +3252,7 @@ impl PackageManager { resolution: &Resolution, task_context: TaskCallbackContext, patch_name_and_version_hash: Option, + is_required: bool, ) -> GitEnqueueResult { enqueue_git_for_checkout( self, @@ -3247,6 +3261,7 @@ impl PackageManager { resolution, task_context, patch_name_and_version_hash, + is_required, ) } @@ -3260,6 +3275,7 @@ impl PackageManager { url: &[u8], task_context: TaskCallbackContext, patch_name_and_version_hash: Option, + is_required: bool, ) -> Result<(), EnqueuePackageForDownloadError> { enqueue_package_for_download( self, @@ -3270,6 +3286,7 @@ impl PackageManager { url, task_context, patch_name_and_version_hash, + is_required, ) } } diff --git a/src/install/PackageManager/runTasks.rs b/src/install/PackageManager/runTasks.rs index 3feca04e87af..7e2a897039df 100644 --- a/src/install/PackageManager/runTasks.rs +++ b/src/install/PackageManager/runTasks.rs @@ -1892,11 +1892,9 @@ pub fn has_created_network_task( .expect("unreachable"); // if there's an existing network task that is optional, we want to make it non-optional if this one would be required - gpe.value_ptr.is_required = if !gpe.found_existing { - is_required - } else { - gpe.value_ptr.is_required || is_required - }; + if !gpe.value_ptr.failed { + gpe.value_ptr.is_required |= is_required; + } gpe.found_existing } diff --git a/src/install/auto_installer.rs b/src/install/auto_installer.rs index 774a05069b6f..30539acb4697 100644 --- a/src/install/auto_installer.rs +++ b/src/install/auto_installer.rs @@ -352,6 +352,9 @@ impl hooks::AutoInstaller for PackageManager { // preserves the tag/union pairing. let npm = *r.npm(); let url = self.lockfile.str(&npm.url).to_vec(); + let is_required = self.lockfile.buffers.dependencies[dependency_id as usize] + .behavior + .is_required(); enqueue::enqueue_package_for_download( self, name, @@ -361,6 +364,7 @@ impl hooks::AutoInstaller for PackageManager { &url, crate::TaskCallbackContext::RootRequestId(ctx.root_request_id), patch_name_and_version_hash, + is_required, ) .map_err(|e| crate::Error::from(e).into()) } diff --git a/src/install/hoisted_install.rs b/src/install/hoisted_install.rs index d58a3032f247..45bc4f7c2c06 100644 --- a/src/install/hoisted_install.rs +++ b/src/install/hoisted_install.rs @@ -384,6 +384,11 @@ pub(crate) fn install_hoisted_packages( summary: &mut summary, force_install, successfully_installed: Bitset::init_empty(pkg_len)?, + required_packages: tree::RequiredPackages::new( + workspace_filters, + install_root_dependencies, + packages_to_install, + ), command_ctx: ctx, tree_ids_to_trees_the_id_depends_on, completed_trees, diff --git a/src/install/isolated_install.rs b/src/install/isolated_install.rs index 756bfd98712f..4c0dc802a4d8 100644 --- a/src/install/isolated_install.rs +++ b/src/install/isolated_install.rs @@ -43,7 +43,7 @@ use bun_wyhash::{Wyhash, Wyhash11}; use crate::analytics; use crate::bun_bunfig::Arguments as Command; use crate::bun_progress::{Node as ProgressNode, Progress}; -use crate::lockfile::tree::is_filtered_dependency_or_workspace; +use crate::lockfile::tree::{RequiredPackages, is_filtered_dependency_or_workspace}; use crate::lockfile::{self, Lockfile}; use crate::package_manager::{self, PackageManager, WorkspaceFilter, run_tasks}; use crate::package_manager_real::ProgressStrings; @@ -2101,6 +2101,12 @@ pub(crate) fn install_isolated_packages( ); } + let mut required_packages = RequiredPackages::new( + workspace_filters, + install_root_dependencies, + packages_to_install, + ); + // add the pending task count upfront installer .manager_mut() @@ -2410,6 +2416,8 @@ pub(crate) fn install_isolated_packages( let ctx = install::TaskCallbackContext::IsolatedPackageInstallContext(entry_id); let dep = &lockfile_ro.buffers.dependencies[dep_id as usize]; + let is_required = + required_packages.contains(installer.manager(), dep_id, pkg_id); match pkg_res_tag { ResolutionTag::Npm => { @@ -2421,6 +2429,7 @@ pub(crate) fn install_isolated_packages( pkg_res.npm().url.slice(string_buf), ctx, patch_info.name_and_version_hash(), + is_required, ) { Ok(()) => {} Err(e) if e == crate::Error::Alloc(bun_alloc::AllocError) => { @@ -2469,6 +2478,7 @@ pub(crate) fn install_isolated_packages( &pkg_res, ctx, patch_info.name_and_version_hash(), + is_required, ) == crate::package_manager::GitEnqueueResult::OfflineMiss { // --offline and not cached: nothing was queued @@ -2491,6 +2501,7 @@ pub(crate) fn install_isolated_packages( &url, ctx, patch_info.name_and_version_hash(), + is_required, ) { Ok(()) => {} Err(e) if e == crate::Error::Alloc(bun_alloc::AllocError) => { @@ -2547,6 +2558,7 @@ pub(crate) fn install_isolated_packages( pkg_res.remote_tarball().slice(string_buf), ctx, patch_info.name_and_version_hash(), + is_required, ) { Ok(()) => {} Err(e) if e == crate::Error::Alloc(bun_alloc::AllocError) => { diff --git a/src/install/lockfile/Tree.rs b/src/install/lockfile/Tree.rs index 3d99cadfed3f..177bcedb8727 100644 --- a/src/install/lockfile/Tree.rs +++ b/src/install/lockfile/Tree.rs @@ -615,6 +615,113 @@ pub(crate) fn is_filtered_dependency_or_workspace( !WorkspaceFilter::is_selected(workspace_filters, pkg_id) } +/// The packages that a linked dependency without `Behavior::OPTIONAL` resolves to. +pub(crate) struct RequiredPackages<'a> { + workspace_filters: &'a [WorkspaceFilter], + install_root_dependencies: bool, + packages_to_install: Option<&'a [PackageID]>, + /// Walked on the first question that the asking dependency cannot answer. + packages: Option, +} + +impl<'a> RequiredPackages<'a> { + pub(crate) fn new( + workspace_filters: &'a [WorkspaceFilter], + install_root_dependencies: bool, + packages_to_install: Option<&'a [PackageID]>, + ) -> Self { + Self { + workspace_filters, + install_root_dependencies, + packages_to_install, + packages: None, + } + } + + /// `dependency_id` is the linked dependency that asks for `package_id`. + pub(crate) fn contains( + &mut self, + manager: &PackageManager, + dependency_id: DependencyID, + package_id: PackageID, + ) -> bool { + let lockfile: &Lockfile = &manager.lockfile; + if !lockfile.buffers.dependencies[dependency_id as usize] + .behavior + .contains(crate::dependency::Behavior::OPTIONAL) + { + return true; + } + // Walk again if the install appended a package since. + let packages = match &mut self.packages { + Some(packages) if packages.bit_length() == lockfile.packages.len() => packages, + stale => stale.insert(bun_core::handle_oom(required_packages( + lockfile, + manager, + self.workspace_filters, + self.install_root_dependencies, + self.packages_to_install, + ))), + }; + packages.is_set(package_id as usize) + } +} + +fn required_packages( + lockfile: &Lockfile, + manager: &PackageManager, + workspace_filters: &[WorkspaceFilter], + install_root_dependencies: bool, + packages_to_install: Option<&[PackageID]>, +) -> Result { + let dependencies = lockfile.buffers.dependencies.as_slice(); + let resolutions = lockfile.buffers.resolutions.as_slice(); + let pkgs = lockfile.packages.slice(); + let pkg_dependencies = pkgs.items_dependencies(); + let pkg_metas = pkgs.items_meta(); + + let mut required = DynamicBitSet::init_empty(pkg_dependencies.len())?; + let mut seen = DynamicBitSet::init_empty(pkg_dependencies.len())?; + let mut queue: Vec = vec![0]; + seen.set(0); + + while let Some(parent_pkg_id) = queue.pop() { + let slice = pkg_dependencies[parent_pkg_id as usize]; + for dep_id in slice.begin()..slice.end() { + let pkg_id = resolutions[dep_id as usize]; + let behavior = dependencies[dep_id as usize].behavior; + if pkg_id as usize >= pkg_dependencies.len() + // The linkers can bind a peer to another package than the one it resolves to. + || behavior.is_peer() + // `is_filtered_dependency_or_workspace` would print this package under `--verbose`. + || pkg_metas[pkg_id as usize].is_disabled(manager.options.cpu, manager.options.os) + || is_filtered_dependency_or_workspace( + dep_id, + parent_pkg_id, + workspace_filters, + install_root_dependencies, + manager, + lockfile, + resolutions, + ) + || (parent_pkg_id == 0 + && packages_to_install.is_some_and(|packages| !packages.contains(&pkg_id))) + { + continue; + } + if !behavior.contains(crate::dependency::Behavior::OPTIONAL) { + required.set(pkg_id as usize); + } + if !seen.is_set(pkg_id as usize) { + seen.set(pkg_id as usize); + queue.push(pkg_id); + } + } + } + + Ok(required) +} + // ────────────────────────────────────────────────────────────────────────── // process_subtree / hoist_dependency // ────────────────────────────────────────────────────────────────────────── diff --git a/test/cli/install/bun-install-retry.test.ts b/test/cli/install/bun-install-retry.test.ts index d9706157a9be..f598b203410e 100644 --- a/test/cli/install/bun-install-retry.test.ts +++ b/test/cli/install/bun-install-retry.test.ts @@ -1,9 +1,21 @@ import { file, spawn } from "bun"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, setDefaultTimeout } from "bun:test"; -import { access, writeFile } from "fs/promises"; -import { bunExe, bunEnv as env, readdirSorted, tmpdirSync, toBeValidBin, toBeWorkspaceLink, toHaveBins } from "harness"; +import { access, mkdir, readdir, rm, writeFile } from "fs/promises"; +import { + bunExe, + bunEnv as env, + readdirSorted, + tempDir, + tmpdirSync, + toBeValidBin, + toBeWorkspaceLink, + toHaveBins, +} from "harness"; import { join } from "path"; +import { pathToFileURL } from "url"; import { + createTestContext, + destroyTestContext, dummyAfterAll, dummyAfterEach, dummyBeforeAll, @@ -12,6 +24,7 @@ import { package_dir, requested, root_url, + setContextHandler, setHandler, } from "./dummy.registry"; @@ -438,4 +451,365 @@ describe.each(["hoisted", "isolated"])("linker=%s", linker => { expect(exitCode).toBe(0); } }); + + // One download serves every dependency on a package. When one of them is + // required, its failure must fail the install, whichever of them asked first. + describe.concurrent("a failed download that an optional and a required dependency share", () => { + const packageTarball = (name: string, pkg: object) => + new Bun.Archive( + { "package/package.json": JSON.stringify({ name, version: "1.0.0", ...pkg }) }, + { compress: "gzip" }, + ).bytes(); + + // A project with a registry prefix of its own, so these tests run together. The + // registry has baz@0.0.3, whose tarball can fail, baz@0.0.5, and `packages` at 1.0.0. + async function project(packages: Record = {}) { + const ctx = await createTestContext({ linker: linker as "hoisted" | "isolated" }); + const dir = ctx.package_dir; + const registry = ctx.registry_url.slice(0, -1); + const tarball = `${registry}/baz-0.0.3.tgz`; + /** How many of the next requests for `tarball` get a 404. */ + let failures = 0; + let tarballGets = 0; + const tarballFailed = Promise.withResolvers(); + const routes = new Map Response | Promise>(); + for (const [name, pkg] of Object.entries(packages)) { + const packed = await packageTarball(name, pkg); + routes.set(`/${name}-1.0.0.tgz`, () => new Response(packed)); + } + const manifest = (name: string, versions: Record) => + Response.json({ + name, + "dist-tags": { latest: Object.keys(versions)[0] }, + versions: Object.fromEntries( + Object.entries(versions).map(([version, pkg]) => [ + version, + { name, version, ...pkg, dist: { tarball: `${registry}/${name}-${version}.tgz` } }, + ]), + ), + }); + setContextHandler(ctx, request => { + const pathname = new URL(request.url).pathname.slice(`/${ctx.id}`.length); + const name = pathname.slice(1); + if (name === "baz") return manifest("baz", { "0.0.3": {}, "0.0.5": {} }); + if (name in packages) return manifest(name, { "1.0.0": packages[name] }); + if (name === "baz-0.0.5.tgz") return new Response(file(join(import.meta.dir, name))); + if (name !== "baz-0.0.3.tgz") return routes.get(pathname)?.() ?? new Response("unexpected", { status: 404 }); + tarballGets++; + if (failures === 0) return new Response(file(join(import.meta.dir, name))); + failures--; + queueMicrotask(tarballFailed.resolve); + return new Response("no", { status: 404 }); + }); + await writeFile( + join(dir, "bunfig.toml"), + Bun.TOML.stringify({ install: { cache: false, registry: ctx.registry_url, linker } }), + ); + + // The isolated linker names the package by its resolution: a version, or the tarball URL. + const errorLine = (resolution: string) => + linker === "hoisted" + ? `error: GET ${tarball} - 404` + : `error: failed to download baz@${resolution}: 404 Not Found`; + return { + dir, + registry, + tarball, + routes, + tarballFailed: tarballFailed.promise, + [Symbol.dispose]: () => destroyTestContext(ctx), + + async install(pkg: object, ...args: string[]) { + await writeFile(join(dir, "package.json"), JSON.stringify({ name: "foo", version: "0.0.1", ...pkg })); + await using proc = spawn({ + cmd: [bunExe(), "install", "--no-progress", "--ignore-scripts", ...args], + cwd: dir, + stdout: "ignore", + stderr: "pipe", + env, + }); + const [err, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + const lines = err.split(/\r?\n/); + return { + warnLines: lines.filter(l => l.startsWith("warn:")), + errorLines: lines.filter(l => l.startsWith("error:")), + tarballGets, + exitCode, + }; + }, + // `cache: false` keeps the cache in node_modules/.cache, so this also empties the cache. + async failTarballOnColdCache(times = Infinity) { + await rm(join(dir, "node_modules"), { recursive: true, force: true }); + failures = times; + tarballGets = 0; + }, + failTarball() { + failures = Infinity; + }, + + installed: { warnLines: [], errorLines: [], tarballGets: 1, exitCode: 0 }, + // The download failed for optional dependencies only. + warned: { warnLines: [`warn: GET ${tarball} - 404`], errorLines: [], tarballGets: 1, exitCode: 0 }, + // The download failed once, for the required dependency. + failed: (resolution = tarball) => ({ + warnLines: [], + errorLines: [errorLine(resolution)], + tarballGets: 1, + exitCode: 1, + }), + // The download failed for an optional dependency first (a warning), then again for the required one. + failedAgain: (resolution = tarball) => ({ + warnLines: [`warn: GET ${tarball} - 404`], + errorLines: [errorLine(resolution)], + tarballGets: 2, + exitCode: 1, + }), + }; + } + + // The lockfile resolves `a`, so only the new `b` asks for the tarball while + // resolving: a warning. The installer then asks for it again for `a`. + it("reports the required one after the optional one's download failed", async () => { + using t = await project(); + expect(await t.install({ dependencies: { a: t.tarball } })).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect(await t.install({ dependencies: { a: t.tarball }, optionalDependencies: { b: t.tarball } })).toEqual( + t.failedAgain(), + ); + }); + + // The failure that `b` got is not `a`'s: `a` downloads again, and this time it works. + it("installs the required one when its own download succeeds", async () => { + using t = await project(); + expect(await t.install({ dependencies: { a: t.tarball } })).toEqual(t.installed); + await t.failTarballOnColdCache(1); + expect(await t.install({ dependencies: { a: t.tarball }, optionalDependencies: { b: t.tarball } })).toEqual({ + warnLines: [`warn: GET ${t.tarball} - 404`], + errorLines: [], + tarballGets: 2, + exitCode: 0, + }); + expect(await file(join(t.dir, "node_modules", "a", "package.json")).json()).toMatchObject({ name: "baz" }); + }); + + // The lockfile resolves both. optionalDependencies sort first, so the installer + // starts the download for `b` and `a` joins it. + it("reports the required one when it joins the optional one's download", async () => { + using t = await project(); + const pkg = { dependencies: { a: t.tarball }, optionalDependencies: { b: t.tarball } }; + expect(await t.install(pkg)).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect(await t.install(pkg)).toEqual(t.failed()); + }); + + // No lockfile. Both aliases resolve to baz@0.0.3, and `b` resolves it first, so + // the download that fails while resolving is a warning. + it("reports the required alias of an npm package after the optional alias's download failed", async () => { + using t = await project(); + t.failTarball(); + expect( + await t.install({ dependencies: { a: "npm:baz@0.0.3" }, optionalDependencies: { b: "npm:baz@0.0.3" } }), + ).toEqual(t.failedAgain("0.0.3")); + }); + + // `d` arrives after the tarball's 404, so its optional dependency `c` asks for + // the tarball once it has failed: that callback stays queued and nothing runs + // it. The download for `a` must start again, not wait behind it. + it("reports the required one when a callback is still queued for the failed download", async () => { + using t = await project(); + const d = await packageTarball("d", { optionalDependencies: { c: t.tarball } }); + t.routes.set("/d.tgz", async () => { + await t.tarballFailed; + return new Response(d); + }); + + expect(await t.install({ dependencies: { a: t.tarball } })).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect( + await t.install({ + dependencies: { a: t.tarball, d: `${t.registry}/d.tgz` }, + optionalDependencies: { b: t.tarball }, + }), + ).toEqual(t.failedAgain()); + }); + + // Peers resolve after everything else, so `p` asks for the tarball once it has + // failed for `b`. That failure stays the warning it was reported as. + it("reports the required one when a peer asked for the failed download in between", async () => { + using t = await project(); + expect(await t.install({ dependencies: { a: t.tarball } })).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect( + await t.install({ + dependencies: { a: t.tarball }, + optionalDependencies: { b: t.tarball }, + peerDependencies: { p: t.tarball }, + }), + ).toEqual(t.failedAgain()); + }); + + // node_modules has one baz for both dependencies on it, and the linker asks for + // it through the first one: the root's optional dependency. + describe("when the optional dependency is the one the linker asks through", () => { + const pkg = { dependencies: { bar: "1.0.0" }, optionalDependencies: { baz: "0.0.3" } }; + const bar = { bar: { dependencies: { baz: "0.0.3" } } }; + + it("reports the required one on a fresh install", async () => { + using t = await project(bar); + t.failTarball(); + expect(await t.install(pkg)).toEqual(t.failedAgain("0.0.3")); + }); + + it("reports the required one from the lockfile on a cold cache", async () => { + using t = await project(bar); + expect(await t.install(pkg)).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect(await t.install(pkg)).toEqual(t.failed("0.0.3")); + }); + + // The same question decides whether a package that --offline cannot find is an error. + // Removes the entries that `isGone` names from node_modules, its store and the cache in it. + async function forget(dir: string, isGone: (entry: string) => boolean) { + for (const store of [".", ".bun", ".cache"]) { + for (const entry of await readdir(join(dir, "node_modules", store)).catch(() => [])) { + if (isGone(entry)) await rm(join(dir, "node_modules", store, entry), { recursive: true, force: true }); + } + } + } + + it("reports the required one that --offline does not find in the cache", async () => { + using t = await project(bar); + expect(await t.install(pkg)).toEqual(t.installed); + // bar stays installed and cached. + await forget(t.dir, entry => entry.startsWith("baz")); + expect(await t.install(pkg, "--offline")).toEqual({ + warnLines: [], + errorLines: ['error: --offline: "baz" is not in the cache'], + // still the request of the first install + tarballGets: 1, + exitCode: 1, + }); + }); + + it.skipIf(!Bun.which("git"))( + "reports the required git dependency that --offline does not find in the cache", + async () => { + using repo = tempDir("shared-download-git", { + "work/package.json": JSON.stringify({ name: "gitpkg", version: "1.0.0" }), + }); + const bare = join(String(repo), "repo.git"); + for (const args of [ + ["init", "-q"], + ["add", "-A"], + ["commit", "-q", "-m", "init", "--no-gpg-sign"], + ["clone", "-q", "--bare", ".", bare], + ]) { + await using git = spawn({ + cmd: ["git", ...args], + cwd: join(String(repo), "work"), + env: { + ...env, + GIT_CONFIG_NOSYSTEM: "1", + GIT_AUTHOR_NAME: "Test", + GIT_AUTHOR_EMAIL: "test@example.com", + GIT_COMMITTER_NAME: "Test", + GIT_COMMITTER_EMAIL: "test@example.com", + }, + stdout: "ignore", + stderr: "pipe", + }); + expect({ stderr: await git.stderr.text(), exitCode: await git.exited }).toEqual({ + stderr: "", + exitCode: 0, + }); + } + const gitpkg = `git+${pathToFileURL(bare)}`; + + using t = await project({ bar: { dependencies: { gitpkg } } }); + const pkg = { dependencies: { bar: "1.0.0" }, optionalDependencies: { gitpkg } }; + expect(await t.install(pkg)).toEqual({ ...t.installed, tarballGets: 0 }); + // bar stays installed and cached. The clone and the checkout leave the cache. + await forget(t.dir, entry => entry.startsWith("gitpkg") || entry.endsWith(".git") || entry.startsWith("@G@")); + expect(await t.install(pkg, "--offline")).toEqual({ + warnLines: [], + errorLines: ['error: --offline: git repository for "gitpkg" is not in the cache'], + tarballGets: 0, + exitCode: 1, + }); + }, + ); + + // `x` comes first, so its dependency on baz is the one the linker asks through. + it.each(["optionalDependencies", "dependencies"])( + "reports the required one when the first of two parents has baz in %s", + async first => { + const second = first === "dependencies" ? "optionalDependencies" : "dependencies"; + using t = await project({ x: { [first]: { baz: "0.0.3" } }, y: { [second]: { baz: "0.0.3" } } }); + const parents = { dependencies: { x: "1.0.0", y: "1.0.0" } }; + expect(await t.install(parents)).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect(await t.install(parents)).toEqual(t.failed("0.0.3")); + }, + ); + }); + + // Nothing that this install links requires baz@0.0.3, so its failed download stays + // a warning and the install succeeds. Hoisted only: the isolated linker fails the + // install for every package that it cannot download. + describe.skipIf(linker === "isolated")("stays a warning", () => { + it("when only a devDependency requires the package and --production skips it", async () => { + using t = await project({ bar: { dependencies: { baz: "0.0.3" } } }); + const pkg = { devDependencies: { bar: "1.0.0" }, optionalDependencies: { baz: "0.0.3" } }; + expect(await t.install(pkg)).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect(await t.install(pkg, "--production")).toEqual(t.warned); + }); + + it("when only a workspace that --filter skips requires the package", async () => { + using t = await project(); + for (const [name, pkg] of Object.entries({ + opt: { optionalDependencies: { baz: "0.0.3" } }, + req: { dependencies: { baz: "0.0.3" } }, + })) { + await mkdir(join(t.dir, "packages", name), { recursive: true }); + await writeFile(join(t.dir, "packages", name, "package.json"), JSON.stringify({ name, ...pkg })); + } + expect(await t.install({ workspaces: ["packages/*"] })).toEqual(t.installed); + await t.failTarballOnColdCache(); + expect(await t.install({ workspaces: ["packages/*"] }, "--filter", "opt")).toEqual(t.warned); + }); + + describe.each(["a fresh install", "the lockfile on a cold cache"])("with %s", flow => { + async function install(t: Awaited>, pkg: object) { + if (flow === "a fresh install") { + t.failTarball(); + } else { + expect(await t.install(pkg)).toEqual(t.installed); + await t.failTarballOnColdCache(); + } + return await t.install(pkg); + } + + // `x` comes first, so its optional peer is the dependency the linker asks through. + it("when an optional peer and an optional dependency share the package", async () => { + using t = await project({ + x: { peerDependencies: { baz: "*" }, peerDependenciesMeta: { baz: { optional: true } } }, + y: { optionalDependencies: { baz: "0.0.3" } }, + }); + expect(await install(t, { dependencies: { x: "1.0.0", y: "1.0.0" } })).toEqual(t.warned); + }); + + // x's peer resolves to baz@0.0.3, but the tree gives x the root's baz@0.0.5. + // Only y's optional dependency links baz@0.0.3. + it("when a peer resolves to the package and the linker binds it to another one", async () => { + using t = await project({ + x: { peerDependencies: { baz: "^0.0.3" } }, + y: { optionalDependencies: { baz: "0.0.3" } }, + }); + const pkg = { dependencies: { x: "1.0.0", y: "1.0.0" }, optionalDependencies: { baz: "0.0.5" } }; + expect(await install(t, pkg)).toEqual(t.warned); + }); + }); + }); + }); });