Skip to content
Closed
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
7 changes: 7 additions & 0 deletions src/install/PackageManager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,11 @@ pub struct PackageManager {
/// could be any of the workspaces.
pub root_package_id: RootPackageId,

/// Name hash of the workspace root's package.json, set the first time it
/// is parsed. Used to resolve `workspace:` dependencies that name the
/// root package (the root is never in `workspace_paths`).
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) workspace_root_name_hash: PackageNameHash,

pub(crate) thread_pool: ThreadPool,
pub(crate) task_batch: thread_pool::Batch,
pub(crate) task_queue: TaskDependencyQueue,
Expand Down Expand Up @@ -1909,6 +1914,7 @@ pub fn init(
wr!(to_update, false);
wr!(update_requests, Box::default());
wr!(root_package_id, RootPackageId::default());
wr!(workspace_root_name_hash, 0);
wr!(task_batch, thread_pool::Batch::default());
wr!(task_queue, TaskDependencyQueue::default());
wr!(manifests, PackageManifestMap::default());
Expand Down Expand Up @@ -2341,6 +2347,7 @@ fn init_with_runtime_once(
wr!(update_requests, Box::default());
wr!(root_package_json_name_at_time_of_init, Box::default());
wr!(root_package_id, RootPackageId::default());
wr!(workspace_root_name_hash, 0);
wr!(task_batch, thread_pool::Batch::default());
wr!(task_queue, TaskDependencyQueue::default());
wr!(manifests, PackageManifestMap::default());
Expand Down
26 changes: 24 additions & 2 deletions src/install/PackageManager/PackageManagerEnqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2632,12 +2632,34 @@ fn get_or_put_resolved_package(
dependency::version::Tag::Workspace => {
// package name hash should be used to find workspace path from map
// SAFETY: `version.tag == Workspace` discriminates the union arm.
let workspace_path_raw: SemverString = this
let workspace_path_raw: SemverString = match this
.lockfile
.workspace_paths
.get(&name_hash)
.copied()
.unwrap_or_else(|| *version.workspace());
{
Some(p) => p,
None => {
// A workspace member may depend on the workspace root
// package by name via `workspace:`. The root is package id
// 0 and is never registered in `workspace_paths` (only
// members are), so match it here when no member has this
// name.
Comment thread
robobun marked this conversation as resolved.
Resolved
if name_hash != 0 {
if let Some(root) = this.lockfile.root_package() {
if root.name_hash == name_hash {
success_fn(this, dependency_id, 0);
return Ok(Some(ResolvedPackageResult {
package: *this.lockfile.packages.get(0),
is_first_time: false,
task: None,
}));
}
}
}
*version.workspace()
}
};
// reshaped for borrowck — `workspace_path` may borrow
// `string_bytes`; detach the slice lifetime so the
// `&mut PackageManager` reborrow for `get_or_put` below does not
Expand Down
22 changes: 22 additions & 0 deletions src/install/lockfile/Package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1621,6 +1621,7 @@ impl Package<u64> {
dependencies_count: u32,
tag: Option<dependency::version::Tag>,
workspace_ver: Option<SemverVersion>,
root_name_hash: PackageNameHash,
external_alias: ExternalString,
version: &[u8],
key_loc: bun_ast::Loc,
Expand Down Expand Up @@ -1792,6 +1793,19 @@ impl Package<u64> {
}
}
dependency::version::Tag::Workspace => 'workspace: {
if workspace_path.is_none()
&& tag.is_none()
&& root_name_hash != 0
&& name_hash == root_name_hash
{
// A `workspace:` dep on the workspace root package. The
// root is not in `workspace_paths` (only members are), and
// the literal after `workspace:` is a version spec, not a
// path. Leave the dependency as-is;
// `get_or_put_resolved_package` resolves it to package
// id 0.
Comment thread
robobun marked this conversation as resolved.
Resolved
break 'workspace;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if let Some(path) = workspace_path {
if let Some(range) = &workspace_range {
if let Some(ver) = workspace_version {
Expand Down Expand Up @@ -2593,6 +2607,11 @@ impl Package<u64> {

total_dependencies_count = 0;

if FEATURES.is_main {
pm.workspace_root_name_hash = self.name_hash;
}
let root_name_hash = pm.workspace_root_name_hash;

for group in &dependency_groups {
if group.behavior.is_workspace() {
let mut seen_workspace_names: ArrayHashMap<
Expand Down Expand Up @@ -2739,6 +2758,7 @@ impl Package<u64> {
total_dependencies_count,
Some(dependency::version::Tag::Workspace),
workspace_version,
root_name_hash,
external_name,
path_,
bun_ast::Loc::EMPTY,
Expand Down Expand Up @@ -2786,6 +2806,7 @@ impl Package<u64> {
total_dependencies_count,
None,
None,
root_name_hash,
external_name,
version,
key_loc,
Expand Down Expand Up @@ -2836,6 +2857,7 @@ impl Package<u64> {
total_dependencies_count,
None,
None,
root_name_hash,
external_name,
b"*",
bun_ast::Loc::EMPTY,
Expand Down
11 changes: 11 additions & 0 deletions src/install/lockfile/bun.lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2118,6 +2118,10 @@ pub(crate) fn parse_into_binary_lockfile(
root_pkg.resolutions = PackageIDSlice::new(off, len);

root_pkg.meta.id = 0;
// Set the root resolution before the packages loop so a
// `<name>@root:` entry dedupes against package id 0 in
// `append_package_dedupe` instead of appending a second Root package.
Comment thread
robobun marked this conversation as resolved.
Resolved
root_pkg.resolution = Resolution::init(crate::resolution::TaggedValue::Root);
Comment thread
robobun marked this conversation as resolved.
Resolved
let root_name_hash = root_pkg.name_hash;
lockfile.packages.append(root_pkg)?;
lockfile.get_or_put_id(0, root_name_hash)?;
Expand Down Expand Up @@ -2743,6 +2747,13 @@ pub(crate) fn parse_into_binary_lockfile(

let pkg_id = lockfile.append_package_dedupe(&mut pkg)?;

if pkg_id == 0 && res.tag == ResolutionTag::Root {
// `<name>@root:` deduped to package id 0; carry over the bin
// parsed from this entry since the root package was created
// with a default bin above.
Comment thread
robobun marked this conversation as resolved.
Resolved
lockfile.packages.items_bin_mut()[0] = pkg.bin;
}

let entry = pkg_map.get_or_put(pkg_path)?;
if entry.found_existing {
log.add_error(Some(source), key_loc, b"Duplicate package path");
Expand Down
73 changes: 73 additions & 0 deletions test/cli/install/bun-workspaces.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1211,6 +1211,79 @@ test.concurrent("it should detect duplicate workspace dependencies", async () =>
expect(await exited).toBe(1);
});

// https://github.com/oven-sh/bun/issues/2773
for (const spec of ["workspace:*", "workspace:0.0.1", "workspace:^"]) {
for (const linker of ["hoisted", "isolated"] as const) {
test.concurrent(`workspace member can depend on root via ${spec} (${linker})`, async () => {
using ctx = await setupTest();
const { packageDir, packageJson, env } = ctx;
await Promise.all([
write(
packageJson,
JSON.stringify({
name: "Foo",
version: "0.0.1",
workspaces: ["bar"],
}),
),
write(
join(packageDir, "bar", "package.json"),
JSON.stringify({
name: "Bar",
version: "0.0.2",
devDependencies: { Foo: spec },
}),
),
write(join(packageDir, "index.js"), "module.exports = 42;\n"),
]);

let { stderr, exited } = spawn({
cmd: [bunExe(), "install", `--linker=${linker}`],
cwd: packageDir,
stdout: "ignore",
stderr: "pipe",
env,
});
let [err, exit] = await Promise.all([stderr.text(), exited]);
expect(err).not.toContain("not found");
expect(err).not.toContain("failed to resolve");
expect(err).not.toContain("error:");
expect(err).toContain("Saved lockfile");
expect(exit).toBe(0);

// bun.lock records the root package and does not add a bogus workspace path
const lock = await file(join(packageDir, "bun.lock")).text();
expect(lock).toContain('"Foo": ["Foo@root:"');
expect(lock).not.toContain("bar/0.0.1");

// the member can require the root package
await using proc = spawn({
cmd: [bunExe(), "-e", 'console.log(require("Foo"))'],
cwd: join(packageDir, "bar"),
stdout: "pipe",
stderr: "pipe",
env,
});
const [rout, rerr, rexit] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(rerr).toBe("");
expect(rout).toBe("42\n");
expect(rexit).toBe(0);

// second install is stable
({ stderr, exited } = spawn({
cmd: [bunExe(), "install", "--frozen-lockfile", `--linker=${linker}`],
cwd: packageDir,
stdout: "ignore",
stderr: "pipe",
env,
}));
[err, exit] = await Promise.all([stderr.text(), exited]);
expect(err).not.toContain("error:");
expect(exit).toBe(0);
});
}
}

const versions = ["workspace:1.0.0", "workspace:*", "workspace:^1.0.0", "1.0.0", "*"];

for (const rootVersion of versions) {
Expand Down
Loading