Repository navigation
fix: scanner on update, install, remove, uninstall and add, and introduce the pm scan command - #22193
Conversation
|
Updated 9:40 PM PT - Sep 9th, 2025
❌ @dylan-conway, your commit b30c1ed has 1 failures in
🧪 To try this PR locally: bunx bun-pr 22193That installs a local version of the PR into your bun-22193 --bun |
WalkthroughAdds a security-scanning feature: new "bun pm scan" CLI command, JS scanner entrypoint with IPC protocol, Zig scanner orchestration and integration into install/update flows, partial-install and lockfile filtering support, build inputs and typings updates, TTY helpers, and extensive tests and test utilities. Changes
Possibly related PRs
Suggested reviewers
Pre-merge checks (1 passed, 2 warnings)❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).Please share your feedback with us on this Discord post. ✨ Finishing Touches🧪 Generate unit tests
Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 22
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
packages/bun-types/shell.d.ts (1)
61-61: Broaden $.env() to match ShellPromise.env()Mirror the widened type here so both entry points accept process.env without casts.
See diff in previous comment.
src/install/PackageManager/install_with_manager.zig (1)
725-751: Free workspace_filters after use (paired with getWorkspaceFilters fix).Ensure the owned slice returned by getWorkspaceFilters is freed in this scope to avoid leaking the array buffer.
- const workspace_filters, const install_root_dependencies = (try getWorkspaceFilters(manager, original_cwd)); + const workspace_filters, const install_root_dependencies = try getWorkspaceFilters(manager, original_cwd); + defer manager.allocator.free(workspace_filters);src/install/PackageInstaller.zig (2)
700-703: Function lacks a return; guaranteed compile error.getPatchfileHash returns ?u64 but never returns a value.
fn getPatchfileHash(patchfile_path: []const u8) ?u64 { - _ = patchfile_path; // autofix + _ = patchfile_path; // TODO: implement real hash + return null; }
978-987: Update all enqueuePackageForDownload call sites and switch to an Options struct
- src/resolver/resolver.zig (around line 2030) and src/install/isolated_install.zig (around line 862) still invoke enqueuePackageForDownload with only the original three arguments—add the new version, URL, context, patch_name_and_version_hash, and force_install_skip_prefetch_check parameters.
- Refactor enqueuePackageForDownload’s signature to accept a single Options struct instead of trailing booleans to prevent positional errors on future extensions.
♻️ Duplicate comments (1)
src/cli/package_manager_command.zig (1)
96-101: Clarify distinction between “scan” and “audit” in helpPast feedback noted confusion vs bun audit. Consider making the description explicitly “scan (via configured external scanner)” to differentiate from “bun audit (npm advisories)”.
Suggested tweak:
-\\ <b><green>bun pm<r> <blue>scan<r> scan all packages in lockfile for security vulnerabilities +\\ <b><green>bun pm<r> <blue>scan<r> security scan via configured external scanner (not the same as `bun audit`)
🧹 Nitpick comments (30)
cmake/targets/BuildBun.cmake (1)
639-639: Avoid duplicating scanner-entry.ts as a direct bun-zig source; rely on JavaScriptSources and codegen insteadscanner-entry.ts is already included via JavaScriptSources.txt and gets funneled into ${BUN_JAVASCRIPT_OUTPUTS} consumed by bun-zig. Listing the raw TS file here duplicates inputs and can cause confusing rebuild triggers.
Apply this diff to remove the redundancy and, if needed, make bun-zig explicitly depend on bun-js-modules for ordering:
SOURCES ${BUN_ZIG_SOURCES} ${BUN_ZIG_GENERATED_SOURCES} - ${CWD}/src/install/PackageManager/scanner-entry.ts # Is there a better way to do this? )Optionally add bun-js-modules to TARGETS to tighten dependencies (only if you observe ordering issues):
TARGETS clone-zig clone-zstd bun-cppbind + bun-js-modulescmake/Sources.json (1)
16-19: Consistent manifesting of scanner-entry.tsSwitching paths to an array and adding scanner-entry.ts is correct. Ensure BuildBun.cmake does not also list the raw TS as a bun-zig source to prevent duplicated dependencies.
src/install/PackageManager.zig (1)
583-586: Use copyForwards to avoid aliasing instead of pointer comparisonPointer inequality doesn’t fully protect against overlapping slices; std.mem.copyForwards is clearer and alias-safe.
Apply this diff:
- // Avoid memcpy alias when source and dest are the same - if (cwd_buf[0..].ptr != top_level_dir_no_trailing_slash.ptr) { - @memcpy(cwd_buf[0..top_level_dir_no_trailing_slash.len], top_level_dir_no_trailing_slash); - } + // Safely copy even if slices alias + std.mem.copyForwards(u8, cwd_buf[0..top_level_dir_no_trailing_slash.len], top_level_dir_no_trailing_slash);src/install/PackageManager/scanner-entry-globals.d.ts (1)
1-2: Ambient globals OK; consider declare global + export {} for claritydeclare const at top-level works in a script .d.ts. To avoid accidental module-ness and make intent explicit, consider:
-declare const __PACKAGES_JSON__: Bun.Security.Package[]; -declare const __SUPPRESS_ERROR__: boolean; +declare global { + const __PACKAGES_JSON__: Bun.Security.Package[]; + const __SUPPRESS_ERROR__: boolean; +} +export {};test/cli/install/generate-scanner-tarballs.ts (2)
8-9: Use mkdtemp in OS tmpdir to prevent collisions and improve portabilityManual /tmp paths + Date.now() can collide and aren’t Windows-friendly. Prefer fs.mkdtemp(tmpdir()).
Apply this diff:
- const tmpDir = `/tmp/test-security-scanner-${behavior}-${Date.now()}`; + const { mkdtemp } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const tmpDir = await mkdtemp(join(tmpdir(), `test-security-scanner-${behavior}-`));
56-57: Avoid shell word-splitting; pass tar args as an arrayUsing Bun.$ with interpolated paths risks breakage if paths contain spaces. Use Bun.spawn with argv or ensure quoting.
Example:
- await Bun.$`tar czf ${outputPath} -C ${tmpDir} package`; + await new Promise<void>((resolve, reject) => { + const p = Bun.spawn({ cmd: ["tar", "czf", outputPath, "-C", tmpDir, "package"] }); + p.exited.then(code => (code === 0 ? resolve() : reject(new Error(`tar exited ${code}`)))); + });src/install/PackageManager/PackageManagerEnqueue.zig (1)
242-243: Parameter name is hard to parseforce_install_skip_prefetch_check is a double-negative that’s easy to misuse. Consider a future rename to force_prefetch or override_prefetch_skip for clarity.
test/cli/install/bun-update-security-simple.test.ts (1)
97-104: Same stdout-only issue in second testRead stderr and assert on combined output to avoid false negatives.
Apply this diff:
- const [out, exitCode] = await Promise.all([updateProc.stdout.text(), updateProc.exited]); - expect(out).not.toContain("Security scanner"); - expect(out).not.toContain("FATAL:"); - expect(out).not.toContain("WARN:"); + const [out, err, exitCode] = await Promise.all([ + updateProc.stdout.text(), + updateProc.stderr.text(), + updateProc.exited, + ]); + const combined = out + err; + expect(combined).not.toContain("Security scanner"); + expect(combined).not.toContain("FATAL:"); + expect(combined).not.toContain("WARN:");src/install/PackageManager/CommandLineArguments.zig (1)
705-733: Help text for scan inherits all pm_params (includes pack/version flags) — confusing UXscan likely only needs shared flags + --json. Consider a dedicated scan_params to avoid exposing unrelated options.
Example:
+const scan_params: []const ParamType = &(shared_params ++ [_]ParamType{ + clap.parseParam("--json Output in JSON format") catch unreachable, +}); … - .scan => { + .scan => { … - clap.simpleHelp(pm_params); + clap.simpleHelp(scan_params);test/cli/install/bun-update-security-provider.test.ts (2)
55-66: Also assert install succeeded to avoid false positives laterIf the initial install fails, the update assertions can become misleading. Assert the exit code for the install step.
Apply this diff:
await installProc.stdout.text(); await installProc.stderr.text(); - await installProc.exited; + const installExit = await installProc.exited; + expect(installExit).toBe(0);
116-118: Disable colors for stable stderr/stdout matching (optional)If any future assertions rely on exact strings, disabling ANSI colors reduces flakiness across CI environments.
Apply this diff:
- await write("bunfig.toml", ""); + await write("bunfig.toml", "");And in the two Bun.spawn calls in this test, pass NO_COLOR=1:
- env: bunEnv, + env: { ...bunEnv, NO_COLOR: "1" },test/cli/install/bun-pm-scan.test.ts (2)
13-28: Stabilize config guidance assertions against color/formattingThese assertions look for fragments that may be colorized. Setting NO_COLOR ensures stable matching across terminals.
Apply this diff to the spawn env:
- env: bunEnv, + env: { ...bunEnv, NO_COLOR: "1" },Repeat this for other tests that assert on stderr formatting.
623-627: Timing output assertion may be noisy across environmentsThe regex is good, but timing lines may be suppressed in some CI modes. Consider guarding with an env flag or relaxing to “Scanning” only.
Possible tweak:
- expect(stderr).toMatch(/Scanning \d+ package[s]? took \d+ms/); + expect(stderr).toMatch(/Scanning \d+ package[s]?/);src/install/PackageManager/scanner-entry.ts (1)
75-82: Optional: validate advisory shape early for clearer errorsZig code likely validates fields; adding a quick JS-side check (package, level) would surface better error messages to users and simplify tests.
If you want, I can add a minimal validator here that enforces {package, level} with level in {"fatal","warn"} before IPC.
src/cli/scan_command.zig (2)
27-29: Remove casual commentMinor polish.
Apply this diff:
- return; // sanity? lol + return;
31-33: Consider printing banner to stdout, not stderrBanners on stderr can interfere with tooling that parses stderr for errors only.
Change prettyError to pretty if we don’t need it on stderr.
test/cli/install/bun-update-security-edge-cases.test.ts (2)
276-280: Use cross-platform rename instead of shell mvShell mv isn’t portable on Windows and can flake in CI. Use fs.promises.rename.
Apply this diff:
- const tempBunfig = join(dir, "bunfig.toml"); - await Bun.$`mv ${tempBunfig} ${tempBunfig}.bak`.quiet(); + const tempBunfig = join(dir, "bunfig.toml"); + await import("node:fs/promises").then(fs => fs.rename(tempBunfig, `${tempBunfig}.bak`)); await Bun.$`${bunExe()} install`.cwd(dir).env(bunEnv).quiet(); - await Bun.$`mv ${tempBunfig}.bak ${tempBunfig}`.quiet(); + await import("node:fs/promises").then(fs => fs.rename(`${tempBunfig}.bak`, tempBunfig));
81-90: Assert we actually updated when expecting a block (optional)You gate on stdout containing “FATAL: …”. Consider additionally asserting that the package version changed in bun.lockb when the block occurs, to ensure the scan ran post-resolution.
I can add a helper to read the lockfile and confirm the target version was selected prior to abort.
src/install/hoisted_install.zig (2)
365-383: Avoid repeated BFS per dependency; add a small memoization cache.shouldInstallPackage iterates roots, then BFS per check, which scales poorly. Cache results per package_id for the duration of the install to reduce O(N·R) traversals.
Example approach (sketch):
- Thread a std.AutoHashMap(PackageID, bool) memo into shouldInstallPackage/isPackageDependencyOf.
- Fill memo on first evaluation; reuse thereafter.
I can provide a concrete patch if you prefer adding a memo struct in PackageInstaller.
Also applies to: 385-424
425-439: doInstallPackageIfInPackagesToInstall is fine; internal visibility would suffice.You can make this internal (fn) unless another module imports it.
-pub fn doInstallPackageIfInPackagesToInstall( +fn doInstallPackageIfInPackagesToInstall(src/install/isolated_install.zig (1)
835-859: Remove commented-out gating code.Dead/commented code within the hot path adds noise and risks divergence from real behavior.
Remove the entire commented should_install block.
test/cli/install/bun-update-security-scan-all.test.ts (1)
270-330: TTY prompt test is marked todo; consider running behind an integration tag.When you wire a pseudo-TTY helper, flip this from test.todo to a tagged test to avoid accidental CI flake.
test/cli/install/bun-security-scanner-matrix.test.ts (1)
205-231: Stream piping helper trims chunks; risk of losing intentional whitespace.Consider not trim() inside write() to preserve output fidelity for regex-based assertions.
- const str = decoder.decode(chunk).trim(); + const str = decoder.decode(chunk);test/cli/install/simple-dummy-registry.ts (4)
41-46: Tarball regex is too strict for pre-releases.Only matches X.Y.Z. Consider allowing prerelease/build metadata to future-proof tests.
- const match = pathname.match(/\/(.+)-(\d+\.\d+\.\d+)\.tgz$/); + const match = pathname.match(/\/(.+)-(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)\.tgz$/);
117-126: Check file existence explicitly instead of relying on size.Bun.file(...) doesn’t throw on missing files; size-based checks can mislead with zero-byte fixtures. Use exists() for clarity.
- const tarballFile = file(tarballPath); - if (!tarballFile.size) { + const tarballFile = file(tarballPath); + if (!(await tarballFile.exists())) { return new Response("Tarball not found", { status: 404 }); }
33-34: Quiet noisy logs in tests.Unconditional console.error can spam CI. Gate behind an env var or a class flag.
- console.error(`[REGISTRY] ${req.method} ${pathname}`); + if (process.env.REGISTRY_DEBUG === "1") { + console.error(`[REGISTRY] ${req.method} ${pathname}`); + }
88-91: Use Response.json for clarity.Minor readability improvement.
- return new Response(JSON.stringify(metadata), { - headers: { "Content-Type": "application/json" }, - }); + return Response.json(metadata);src/install/PackageManager/security_scanner.zig (3)
525-585: Non-deterministic JSON ordering can cause flaky tests.HashMap iteration order isn’t stable. Consider emitting packages in a name-sorted order for deterministic scanner input and snapshots.
- var iter = this.collector.package_paths.iterator(); - while (iter.next()) |entry| { + // collect keys and sort by package name + var keys = std.ArrayList(PackageID).init(this.manager.allocator); + defer keys.deinit(); + { + var it = this.collector.package_paths.iterator(); + while (it.next()) |e| try keys.append(e.key_ptr.*); + } + const pkgs = this.manager.lockfile.packages.slice(); + const pkg_names = pkgs.items(.name); + const string_buf = this.manager.lockfile.buffers.string_bytes.items; + std.sort.block(PackageID, keys.items, .{}, struct { + fn lessThan(_: void, a: PackageID, b: PackageID) bool { + return std.mem.lessThan(u8, pkg_names[a].slice(string_buf), pkg_names[b].slice(string_buf)); + } + }.lessThan); + + for (keys.items) |pkg_id| { + var entry = (this.collector.package_paths.getEntry(pkg_id) orelse unreachable); + // ... (rest unchanged)
175-183: Message accuracy: “installed successfully” vs “already present.”If the partial install skips because the scanner is already present, “installed successfully” can mislead. Tailor the message based on summary.success/skipped.
- Output.prettyln("<r><green><b>Security scanner installed successfully.<r>", .{}); + Output.prettyln("<r><green><b>Security scanner ready.<r>", .{});
1039-1138: Advisory parsing: robust validation and safe duplication.Type checks with explicit errors + ownership rules are correct. One caveat: package disambiguation by name only may map to the first match when multiple versions exist; acceptable given input schema, but consider allowing an optional version in future.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between c0ba7e9 and a3173fe4e36621de1bf570f010d0b6b06bef563f.
⛔ Files ignored due to path filters (1)
test/cli/install/__snapshots__/bun-security-scanner-matrix.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (29)
cmake/Sources.json(1 hunks)cmake/sources/JavaScriptSources.txt(1 hunks)cmake/sources/ZigSources.txt(1 hunks)cmake/targets/BuildBun.cmake(1 hunks)packages/bun-types/shell.d.ts(1 hunks)src/cli/package_manager_command.zig(3 hunks)src/cli/scan_command.zig(1 hunks)src/install/PackageInstaller.zig(3 hunks)src/install/PackageManager.zig(2 hunks)src/install/PackageManager/CommandLineArguments.zig(2 hunks)src/install/PackageManager/PackageManagerEnqueue.zig(2 hunks)src/install/PackageManager/install_with_manager.zig(4 hunks)src/install/PackageManager/scanner-entry-globals.d.ts(1 hunks)src/install/PackageManager/scanner-entry.ts(1 hunks)src/install/PackageManager/security_scanner.zig(8 hunks)src/install/hoisted_install.zig(6 hunks)src/install/isolated_install.zig(4 hunks)src/output.zig(2 hunks)src/resolver/resolver.zig(1 hunks)test/cli/install/bun-install-security-provider.test.ts(2 hunks)test/cli/install/bun-pm-scan.test.ts(1 hunks)test/cli/install/bun-security-scanner-matrix.test.ts(1 hunks)test/cli/install/bun-update-security-edge-cases.test.ts(1 hunks)test/cli/install/bun-update-security-provider.test.ts(1 hunks)test/cli/install/bun-update-security-scan-all.test.ts(1 hunks)test/cli/install/bun-update-security-simple.test.ts(1 hunks)test/cli/install/generate-scanner-tarballs.ts(1 hunks)test/cli/install/simple-dummy-registry.ts(1 hunks)test/js/bun/test/jest.d.ts(1 hunks)
🧰 Additional context used
🧠 Learnings (23)
📚 Learning: 2025-08-30T00:13:36.784Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/zig-javascriptcore-classes.mdc:0-0
Timestamp: 2025-08-30T00:13:36.784Z
Learning: Applies to src/bun.js/bindings/generated_classes_list.zig : Update src/bun.js/bindings/generated_classes_list.zig to include new classes
Applied to files:
cmake/targets/BuildBun.cmakecmake/sources/ZigSources.txt
📚 Learning: 2025-08-30T00:11:57.056Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.056Z
Learning: Ensure new source files are included in the build system targets
Applied to files:
cmake/targets/BuildBun.cmake
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Run bun run zig:check-all when making platform-specific changes to ensure cross-platform compilation
Applied to files:
cmake/targets/BuildBun.cmake
📚 Learning: 2025-08-30T00:13:36.784Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/zig-javascriptcore-classes.mdc:0-0
Timestamp: 2025-08-30T00:13:36.784Z
Learning: Applies to src/bun.js/**/*.zig : In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS<ClassName> and re-export toJS/fromJS/fromJSDirect
Applied to files:
cmake/targets/BuildBun.cmake
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/js/bun/**/*.test.{ts,tsx} : Put Bun-specific API tests under test/js/bun/
Applied to files:
test/cli/install/bun-install-security-provider.test.tstest/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.tstest/cli/install/generate-scanner-tarballs.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Applied to files:
test/cli/install/bun-install-security-provider.test.tstest/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Applied to files:
test/cli/install/bun-install-security-provider.test.tstest/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.tstest/cli/install/generate-scanner-tarballs.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/**/*.test.{ts,tsx} : Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Applied to files:
test/cli/install/bun-install-security-provider.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-install-security-provider.test.tstest/js/bun/test/jest.d.tstest/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.tstest/cli/install/generate-scanner-tarballs.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/js/**/*.{js,ts} : Place JavaScript and TypeScript tests under test/js/
Applied to files:
cmake/Sources.json
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Import testing utilities (devTest, prodTest, devAndProductionTest, Dev, Client) from test/bake/bake-harness.ts
Applied to files:
cmake/sources/JavaScriptSources.txt
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/dev/bundle.test.ts : bundle.test.ts should contain DevServer-specific bundling tests
Applied to files:
cmake/sources/JavaScriptSources.txt
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to src/js/**/*.{ts,js} : In built-in modules, use export default (converted to a return statement by the preprocessor)
Applied to files:
cmake/sources/JavaScriptSources.txt
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.tstest/cli/install/generate-scanner-tarballs.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.tstest/cli/install/generate-scanner-tarballs.tssrc/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Use bun:test in files that end in *.test.ts
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : Place CLI command tests (e.g., bun install, bun init) under test/cli/
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.tstest/cli/install/generate-scanner-tarballs.tssrc/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{test/js/bun/**,test/js/node/**} : Place unit tests by module under /test/js/bun/ and /test/js/node/
Applied to files:
test/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-pm-scan.test.tstest/cli/install/bun-update-security-scan-all.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Applied to files:
test/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-provider.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: For Node.js compatibility bugs, validate expected behavior in Node.js first, then confirm failure on Bun canary
Applied to files:
test/cli/install/bun-update-security-simple.test.tstest/cli/install/bun-update-security-edge-cases.test.tstest/cli/install/bun-update-security-scan-all.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to **/*.zig : Format Zig files with zig fmt (bun run zig-format)
Applied to files:
cmake/sources/ZigSources.txt
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/bundler/**/*.test.{ts,tsx} : Put bundler and transpiler tests under test/bundler/
Applied to files:
test/cli/install/bun-update-security-scan-all.test.ts
🔇 Additional comments (26)
cmake/sources/ZigSources.txt (1)
482-482: Nice: scan_command.zig is registered in the Zig sources manifestThis ensures bun pm scan wiring can compile. Confirm that CLI dispatch and help/completions reference it as intended.
Would you like a quick grep script to verify that ScanCommand is exported from package_manager_command.zig and routed from cli.zig?
cmake/sources/JavaScriptSources.txt (1)
1-1: Good addition; confirm no other ad-hoc inclusions for this filescanner-entry.ts belongs here. Given this, the extra inclusion in BuildBun.cmake is unnecessary (see related comment) and can be removed to avoid duplication.
src/install/PackageManager.zig (1)
157-158: Adding Subcommand.scan: verify feature flags and JSON output expectationsscan is now a first-class subcommand. If bun pm scan should support --json (likely), consider updating supportsJsonOutput to include .scan. Also verify that help text and workspace filtering behave as desired.
Example adjustment (outside this hunk, for reference):
pub fn supportsJsonOutput(this: Subcommand) bool { return switch (this) { .audit, .pm, .info, .scan => true, else => false, }; }packages/bun-types/shell.d.ts (1)
109-109: Verify dependency on NodeJS.Dict is safeNodeJS.Dict comes from @types/node. If consumers don’t include Node types, this can break type resolution. If that’s a concern, consider defining a local structural alias instead of referencing NodeJS.Dict.
Would you like me to scan bun-types for NodeJS.* references and report whether @types/node is already a hard dependency?
src/output.zig (2)
10-12: No duplicate C-side definitions of bun_stdio_tty found
Only declared asextern "C" int32_t bun_stdio_tty[3];in BunProcess.cpp and c-bindings.cpp; the Zigpub export var bun_stdio_ttyis the sole definition.
436-446: Confirm POSIX bun_stdio_tty initialization
WindowsStdio.init sets bun_stdio_tty on Windows; please verify that the extern C fn bun_initialize_process populates bun_stdio_tty[0–2] via isatty on POSIX before these helpers run.test/cli/install/bun-install-security-provider.test.ts (3)
142-144: Error copy: path-not-found wording LGTMClear, actionable guidance. No changes needed.
152-153: Import error prefix LGTMConsistent "Security scanner failed:" prefix will help users triage. Good.
73-75: All tests updated to use the new message No remaining instances of the old phrasing were found across the suite.src/install/PackageManager/PackageManagerEnqueue.zig (1)
1389-1393: Prefetch override inconsistency: extract path still gated only by prefetch_resolved_tarballsgetOrPutResolvedPackageWithFindResult short-circuits tarball downloads when prefetch_resolved_tarballs is false, with no way to override. If the new force flag is meant to enable downloads during partial installs/scans, you may need to thread that signal here as well.
Would you like a patch to plumb a force flag through determinePreinstallState/getOrPutResolvedPackageWithFindResult so behavior matches enqueuePackageForDownload?
src/cli/package_manager_command.zig (1)
162-165: LGTM: wiring for “bun pm scan”Dispatch and exit flow look correct; placement before “pack” is fine.
test/cli/install/bun-pm-scan.test.ts (1)
233-236: Confirm warning exit code policy is intentionalpm scan exits with 1 when any advisories (including warnings) are present. If the intended policy is “warnings fail CI,” keep as-is; otherwise adjust to 0 for warnings-only.
Do you want warnings to be non-zero? If not, I can submit a follow-up patch in scan_command.zig to exit(0) when only warnings are present.
src/cli/scan_command.zig (1)
6-10: Message wording mismatch with testsTests should assert “No package.json found …” (current message) rather than “was found”. No code change required if we adjust the test as suggested.
I can update any other tests or docs that reference the older phrasing.
src/install/PackageManager/install_with_manager.zig (1)
1001-1031: Path/name matching logic looks reasonable, but verify .name vs .path semantics.matchImpl is path-glob oriented; you’re feeding a package name for .name and an absolute path for .path. Please confirm this aligns with prior behavior (especially negation patterns). If .name expects different matching rules, consider a dedicated comparator.
src/install/hoisted_install.zig (1)
193-194: Good: prefetch-skip check gated by partial install.This ensures scanner-driven partial installs don’t stall on prefetch heuristics.
src/install/isolated_install.zig (2)
860-871: Propagating partial-install flag to enqueuePackageForDownload is good.This ties isolated path to the partial install semantics used by the scanner.
171-195: Root-only partial-queue looks correct; add invalid_package_id guard.Queueing only requested roots at the real root is correct for partial install. Add a check to skip invalid resolutions.
- for (dep_ids_sort_buf.items) |dep_id| { + for (dep_ids_sort_buf.items) |dep_id| { const pkg_id = resolutions[dep_id]; - if (pkg_id == invalid_package_id) { - continue; - } + if (pkg_id == invalid_package_id) continue;Likely an incorrect or invalid review comment.
test/cli/install/bun-update-security-scan-all.test.ts (2)
64-91: End-to-end “update scans all” scenario is solid.Covers scanner enable/disable, stderr tracing, advisory rendering, and exit code behavior without TTY.
93-172: Targeted package scan behavior looks correct.Confirms scanning is limited to updated packages and their deps, and exit code semantics for warnings.
test/cli/install/bun-security-scanner-matrix.test.ts (1)
268-275: Hard-coded messages for npm-scanner partial install.If these strings change upstream, tests will flap. Prefer a looser assertion (e.g., contains “security scanner” and “installed”) or snapshot the status line.
src/install/PackageInstaller.zig (1)
1381-1400: installPackage callers verified
All invocations now pass(dependency_id, package_id, log_level)(only in hoisted_install.zig) matching the updated signature; aliasing and resolution remain internal and consistent.src/install/PackageManager/security_scanner.zig (5)
641-660: Also escape boolean/string substitutions consistently.You correctly inject JSON for packages and booleans for suppress flag. Keep it consistent: already good for PACKAGES_JSON and SUPPRESS_ERROR. No change needed.
597-606: Verbose diagnostics are helpful. Good.Logging security provider paths and CWD under verbose will aid debugging tricky setups.
689-690: Count computed from dedupe map is correct.packages_scanned = unique npm packages traversed. Matches collector semantics.
218-280: Advisory printing UX looks solid.Clear grouping, ancestry display, and pluralization. Nice.
343-375: Collector lifecycle and memory frees are correct.Deinit frees pkg_path/dep_path allocations. Good.
pm scan commandpm scan command
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (7)
test/cli/install/simple-dummy-registry.ts (1)
36-39: Good fix: robust decoding for scoped package names.Switching to decodeURIComponent avoids missing %2F/%2f and similar encodings. Nice.
Also applies to: 142-146
test/cli/install/bun-security-scanner-matrix.test.ts (2)
426-437: Gate the full matrix behind an env flag to keep CI fast.Default to a representative subset; enable exhaustive runs with SCANNER_MATRIX_ALL=1.
describe("Security Scanner Matrix Tests", () => { let i = 0; - describe.each(["install", "update", "add", "remove", "uninstall"] as const)("bun %s", command => { + const runAll = process.env.SCANNER_MATRIX_ALL === "1"; + const commands = runAll ? (["install","update","add","remove","uninstall"] as const) : (["install","update"] as const); + const argVariants = runAll + ? ([{args:[],name:"no args"},{args:["is-even"],name:"is-even"},{args:["left-pad","is-even"],name:"left-pad,is-even"}] as const) + : ([{args:["is-even"],name:"is-even"}] as const); + const nodeModulesOpts = runAll ? ([true,false] as const) : ([false] as const); + const linkers = runAll ? (["hoisted","isolated"] as const) : (["hoisted"] as const); + const scannerTypes = runAll ? (["local","npm","npm.bunfigonly"] as const) : (["local","npm"] as const); + const lockfileOpts = runAll ? ([true,false] as const) : ([false] as const); + const advisoryLevels = runAll ? (["none","warn","fatal"] as const) : (["none","fatal"] as const); + + describe.each(commands)("bun %s", command => { - describe.each([ - { args: [], name: "no args" }, - { args: ["is-even"], name: "is-even" }, - { args: ["left-pad", "is-even"], name: "left-pad,is-even" }, - ])("$name", ({ args }) => { - describe.each([true, false] as const)("(node_modules: %p)", hasExistingNodeModules => { - describe.each(["hoisted", "isolated"] as const)("--linker=%s", linker => { - describe.each(["local", "npm", "npm.bunfigonly"] as const)("(scanner: %s)", scannerType => { - describe.each([true, false] as const)("(bun.lock exists: %p)", hasLockfile => { - describe.each(["none", "warn", "fatal"] as const)("(advisories: %s)", scannerReturns => { + describe.each(argVariants)("$name", ({ args }) => { + describe.each(nodeModulesOpts)("(node_modules: %p)", hasExistingNodeModules => { + describe.each(linkers)("--linker=%s", linker => { + describe.each(scannerTypes)("(scanner: %s)", scannerType => { + describe.each(lockfileOpts)("(bun.lock exists: %p)", hasLockfile => { + describe.each(advisoryLevels)("(advisories: %s)", scannerReturns => {Also applies to: 429-437, 431-434, 435-437, 437-438, 439-440
283-285: Replace no-op assertion for bunfig-only scanner with real checks.Assert that the scanner didn’t run and a helpful error was shown.
- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + expect(errAndOut).not.toMatch(/SCANNER_RAN/); + expect(errAndOut).toMatch(/(Security scanner|Could not (resolve|load) scanner)/i); + }src/install/PackageManager/PackageManagerEnqueue.zig (1)
257-259: Honor --lockfile-only even when forcing prefetch.Prevent any tarball fetch when lockfile-only is set, regardless of force_install_skip_prefetch_check.
// Skip tarball download when prefetch_resolved_tarballs is disabled (e.g., --lockfile-only) - if (!this.options.do.prefetch_resolved_tarballs and !force_install_skip_prefetch_check) return; + if (this.options.lockfile_only) return; + if (!this.options.do.prefetch_resolved_tarballs and !force_install_skip_prefetch_check) return;src/install/PackageManager/install_with_manager.zig (1)
599-602: Enable prefetch only when a scan is attempted.Currently prefetch is set whenever a scanner is configured, even if the subcommand won’t run a scan. Move it inside the is_subcommand_to_run_scanner branch.
- } - manager.options.do.prefetch_resolved_tarballs = true; + } + // Enable prefetch only when a scan may run + if (is_subcommand_to_run_scanner) { + manager.options.do.prefetch_resolved_tarballs = true; + } }src/install/hoisted_install.zig (1)
220-221: Guard invalid_package_id before install to prevent OOB/crashBoth hot paths may pass invalid_package_id into installPackage, risking out-of-bounds on names/resolutions. Add a guard as previously suggested.
- const package_id = this.lockfile.buffers.resolutions.items[remaining[i]]; - doInstallPackageIfInPackagesToInstall(&installer, packages_to_install, remaining[i], package_id, log_level); + const package_id = this.lockfile.buffers.resolutions.items[remaining[i]]; + if (package_id != invalid_package_id) { + doInstallPackageIfInPackagesToInstall(&installer, packages_to_install, remaining[i], package_id, log_level); + } - const pkg_id = this.lockfile.buffers.resolutions.items[dependency_id]; - doInstallPackageIfInPackagesToInstall(&installer, packages_to_install, dependency_id, pkg_id, log_level); + const pkg_id = this.lockfile.buffers.resolutions.items[dependency_id]; + if (pkg_id != invalid_package_id) { + doInstallPackageIfInPackagesToInstall(&installer, packages_to_install, dependency_id, pkg_id, log_level); + }Also applies to: 247-249
src/install/PackageManager/security_scanner.zig (1)
633-639: Escape injected module string to avoid JS breakage/injectionRaw splice of security_scanner risks syntax errors or injection. Replace with JSON-escaped string literal.
- if (std.mem.indexOf(u8, temp_source, scanner_placeholder)) |index| { - try code.appendSlice(temp_source[0..index]); - try code.appendSlice(security_scanner); - try code.appendSlice(temp_source[index + scanner_placeholder.len ..]); - temp_source = code.items; - } + if (std.mem.indexOf(u8, temp_source, scanner_placeholder)) |index| { + try code.appendSlice(temp_source[0..index]); + const scanner_js = bun.fmt.formatJSONStringUTF8(security_scanner, .{}); + try code.appendSlice(scanner_js); + try code.appendSlice(temp_source[index + scanner_placeholder.len ..]); + temp_source = code.items; + }
🧹 Nitpick comments (7)
src/output.zig (1)
436-447: TTY helpers look good; add tiny docs for discoverabilityThe helpers are clear and cheap; suggest brief doc comments.
+/// True if STDOUT is a TTY (1 = yes, 0 = no in bun_stdio_tty[1]). pub inline fn isStdoutTTY() bool { return bun_stdio_tty[1] != 0; } +/// True if STDERR is a TTY. pub inline fn isStderrTTY() bool { return bun_stdio_tty[2] != 0; } +/// True if STDIN is a TTY. pub inline fn isStdinTTY() bool { return bun_stdio_tty[0] != 0; }cmake/targets/BuildBun.cmake (1)
637-640: Avoid direct TS source in bun-zig SOURCES; rely on JS manifest outputs.scanner-entry.ts should already be tracked via BUN_JAVASCRIPT_SOURCES and its generated outputs in BUN_JAVASCRIPT_OUTPUTS. Appending the raw TS path to bun-zig’s SOURCES is redundant and can complicate dependency tracking (especially on Windows). Remove it and let the existing JS pipeline handle rebuilds.
SOURCES ${BUN_ZIG_SOURCES} ${BUN_ZIG_GENERATED_SOURCES} - ${CWD}/src/install/PackageManager/scanner-entry.ts # Is there a better way to do this? )test/cli/install/bun-security-scanner-matrix.test.ts (1)
160-168: Prefer filesystem APIs over shell rm for cross-platform reliability.Use node:fs/promises rm to avoid shell differences on Windows.
+import { rm } from "node:fs/promises"; ... if (shouldDoInitialInstall && !hasExistingNodeModules) { - console.log(redShellPrefix, `rm -rf ${dir}/node_modules`); - await $`rm -rf node_modules`.cwd(dir); + console.log(redShellPrefix, `rm -rf ${dir}/node_modules`); + await rm(join(dir, "node_modules"), { recursive: true, force: true }); } if (shouldDoInitialInstall && !hasLockfile) { - console.log(redShellPrefix, `rm ${dir}/bun.lock`); - await $`rm bun.lock`.cwd(dir); + console.log(redShellPrefix, `rm ${dir}/bun.lock`); + await rm(join(dir, "bun.lock"), { force: true }); }Also applies to: 1-6
src/install/hoisted_install.zig (1)
365-383: Avoid repeated BFS in shouldInstallPackage; precompute an allowed setCurrent per-dependency BFS scales poorly under large graphs. Build a one-time “allowed” set (Bitset or HashMap) from all roots, then check membership in O(1) inside doInstallPackageIfInPackagesToInstall. I can draft a focused refactor if you want it in this PR.
Also applies to: 385-423, 425-439
src/install/isolated_install.zig (1)
835-859: Remove dead commented code before mergeThe commented should_install block adds noise and can confuse future readers.
- // const should_install = should_install: { - // if (manager.options.do.prefetch_resolved_tarballs) break :should_install true; - // // we only want to consider this package for download if it's in the packages_to_install array - // if (packages_to_install) |_pkgs| { - // for (_pkgs) |pkg_to_install| { - // if (pkg_to_install == pkg_id) { - // break :should_install true; - // } - // } - // } else { - // // If packages_to_install is null, we're doing a full install (not partial) - // // This happens after security scan passes - we need to install everything - // break :should_install true; - // } - // break :should_install false; - // }; - // if (!should_install) { - // entry_steps[entry_id.get()].store(.done, .monotonic); - // installer.onTaskComplete(entry_id, .skipped); - // continue; - // }src/install/PackageManager/security_scanner.zig (2)
664-666: Avoid duplicate allocation of json_data in subprocess structjson_data is embedded into code and never otherwise used; duplicating/storing it in the subprocess adds alloc/free churn. Consider removing the field and associated dup/free.
Also applies to: 670-675
377-410: Minor performance: reduce O(N^2) scans in collectUpdatePackages/processQueueYou repeatedly scan all packages to locate parents and traverse. Building a name->pkg_id and parent adjacency once would trim this substantially on large graphs. Happy to propose a focused refactor if desired.
Also applies to: 466-517
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between a3173fe4e36621de1bf570f010d0b6b06bef563f and 9c96bb5.
⛔ Files ignored due to path filters (1)
test/cli/install/__snapshots__/bun-security-scanner-matrix.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (29)
cmake/Sources.json(1 hunks)cmake/sources/JavaScriptSources.txt(1 hunks)cmake/sources/ZigSources.txt(1 hunks)cmake/targets/BuildBun.cmake(1 hunks)packages/bun-types/shell.d.ts(2 hunks)src/cli/package_manager_command.zig(3 hunks)src/cli/scan_command.zig(1 hunks)src/install/PackageInstaller.zig(3 hunks)src/install/PackageManager.zig(2 hunks)src/install/PackageManager/CommandLineArguments.zig(2 hunks)src/install/PackageManager/PackageManagerEnqueue.zig(2 hunks)src/install/PackageManager/install_with_manager.zig(4 hunks)src/install/PackageManager/scanner-entry-globals.d.ts(1 hunks)src/install/PackageManager/scanner-entry.ts(1 hunks)src/install/PackageManager/security_scanner.zig(8 hunks)src/install/hoisted_install.zig(6 hunks)src/install/isolated_install.zig(4 hunks)src/output.zig(2 hunks)src/resolver/resolver.zig(1 hunks)test/cli/install/bun-install-security-provider.test.ts(2 hunks)test/cli/install/bun-pm-scan.test.ts(1 hunks)test/cli/install/bun-security-scanner-matrix.test.ts(1 hunks)test/cli/install/bun-update-security-edge-cases.test.ts(1 hunks)test/cli/install/bun-update-security-provider.test.ts(1 hunks)test/cli/install/bun-update-security-scan-all.test.ts(1 hunks)test/cli/install/bun-update-security-simple.test.ts(1 hunks)test/cli/install/generate-scanner-tarballs.ts(1 hunks)test/cli/install/simple-dummy-registry.ts(1 hunks)test/js/bun/test/jest.d.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (19)
- src/install/PackageManager/scanner-entry-globals.d.ts
- cmake/sources/ZigSources.txt
- test/cli/install/bun-update-security-scan-all.test.ts
- cmake/Sources.json
- test/cli/install/bun-update-security-edge-cases.test.ts
- cmake/sources/JavaScriptSources.txt
- src/resolver/resolver.zig
- test/js/bun/test/jest.d.ts
- packages/bun-types/shell.d.ts
- src/install/PackageManager/CommandLineArguments.zig
- src/install/PackageManager/scanner-entry.ts
- test/cli/install/generate-scanner-tarballs.ts
- test/cli/install/bun-update-security-simple.test.ts
- src/cli/package_manager_command.zig
- src/cli/scan_command.zig
- test/cli/install/bun-install-security-provider.test.ts
- test/cli/install/bun-update-security-provider.test.ts
- src/install/PackageManager.zig
- test/cli/install/bun-pm-scan.test.ts
🧰 Additional context used
📓 Path-based instructions (10)
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Place tests in test/ and ensure filenames end with .test.ts or .test.tsx
Always use port: 0 in tests; never hardcode port numbers or use custom random-port functions
Prefer snapshot tests using normalizeBunSnapshot(...).toMatchInlineSnapshot(...) over exact string comparisons
Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Put CLI command tests under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Format JavaScript/TypeScript with Prettier (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/simple-dummy-registry.ts
test/**/*.test.ts
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.ts: Use bun:test in files that end in *.test.ts
Prefer async/await over callbacks in tests
For single-callback flows in tests, use Promise.withResolvers()
Do not set timeouts on tests; rely on Bun’s built-in timeouts
Use tempDirWithFiles from harness to create temporary directories/files in tests
Organize tests with describe blocks
Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Avoid flaky tests: never wait for arbitrary time; wait for conditions to be met
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/{**/*.test.ts,**/*-fixture.ts}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/{**/*.test.ts,**/*-fixture.ts}: When spawning Bun processes, use bunExe() and bunEnv from harness
Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Never hardcode port numbers; use port: 0 to get a random port
Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/simple-dummy-registry.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/simple-dummy-registry.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix.test.tstest/cli/install/simple-dummy-registry.ts
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/PackageManager/install_with_manager.zigsrc/install/PackageManager/PackageManagerEnqueue.zigsrc/output.zigsrc/install/hoisted_install.zigsrc/install/PackageManager/security_scanner.zigsrc/install/isolated_install.zigsrc/install/PackageInstaller.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager/install_with_manager.zigsrc/install/PackageManager/PackageManagerEnqueue.zigsrc/output.zigsrc/install/hoisted_install.zigsrc/install/PackageManager/security_scanner.zigsrc/install/isolated_install.zigsrc/install/PackageInstaller.zig
🧠 Learnings (14)
📚 Learning: 2025-08-30T00:13:36.784Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/zig-javascriptcore-classes.mdc:0-0
Timestamp: 2025-08-30T00:13:36.784Z
Learning: Applies to src/bun.js/bindings/generated_classes_list.zig : Update src/bun.js/bindings/generated_classes_list.zig to include new classes
Applied to files:
cmake/targets/BuildBun.cmake
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Run bun run zig:check-all when making platform-specific changes to ensure cross-platform compilation
Applied to files:
cmake/targets/BuildBun.cmake
📚 Learning: 2025-08-30T00:13:36.784Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/zig-javascriptcore-classes.mdc:0-0
Timestamp: 2025-08-30T00:13:36.784Z
Learning: Applies to src/bun.js/**/*.zig : In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS<ClassName> and re-export toJS/fromJS/fromJSDirect
Applied to files:
cmake/targets/BuildBun.cmake
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/js/bun/**/*.test.{ts,tsx} : Put Bun-specific API tests under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tssrc/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Explicitly assert client console logs with c.expectMessage; unasserted logs should not appear
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.tssrc/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to **/*.zig : In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
Applied to files:
src/install/PackageManager/install_with_manager.zig
🧬 Code graph analysis (1)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
test/harness.ts (2)
registryUrl(1630-1632)tempDirWithFiles(258-265)test/cli/install/simple-dummy-registry.ts (4)
getRegistry(168-170)SimpleRegistry(6-151)startRegistry(155-159)stopRegistry(161-166)
🔇 Additional comments (12)
src/output.zig (1)
10-12: Confirm removal of old callsites & POSIX TTY init
- No occurrences of
Source.bun_stdio_ttyorbun_stdio_ttyacross Zig/C code—please verify no stray references remain- Confirm that POSIX initialization (in
Stdio.init()orbun_initialize_process()) populatesbun_stdio_tty; if not, add fallback usingstd.posix.isattyfor stdin/stdout/stderrsrc/install/PackageManager/PackageManagerEnqueue.zig (1)
233-243: Verified all enqueuePackageForDownload call sites now pass the new force_install_skip_prefetch_check boolean argument.src/install/hoisted_install.zig (2)
193-194: Prefetch-skip wiring looks correctTying force_install_skip_prefetch_check to packages_to_install != null aligns with the partial-install flow.
1-8: No action required: all callsites updated
Both invocations in security_scanner.zig and install_with_manager.zig now pass the new packages_to_install argument.src/install/isolated_install.zig (2)
171-194: Root-scoped partial queueing LGTMQueuing only requested root deps in partial mode is sound; transitive deps are discovered on subsequent iterations.
870-871: Propagating partial-install flag to enqueue is correctPassing packages_to_install != null through to enqueuePackageForDownload is consistent with hoisted flow.
src/install/PackageInstaller.zig (3)
5-5: Good: default provided for new struct fieldAdding = false keeps existing initializers source-compatible.
978-987: Prefetch control hooked up correctlyForwarding force_install_skip_prefetch_check to enqueuePackageForDownload is correct.
1381-1400: All installPackage call sites updated. External calls in src/install/hoisted_install.zig now pass (dependency_id, package_id, log_level), matching the revised signature.src/install/PackageManager/security_scanner.zig (3)
734-741: Working dir for scanner subprocess set to top_level_dir — goodThis reduces path ambiguity when resolving the scanner module.
587-591: scanner-entry.ts is already listed in cmake/sources/JavaScriptSources.txt, no action required.
914-925: Ignore this check:isPackagePathcorrectly excludes.//../paths
isPackagePathreturns false for inputs starting with"./"or"../"(seeisPackagePathNotAbsolute), so relative file paths won’t be misclassified as packages and no change is needed.Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
test/js/web/fetch/utf8-bom.test.ts (3)
27-27: Remove remainingas anyfor consistencySame pattern elsewhere doesn’t need a cast either. Suggested cleanup:
- expect(await blob.json()).toStrictEqual({ "hello": "World 🌎" } as any); + expect(await blob.json()).toStrictEqual({ "hello": "World 🌎" }); - expect(await blob.json()).toEqual({ "hello": "World" } as any); + expect(await blob.json()).toEqual({ "hello": "World" }); - expect(await response.json()).toEqual({ "hello": "World" } as any); + expect(await response.json()).toEqual({ "hello": "World" }); - expect(await request.json()).toEqual({ "hello": "World" } as any); + expect(await request.json()).toEqual({ "hello": "World" }); - expect(await Bun.readableStreamToJSON(stream)).toEqual({ "hello": "World" } as any); + expect(await Bun.readableStreamToJSON(stream)).toEqual({ "hello": "World" });Also applies to: 44-44, 64-64, 90-90, 121-121
8-9: Prefer rejects.toThrow() for async error assertions
toThrow()expects a synchronous throw; for Promises use.rejects.toThrow().- expect(async () => await blob.json()).toThrow(); + await expect(blob.json()).rejects.toThrow(); - expect(async () => await blob.json()).toThrow(); + await expect(blob.json()).rejects.toThrow();Also applies to: 15-16
42-45: Nit: considertoStrictEqualfor JSON object checksUsing
toStrictEqualeverywhere for JSON objects would uniformly assert on prototypes as well, matching Line 27.Also applies to: 60-65, 86-91, 120-122, 141-141
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
test/cli/install/bun-pm-scan.test.ts(1 hunks)test/js/bun/test/jest.d.ts(1 hunks)test/js/web/fetch/utf8-bom.test.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- test/js/bun/test/jest.d.ts
- test/cli/install/bun-pm-scan.test.ts
🧰 Additional context used
📓 Path-based instructions (9)
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Place tests in test/ and ensure filenames end with .test.ts or .test.tsx
Always use port: 0 in tests; never hardcode port numbers or use custom random-port functions
Prefer snapshot tests using normalizeBunSnapshot(...).toMatchInlineSnapshot(...) over exact string comparisons
Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Files:
test/js/web/fetch/utf8-bom.test.ts
test/js/web/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Put Web API tests under test/js/web/
Files:
test/js/web/fetch/utf8-bom.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Format JavaScript/TypeScript with Prettier (bun run prettier)
Files:
test/js/web/fetch/utf8-bom.test.ts
test/**/*.test.ts
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.ts: Use bun:test in files that end in *.test.ts
Prefer async/await over callbacks in tests
For single-callback flows in tests, use Promise.withResolvers()
Do not set timeouts on tests; rely on Bun’s built-in timeouts
Use tempDirWithFiles from harness to create temporary directories/files in tests
Organize tests with describe blocks
Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Avoid flaky tests: never wait for arbitrary time; wait for conditions to be met
Files:
test/js/web/fetch/utf8-bom.test.ts
test/{**/*.test.ts,**/*-fixture.ts}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/{**/*.test.ts,**/*-fixture.ts}: When spawning Bun processes, use bunExe() and bunEnv from harness
Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Never hardcode port numbers; use port: 0 to get a random port
Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Files:
test/js/web/fetch/utf8-bom.test.ts
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/js/web/fetch/utf8-bom.test.ts
test/js/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place JavaScript and TypeScript tests under test/js/
Files:
test/js/web/fetch/utf8-bom.test.ts
test/js/web/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place Web API tests under test/js/web/, separated by category
Files:
test/js/web/fetch/utf8-bom.test.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/js/web/fetch/utf8-bom.test.ts
🧠 Learnings (1)
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Applied to files:
test/js/web/fetch/utf8-bom.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (1)
test/js/web/fetch/utf8-bom.test.ts (1)
141-141: Good: removed unnecessary type assertion in JSON equalityDropping
as anyimproves type-safety and readability.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/install/PackageManager/security_scanner.zig (2)
677-688: Add a watchdog timeout to prevent hangs/timeouts.If the subprocess stalls, sleepUntil waits indefinitely. Add a timeout and kill the child to avoid CI timeouts.
Example approach:
- manager.sleepUntil(&closure, &@TypeOf(closure).isDone); + const deadline_ms: i64 = std.time.milliTimestamp() + 60_000; // env-configurable + while (!closure.isDone()) { + if (std.time.milliTimestamp() > deadline_ms) { + if (scanner.process) |p| p.kill() catch {}; + return error.SecurityScannerTimedOut; + } + manager.sleep(); + }I can wire this to an env/flag (e.g., BUN_SCANNER_TIMEOUT_MS).
713-721: Close pipe fds on early errors to avoid FD leaks.If spawnProcess fails, both pipe ends leak. Use errdefer after pipe creation.
const pipe_result = bun.sys.pipe(); - const pipe_fds = switch (pipe_result) { + const pipe_fds = switch (pipe_result) { .err => { return error.IPCPipeFailed; }, .result => |fds| fds, }; + errdefer { + // Close both ends if we error before handing ownership to ipc_reader/spawned child + pipe_fds[0].close(); + pipe_fds[1].close(); + }
♻️ Duplicate comments (2)
src/install/PackageManager/install_with_manager.zig (1)
569-603: Gate prefetch_resolved_tarballs on actually running a scan.This still sets prefetch even when the subcommand won’t run the scanner. Move it inside the is_subcommand_to_run_scanner branch (after the scan attempt).
if (manager.options.security_scanner != null) { const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove; if (is_subcommand_to_run_scanner) { if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| { @@ } + // Enable prefetch only when a scan has been attempted + manager.options.do.prefetch_resolved_tarballs = true; } - - manager.options.do.prefetch_resolved_tarballs = true; }src/install/PackageManager/security_scanner.zig (1)
632-641: Escape the scanner module string to avoid parse/injection issues.Splicing raw security_scanner into JS can break the script or allow injection. JSON-escape it so the placeholder becomes a valid JS string literal.
- if (std.mem.indexOf(u8, temp_source, scanner_placeholder)) |index| { - try code.appendSlice(temp_source[0..index]); - try code.appendSlice(security_scanner); - try code.appendSlice(temp_source[index + scanner_placeholder.len ..]); - temp_source = code.items; - } + if (std.mem.indexOf(u8, temp_source, scanner_placeholder)) |index| { + try code.appendSlice(temp_source[0..index]); + const scanner_js = bun.fmt.formatJSONStringUTF8(security_scanner, .{}); + try code.appendSlice(scanner_js); + try code.appendSlice(temp_source[index + scanner_placeholder.len ..]); + temp_source = code.items; + }
🧹 Nitpick comments (5)
src/install/PackageManager/install_with_manager.zig (1)
983-1035: Confirm ownership semantics for WorkspaceFilter elements.You return an owned slice of WorkspaceFilter and free only the slice buffer at callsites. If WorkspaceFilter contains owned allocations (e.g., duplicated strings/paths), they likely need per-element deinit to avoid leaks.
If needed, add a helper:
pub fn deinitWorkspaceFilters(alloc: std.mem.Allocator, filters: []const WorkspaceFilter) void { for (filters) |*f| f.deinit(alloc); // if WorkspaceFilter has deinit alloc.free(filters); }Then replace:
defer manager.allocator.free(workspace_filters);with:
defer deinitWorkspaceFilters(manager.allocator, workspace_filters);src/install/PackageManager/security_scanner.zig (4)
738-746: Capture stderr for diagnostics (optional).Right now stderr is inherited; on parse failures you can’t show scanner errors. Pipe stderr and append to stderr_data; include it in error logs.
- .stderr = .inherit, + .stderr = .pipe,And when JSON parsing fails or scanner exits non-0, print a tail of stderr_data.
Also applies to: 797-809
357-364: Use a single allocator consistently.dedupe and queue use default_allocator while package_paths uses manager.allocator. Prefer manager.allocator for all to simplify lifetime management.
- .dedupe = std.AutoArrayHashMap(PackageID, void).init(bun.default_allocator), - .queue = std.fifo.LinearFifo(QueueItem, .Dynamic).init(bun.default_allocator), + .dedupe = std.AutoArrayHashMap(PackageID, void).init(manager.allocator), + .queue = std.fifo.LinearFifo(QueueItem, .Dynamic).init(manager.allocator),
826-854: Robust IPC/result handling.Good validation and structured errors. Consider including stderr (see earlier comment) in error messages to aid debugging CI failures.
Also applies to: 998-1037
1040-1139: Parsing advisories: OK; micro-optimization optional.Lookup by linear scan is fine; if advisories get large, precompute a name->PackageID map once.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/install/PackageManager/install_with_manager.zig(4 hunks)src/install/PackageManager/security_scanner.zig(8 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/PackageManager/security_scanner.zigsrc/install/PackageManager/install_with_manager.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager/security_scanner.zigsrc/install/PackageManager/install_with_manager.zig
🧠 Learnings (3)
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
src/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
src/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to **/*.zig : In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
Applied to files:
src/install/PackageManager/install_with_manager.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (3)
src/install/PackageManager/install_with_manager.zig (1)
725-744: Nice extraction: getWorkspaceFilters usage is clean and readable.Passing the owned slice through both hoisted/isolated paths looks good.
Also applies to: 746-752
src/install/PackageManager/security_scanner.zig (2)
219-281: Advisory printing looks solid.Clear formatting, path ancestry is helpful. No changes suggested.
48-105: Partial install flow: good structure, one follow-up.Flow is tidy. Same note as above: ensure workspace_filters elements don’t need per-item deinit.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/install/PackageManager/security_scanner.zig (1)
641-647: Fix JS injection: JSON-escape the scanner module string before splicing.Directly appending
security_scannerinto JS can break parsing or enable injection if it contains quotes, backslashes, or special chars. Usebun.fmt.formatJSONStringUTF8to emit a valid JS string literal.- try code.appendSlice(security_scanner); + const scanner_js = bun.fmt.formatJSONStringUTF8(security_scanner, .{}); + try code.appendSlice(scanner_js);
🧹 Nitpick comments (13)
src/install/PackageManager/security_scanner.zig (13)
238-249: Fix “direct dependency” detection in path printing.With current collector, direct deps have
pkg_path.len == 2(root + dep), so the “(direct dependency)” branch never hits. Hide the root and show the label for len <= 2.- if (advisory.pkg_path) |pkg_path| { - if (pkg_path.len > 1) { + if (advisory.pkg_path) |pkg_path| { + if (pkg_path.len > 2) { Output.pretty(" <d>via ", .{}); - for (pkg_path[0 .. pkg_path.len - 1], 0..) |ancestor_id, idx| { + // skip root (index 0) + for (pkg_path[1 .. pkg_path.len - 1], 0..) |ancestor_id, idx| { if (idx > 0) Output.pretty(" › ", .{}); const ancestor_name = pkg_names[ancestor_id].slice(string_buf); Output.pretty("{s}", .{ancestor_name}); } Output.pretty(" › <red>{s}<r>\n", .{advisory.package}); } else { Output.pretty(" <d>(direct dependency)<r>\n", .{}); } }
306-333: Simplify CR handling; currentand falseis confusing.The
'\r'arm returnsfalseregardless; make it explicit and discard the next byte if present.- '\r' => blk: { - const next_byte = reader.readByte() catch { - break :blk false; - }; - break :blk next_byte == '\n' and false; - }, + '\r' => blk: { + _ = reader.readByte() catch {}; // optionally consume '\n' + break :blk false; + },
748-757: Optionally capture stderr when suppressing JS errors.You set
.stderr = .inheritand also allocatestderr_data, but never wire it. To honorsuppress_error_output, consider piping stderr when suppression is enabled so errors aren’t emitted to the user, while still retaining them instderr_datafor diagnostics.- const spawn_options = bun.spawn.SpawnOptions{ + const spawn_options = bun.spawn.SpawnOptions{ .stdout = .inherit, - .stderr = .inherit, + .stderr = if (this.manager.options.log_level != .verbose) .pipe else .inherit, .stdin = .inherit, .cwd = spawn_cwd, .extra_fds = &.{.{ .pipe = pipe_fds[1] }}, .windows = if (Environment.isWindows) .{ .loop = jsc.EventLoopHandle.init(&this.manager.event_loop), }, };If you switch to
.pipe, also hook stderr into the event loop and append tostderr_datausingonStderrChunk.Also applies to: 808-811
219-281: Printing UX: avoid repeating the package name twice.You print the package name in the header and again at the end of the path (“› {s}”). Consider omitting the final repetition for brevity or only printing the ancestry.
600-610: Add a timeout/guard for the scanner subprocess.If the scanner hangs, we wait indefinitely. Consider a soft timeout with a cancel/kill and a clear error message, controlled by log level.
I can draft a small timer using the event loop to kill the process after N seconds unless it has produced IPC.
Also applies to: 686-700
605-610: Prefer scoped debug logger per guidelines.Use
const log = bun.Output.scoped(.SecurityScanner, false);andlog("...", .{})instead of rawprettyErrorlnfor internal diagnostics inattemptSecurityScanWithRetry.Want me to convert the verbose diagnostics to a scoped logger?
1004-1017: Exit-status handling order is good; minor polish.You parse and validate results before enforcing
status.isOK(). That’s fine. Consider attaching exit code to returned errors for easier triage.Also applies to: 1019-1026
48-104: Partial install flow looks solid; add clearer user-facing error on InvalidPackageID.The error path logs are fine. To improve UX, include the configured scanner name when
security_scanner_pkg_id == invalid_package_id.- Output.errGeneric("Cannot perform partial install: security scanner package ID is invalid", .{}); + Output.errGeneric("Cannot perform partial install: security scanner package ID is invalid for '{s}'", .{this.manager.options.security_scanner orelse "(unset)"});
939-953: Edge-case: MODULE_NOT_FOUND after retry.The is-package vs local-path branches are good. Consider also hinting at
bun pm scan(once implemented) orbun add -din the error message for the package case.
531-592: Small optimization (optional): reuse writer buffer capacity.You can pre-allocate
json_bufcapacity withadvisories count * avg item sizeto reduce reallocs. Low impact.
171-175: Scan-all flag logic: confirm uninstall semantics.Currently only
.removetriggers “scan all” after operation. If.uninstallis a distinct subcommand variant, consider including it too.
904-915: Consider enumerating error codes with a shared type.Inline enum via
stringToEnumis fine. If scanner-entry shares a TS enum/union, generating a shared Zig enum may reduce drift.
527-534: Minor: consider pre-sizing json_buf.If
collector.package_paths.count()is known, you canensureTotalCapacityto reduce reallocs.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/cli/scan_command.zig(1 hunks)src/install/PackageManager/security_scanner.zig(8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/cli/scan_command.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/PackageManager/security_scanner.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager/security_scanner.zig
🧠 Learnings (2)
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
src/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
src/install/PackageManager/security_scanner.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (19)
src/install/PackageManager/security_scanner.zig (19)
116-141: Scanner discovery logic looks correct.Root-only dependency scan and workspace guard make sense.
Also applies to: 143-164
527-593: JSON builder: good escaping and structure.Using
formatJSONStringUTF8for string fields and writing a valid JSON array is correct.
837-849: Robust IPC validation; consider freeing/tearing down JSON parser resources if required.Parsing and structural checks are thorough. If
bun.json.parseUTF8allocates internal buffers, ensure we’re not missing a deinit step for the parsed expression/arena.Do we need to deinit/free memory associated with
json_expror its arena? If yes, I can add that with proper allocator ownership.Also applies to: 852-866, 867-882
219-221: Guard is correct; printing is skipped when no advisories.
471-525: Queue processing and path propagation look correct; good use of dedupe.
378-413: Collection phase logic looks sound.Root and update package collection correctly seed the queue.
Also applies to: 415-469
283-342: TTY prompt behavior is clear and conservative.Defaults to cancel on non-tty and on Enter; good.
166-191: Retry flow and messaging are sensible.Installing on MODULE_NOT_FOUND and retrying is the right behavior.
Also applies to: 193-217
698-700: Pass-through counts and duration are correct; allocator stored for deinit is appropriate.
746-753: CWD selection for spawn looks right.Running in
top_level_diravoids CWD drift. Good.
600-603: Wrapper function is clean.
672-685: Resource cleanup is comprehensive.Freeing
code,json_data, and destroying the subprocess is correct.
717-783: Spawn error handling paths return precise errors.Looks good.
1009-1010: Good separation: parse advisories separately from transport.
1030-1037: Counting advisories by level is straightforward.
621-631: Collector lifecycle is correct.
init/deinitbracketing and processing order are safe.
599-599: Build embedding note: ensure scanner-entry.ts is listed in JavaScriptSources.txt.Just a reminder to avoid build flakes.
905-953: isPackagePath correctly distinguishes npm names and file paths
It returns true for non-absolute paths that don’t start with “./” or “../” (and false for absolute or explicit relative paths), so the branch logic is valid.
894-909: Free strings returned by asString to avoid leaks
Insertdefer this.manager.allocator.free(...)immediately after eachasString(this.manager.allocator)call—fortype_str,code_strand everymsg_strin the two error‐handling branches (around lines 894–909 and 955–969). Confirm whetherasStringreturns a borrowed slice (no free needed) or an allocated buffer.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
src/install/PackageManager/security_scanner.zig (2)
634-639: Escape the embedded scanner module to prevent JS injection/breakage.
security_scanneris spliced into JS without escaping. If it contains quotes, backslashes, newlines, or hyphens, the generated script can break or be exploitable. Serialize it as a JS string literal first.- if (std.mem.indexOf(u8, temp_source, scanner_placeholder)) |index| { - try code.appendSlice(temp_source[0..index]); - try code.appendSlice(security_scanner); - try code.appendSlice(temp_source[index + scanner_placeholder.len ..]); - temp_source = code.items; - } + if (std.mem.indexOf(u8, temp_source, scanner_placeholder)) |index| { + try code.appendSlice(temp_source[0..index]); + const escaped = try std.fmt.allocPrint(manager.allocator, "{}", .{bun.fmt.formatJSONStringUTF8(security_scanner, .{})}); + defer manager.allocator.free(escaped); + try code.appendSlice(escaped); + try code.appendSlice(temp_source[index + scanner_placeholder.len ..]); + temp_source = code.items; + }
1062-1072: Stop leaking temporaries in advisory parsing; add errdefers for safety.Free the temps returned by
asString, and useerrdeferon dupes so early returns don’t leak.- const name_str_temp = name_expr.asString(manager.allocator) orelse { + const name_str_temp = name_expr.asString(manager.allocator) orelse { Output.errGeneric("Security advisory at index {d} 'package' field must be a string", .{i}); return error.InvalidPackageField; }; + defer manager.allocator.free(name_str_temp); if (name_str_temp.len == 0) { Output.errGeneric("Security advisory at index {d} 'package' field cannot be empty", .{i}); return error.EmptyPackageField; } // Duplicate the string since asString returns temporary memory - const name_str = try manager.allocator.dupe(u8, name_str_temp); + const name_str = try manager.allocator.dupe(u8, name_str_temp); + errdefer manager.allocator.free(name_str); @@ - if (desc_expr.asString(manager.allocator)) |str| { - // Duplicate the string since asString returns temporary memory - break :blk try manager.allocator.dupe(u8, str); - } + if (desc_expr.asString(manager.allocator)) |str| { + defer manager.allocator.free(str); + const duped = try manager.allocator.dupe(u8, str); + errdefer manager.allocator.free(duped); + break :blk duped; + } @@ - if (url_expr.asString(manager.allocator)) |str| { - // Duplicate the string since asString returns temporary memory - break :blk try manager.allocator.dupe(u8, str); - } + if (url_expr.asString(manager.allocator)) |str| { + defer manager.allocator.free(str); + const duped = try manager.allocator.dupe(u8, str); + errdefer manager.allocator.free(duped); + break :blk duped; + } @@ - const level_str = level_expr.asString(manager.allocator) orelse { + const level_str = level_expr.asString(manager.allocator) orelse { Output.errGeneric("Security advisory at index {d} 'level' field must be a string", .{i}); return error.InvalidLevelField; }; + defer manager.allocator.free(level_str);Also applies to: 1074-1077, 1084-1087, 1097-1104
🧹 Nitpick comments (4)
src/install/PackageManager/security_scanner.zig (4)
219-281: Consider surfacing when advisory ancestry (pkg_path) is unknown.When
pkg_pathis null, nothing is printed about provenance. A short hint like “(path unavailable)” helps users understand why ancestry isn’t shown.
292-341: Simplify CR/LF handling in prompt; current CR branch always resolves to false.
break :blk next_byte == '\n' and false;is always false. Simplify and keep behavior unchanged.- '\r' => blk: { - const next_byte = reader.readByte() catch { - break :blk false; - }; - break :blk next_byte == '\n' and false; - }, + '\r' => false,
671-688: Add a timeout to avoid hangs when the scanner stalls.
sleepUntilwaits until exit with no deadline. Consider a configurable timeout (e.g., bunfig option) and kill the subprocess if exceeded, surfacing a clear error.I can propose a minimal timeout wrapper aligned with existing event loop utilities if you share the preferred API (e.g., sleepUntilWithTimeout).
525-586: Minor: JSON building could use a JSON writer to avoid manual commas.Current approach is fine; using a JSON writer would simplify commas/quoting and reduce chances of drift.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/cli/scan_command.zig(1 hunks)src/install/PackageManager/security_scanner.zig(8 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/cli/scan_command.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/PackageManager/security_scanner.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager/security_scanner.zig
🧠 Learnings (3)
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to **/*.zig : In Zig code, manage memory carefully: use the correct allocator and defer for cleanup
Applied to files:
src/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
src/install/PackageManager/security_scanner.zig
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
src/install/PackageManager/security_scanner.zig
🔇 Additional comments (1)
src/install/PackageManager/security_scanner.zig (1)
721-733: I’ve inquired how stderr is configured in the spawn options; awaiting output to confirm if it’s set to.inheritor.pipe.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (2)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
284-286: Fix no-op assertion for npm.bunfigonly; assert non-execution and helpful error text.The current expect(...).toContain("") never fails. Ensure we both (a) confirm the scanner didn’t run and (b) surfaced a useful error.
- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + expect(errAndOut).not.toContain("SCANNER_RAN"); + expect(errAndOut).toMatch(/(Security scanner|Could not (resolve|load)|Unknown scanner)/i); + }
427-486: Gate the full matrix behind an env flag to stop CI timeouts; run a lean smoke set by default.540 cases is overkill for every CI run and is timing out across platforms. Keep the exhaustive suite opt-in.
describe("Security Scanner Matrix Tests", () => { let i = 0; - describe.each(["install", "update", "add", "remove", "uninstall"] as const)("bun %s", command => { - describe.each([ - { args: [], name: "no args" }, - { args: ["is-even"], name: "is-even" }, - { args: ["left-pad", "is-even"], name: "left-pad,is-even" }, - ])("$name", ({ args }) => { - describe.each([true, false] as const)("(node_modules: %p)", hasExistingNodeModules => { - describe.each(["hoisted", "isolated"] as const)("--linker=%s", linker => { - describe.each(["local", "npm", "npm.bunfigonly"] as const)("(scanner: %s)", scannerType => { - describe.each([true, false] as const)("(bun.lock exists: %p)", hasLockfile => { - describe.each(["none", "warn", "fatal"] as const)("(advisories: %s)", scannerReturns => { + const RUN_ALL = process.env.SCANNER_MATRIX_ALL === "1"; + const COMMANDS = (RUN_ALL ? ["install", "update", "add", "remove", "uninstall"] : ["install", "update"]) as const; + const ARGSETS = (RUN_ALL + ? [ + { args: [], name: "no args" }, + { args: ["is-even"], name: "is-even" }, + { args: ["left-pad", "is-even"], name: "left-pad,is-even" }, + ] + : [ + { args: [], name: "no args" }, + { args: ["is-even"], name: "is-even" }, + ]) as const; + const NM_STATES = (RUN_ALL ? [true, false] : [false]) as const; + const LINKERS = (RUN_ALL ? ["hoisted", "isolated"] : ["hoisted"]) as const; + const SCANNERS = (RUN_ALL ? ["local", "npm", "npm.bunfigonly"] : ["local", "npm"]) as const; + const LOCKFILES = (RUN_ALL ? [true, false] : [false]) as const; + const RETURNS = (RUN_ALL ? ["none", "warn", "fatal"] : ["none", "fatal"]) as const; + + describe.each(COMMANDS)("bun %s", command => { + describe.each(ARGSETS)("$name", ({ args }) => { + describe.each(NM_STATES)("(node_modules: %p)", hasExistingNodeModules => { + describe.each(LINKERS as readonly typeof LINKERS[number][])("--linker=%s", linker => { + describe.each(SCANNERS as readonly typeof SCANNERS[number][])("(scanner: %s)", scannerType => { + describe.each(LOCKFILES)("(bun.lock exists: %p)", hasLockfile => { + describe.each(RETURNS as readonly typeof RETURNS[number][])("(advisories: %s)", scannerReturns => { if ((command === "add" || command === "uninstall" || command === "remove") && args.length === 0) { // TODO(@alii): Test this case: // - Exit code 1 // - No changes to disk // - Scanner does not run return; }
🧹 Nitpick comments (3)
test/cli/install/bun-security-scanner-matrix.test.ts (3)
33-35: Rename typo: scannerSyncronouslyThrows → scannerSynchronouslyThrows.Spelling nit; avoids confusion and future search misses.
interface SecurityScannerTestOptions { @@ - scannerSyncronouslyThrows: boolean; + scannerSynchronouslyThrows: boolean; @@ - scannerSyncronouslyThrows, + scannerSynchronouslyThrows, @@ - ${scannerSyncronouslyThrows ? "throw new Error('Scanner error!');" : ""} + ${scannerSynchronouslyThrows ? "throw new Error('Scanner error!');" : ""} @@ - if (scannerType !== "npm.bunfigonly" && !scannerSyncronouslyThrows) { + if (scannerType !== "npm.bunfigonly" && !scannerSynchronouslyThrows) { @@ - // TODO(@alii): Test this case - scannerSyncronouslyThrows: false, + // TODO(@alii): Test this case + scannerSynchronouslyThrows: false,Also applies to: 64-65, 76-76, 288-288, 475-477
366-369: Typo in comment (“expext”).Small fix.
- // but, if we expext the scanner to report failure then we should ONLY see the scanner tarball requested, no others + // but, if we expect the scanner to report failure then we should ONLY see the scanner tarball requested, no others
221-229: Optional: dispose spawned process withusingto ensure prompt cleanup (if supported).Can help avoid lingering FDs in CI.
- const proc = Bun.spawn({ + await using proc = Bun.spawn({ cmd, cwd: dir, stdout: "pipe", stderr: "pipe", stdin: "pipe", env: bunEnv, });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
test/cli/install/bun-security-scanner-matrix.test.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Place tests in test/ and ensure filenames end with .test.ts or .test.tsx
Always use port: 0 in tests; never hardcode port numbers or use custom random-port functions
Prefer snapshot tests using normalizeBunSnapshot(...).toMatchInlineSnapshot(...) over exact string comparisons
Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Put CLI command tests under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Format JavaScript/TypeScript with Prettier (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**/*.test.ts
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.ts: Use bun:test in files that end in *.test.ts
Prefer async/await over callbacks in tests
For single-callback flows in tests, use Promise.withResolvers()
Do not set timeouts on tests; rely on Bun’s built-in timeouts
Use tempDirWithFiles from harness to create temporary directories/files in tests
Organize tests with describe blocks
Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Avoid flaky tests: never wait for arbitrary time; wait for conditions to be met
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/{**/*.test.ts,**/*-fixture.ts}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/{**/*.test.ts,**/*-fixture.ts}: When spawning Bun processes, use bunExe() and bunEnv from harness
Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Never hardcode port numbers; use port: 0 to get a random port
Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Run bun run zig:check-all when making platform-specific changes to ensure cross-platform compilation
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/js/bun/**/*.test.{ts,tsx} : Put Bun-specific API tests under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Use bun:test in files that end in *.test.ts
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Explicitly assert client console logs with c.expectMessage; unasserted logs should not appear
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
🧬 Code graph analysis (1)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
test/harness.ts (1)
tempDirWithFiles(258-265)test/cli/install/simple-dummy-registry.ts (4)
getRegistry(168-170)SimpleRegistry(6-151)startRegistry(155-159)stopRegistry(161-166)
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (5)
test/cli/install/bun-security-scanner-matrix.test.ts (5)
439-504: Consider reducing test matrix size for faster CI runs.The current matrix generates 540 test cases (5×3×2×2×3×3), which may significantly slow down CI. Consider running a representative subset by default and the full matrix only when needed.
+const RUN_FULL_MATRIX = process.env.SCANNER_MATRIX_ALL === "1"; + describe("Security Scanner Matrix Tests", () => { let i = 0; - describe.each(["install", "update", "add", "remove", "uninstall"] as const)("bun %s", command => { + const commands = RUN_FULL_MATRIX + ? ["install", "update", "add", "remove", "uninstall"] as const + : ["install", "update"] as const; + + describe.each(commands)("bun %s", command => { describe.each([ { args: [], name: "no args" }, { args: ["is-even"], name: "is-even" }, - { args: ["left-pad", "is-even"], name: "left-pad,is-even" }, + ...(RUN_FULL_MATRIX ? [{ args: ["left-pad", "is-even"], name: "left-pad,is-even" }] : []), ])("$name", ({ args }) => { describe.each([true, false] as const)("(node_modules: %p)", hasExistingNodeModules => { describe.each(["hoisted", "isolated"] as const)("--linker=%s", linker => { - describe.each(["local", "npm", "npm.bunfigonly"] as const)("(scanner: %s)", scannerType => { + const scannerTypes = RUN_FULL_MATRIX + ? ["local", "npm", "npm.bunfigonly"] as const + : ["local", "npm"] as const; + + describe.each(scannerTypes)("(scanner: %s)", scannerType => { describe.each([true, false] as const)("(bun.lock exists: %p)", hasLockfile => { - describe.each(["none", "warn", "fatal"] as const)("(advisories: %s)", scannerReturns => { + const returns = RUN_FULL_MATRIX + ? ["none", "warn", "fatal"] as const + : ["none", "fatal"] as const; + + describe.each(returns)("(advisories: %s)", scannerReturns => {
284-286: Thenpm.bunfigonlytest case has a no-op assertion.
expect(errAndOut).toContain("")always passes. This should verify that the scanner wasn't loaded and an appropriate error message was shown.- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + // Verify the scanner didn't run and an error was shown + expect(errAndOut).not.toContain("SCANNER_RAN"); + expect(errAndOut).toMatch(/(Could not (resolve|load) scanner|Security scanner)/i); + }
232-244: Minimize subprocess output logging in CI to prevent timeouts.The line-by-line output logging can be expensive for large outputs. Consider buffering the output and only displaying it on failure.
+ const VERBOSE = process.env.SCANNER_MATRIX_VERBOSE === "1"; + const write = (chunk: Uint8Array<ArrayBuffer>, stream: NodeJS.WriteStream, decoder: TextDecoder) => { const str = decoder.decode(chunk); errAndOut += str; - const lines = str.split("\n"); - for (const line of lines) { - stream.write(redSubprocessPrefix); - stream.write(" "); - stream.write(line); - stream.write("\n"); - } + if (VERBOSE) { + const lines = str.split("\n"); + for (const line of lines) { + stream.write(redSubprocessPrefix); + stream.write(" "); + stream.write(line); + stream.write("\n"); + } + } };
37-41: ReplaceglobEverythingwith targeted file existence checks for better performance.The current
globEverythingfunction scans the entire directory tree, which is expensive. Since the test only checks for specific files, use targeted file existence checks instead.-async function globEverything(dir: string) { - return await Array.fromAsync( - new Bun.Glob("**/*").scan({ cwd: dir, dot: true, followSymlinks: false, onlyFiles: false }), - ); -} +async function pathExists(path: string): Promise<boolean> { + return await Bun.file(path).exists(); +}Then update the usage at lines 202-205 and 266 accordingly:
- const files = await globEverything(dir); - for (const file of files) { - console.log(` ${file}`); - } + const filesToCheck = ["package.json", "bunfig.toml", "scanner.js", "node_modules", "bun.lock"]; + for (const file of filesToCheck) { + const fullPath = join(dir, file); + if (await pathExists(fullPath)) { + console.log(` ${file}`); + } + }- console.log("Files in test dir:", await globEverything(dir)); + const relevantFiles = ["package.json", "bunfig.toml", "node_modules", "bun.lock"]; + const existingFiles = []; + for (const file of relevantFiles) { + if (await pathExists(join(dir, file))) { + existingFiles.push(file); + } + } + console.log("Files in test dir:", existingFiles);
262-272: Display subprocess output on failure for better debugging.When a test fails due to unexpected exit code, also display the captured output to help with debugging.
if (exitCode !== expectedExitCode) { console.log("Command:", cmd.join(" ")); console.log("Expected exit code:", expectedExitCode, "Got:", exitCode); console.log("Test directory:", dir); - console.log("Files in test dir:", await globEverything(dir)); + const relevantFiles = ["package.json", "bunfig.toml", "node_modules", "bun.lock"]; + const existingFiles = []; + for (const file of relevantFiles) { + if (await Bun.file(join(dir, file)).exists()) { + existingFiles.push(file); + } + } + console.log("Files in test dir:", existingFiles); console.log("Registry:", registryUrl); console.log(); console.log("bunfig:"); console.log(await Bun.file(join(dir, "bunfig.toml")).text()); console.log(); + console.log("----- subprocess output (stderr+stdout) -----"); + console.log(errAndOut); }
🧹 Nitpick comments (2)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
193-219: Reduce console output in CI by gating behind environment variable.The verbose debug output can slow down CI and make logs harder to read. Consider only showing this output when specifically requested or when a test fails.
+ const VERBOSE = process.env.SCANNER_MATRIX_VERBOSE === "1" || process.env.SCANNER_TEST_DEBUG; + - if (process.env.SCANNER_TEST_DEBUG) { + if (VERBOSE) { console.log(`[DEBUG] Test directory: ${dir}`); // ... rest of debug output
469-473: Remove the empty TODO comment or provide more context.The skip for
uninstallcommand has a comment saying it's the same asremove, but this should be clarified or the test should be implemented.if (command === "uninstall") { return test.skip(testName, async () => { - // Same as `remove`, optimising for CI time here + // Skipped: uninstall is functionally identical to remove, + // optimizing CI time by not running duplicate tests }); }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (2)
bun.lockis excluded by!**/*.locktest/cli/install/__snapshots__/bun-security-scanner-matrix.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (1)
test/cli/install/bun-security-scanner-matrix.test.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Place tests in test/ and ensure filenames end with .test.ts or .test.tsx
Always use port: 0 in tests; never hardcode port numbers or use custom random-port functions
Prefer snapshot tests using normalizeBunSnapshot(...).toMatchInlineSnapshot(...) over exact string comparisons
Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Put CLI command tests under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Format JavaScript/TypeScript with Prettier (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**/*.test.ts
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.ts: Use bun:test in files that end in *.test.ts
Prefer async/await over callbacks in tests
For single-callback flows in tests, use Promise.withResolvers()
Do not set timeouts on tests; rely on Bun’s built-in timeouts
Use tempDirWithFiles from harness to create temporary directories/files in tests
Organize tests with describe blocks
Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Avoid flaky tests: never wait for arbitrary time; wait for conditions to be met
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/{**/*.test.ts,**/*-fixture.ts}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/{**/*.test.ts,**/*-fixture.ts}: When spawning Bun processes, use bunExe() and bunEnv from harness
Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Never hardcode port numbers; use port: 0 to get a random port
Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
🧠 Learnings (12)
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/js/bun/**/*.test.{ts,tsx} : Put Bun-specific API tests under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Explicitly assert client console logs with c.expectMessage; unasserted logs should not appear
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Do not use node:fs APIs in tests; mutate files via dev.write, dev.patch, and dev.delete
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/dev/ecosystem.test.ts : ecosystem.test.ts should focus on concrete library integration bugs rather than whole-package coverage
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
🧬 Code graph analysis (1)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
test/harness.ts (2)
registryUrl(1630-1632)tempDirWithFiles(258-265)test/cli/install/simple-dummy-registry.ts (4)
getRegistry(168-170)SimpleRegistry(6-151)startRegistry(155-159)stopRegistry(161-166)
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
156-159: Fail fast on initial install errors.If the bootstrap install fails, subsequent rm() calls may throw and the test continues in an invalid state. Capture result and assert exit code.
- console.log(redShellPrefix, `${bunExe()} install`); - await $`${bunExe()} install`.cwd(dir).env(bunEnv); + console.log(redShellPrefix, `${bunExe()} install`); + const init = await $`${bunExe()} install`.cwd(dir).env(bunEnv).nothrow(); + if (init.exitCode !== 0) { + throw new Error(`Initial install failed (${init.exitCode})\nstdout:\n${init.stdout}\nstderr:\n${init.stderr}`); + }
284-286: Fix no-op assertion for bunfig-only scanner.This never asserts anything. Ensure the scanner didn’t run and a helpful error surfaced.
- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + expect(errAndOut).not.toMatch(/SCANNER_RAN/); + expect(errAndOut).toMatch(/(Security scanner|Could not (resolve|load) scanner)/i); + }
🧹 Nitpick comments (8)
test/cli/install/bun-security-scanner-matrix.test.ts (8)
175-178: Quiet default logging; gate debug prints.Unconditional logs bloat CI. Gate behind a verbose flag.
- console.log(redDebugPrefix, "SETUP DONE"); - console.log("-------------------------------- THE REAL TEST IS ABOUT TO HAPPEN --------------------------------"); - console.log(redShellPrefix, cmd.join(" ")); + const VERBOSE = process.env.SCANNER_MATRIX_VERBOSE === "1"; + if (VERBOSE) { + console.log(redDebugPrefix, "SETUP DONE"); + console.log("-------------------------------- THE REAL TEST IS ABOUT TO HAPPEN --------------------------------"); + console.log(redShellPrefix, cmd.join(" ")); + }
232-257: Buffer subprocess output; print only on failure or when verbose.Reduce spam; still retain output for failures.
- const write = (chunk: Uint8Array<ArrayBuffer>, stream: NodeJS.WriteStream, decoder: TextDecoder) => { + const write = (chunk: Uint8Array<ArrayBuffer>, stream: NodeJS.WriteStream, decoder: TextDecoder) => { const str = decoder.decode(chunk); errAndOut += str; - const lines = str.split("\n"); - for (const line of lines) { - stream.write(redSubprocessPrefix); - stream.write(" "); - stream.write(line); - stream.write("\n"); - } + if (VERBOSE) { + const lines = str.split("\n"); + for (const line of lines) { + stream.write(redSubprocessPrefix + " " + line + "\n"); + } + } }; @@ const stdoutWriter = new WritableStream<Uint8Array<ArrayBuffer>>({ - write: chunk => write(chunk, process.stdout, outDecoder), - close: () => void process.stdout.write(outDecoder.decode()), + write: chunk => write(chunk, process.stdout, outDecoder), + close: () => { + if (VERBOSE) process.stdout.write(outDecoder.decode()); + }, }); @@ const stderrWriter = new WritableStream<Uint8Array<ArrayBuffer>>({ - write: chunk => write(chunk, process.stderr, errDecoder), - close: () => void process.stderr.write(errDecoder.decode()), + write: chunk => write(chunk, process.stderr, errDecoder), + close: () => { + if (VERBOSE) process.stderr.write(errDecoder.decode()); + }, });
262-272: On failure, dump the buffered subprocess output.Helps diagnostics when VERBOSE is off.
if (exitCode !== expectedExitCode) { console.log("Command:", cmd.join(" ")); console.log("Expected exit code:", expectedExitCode, "Got:", exitCode); console.log("Test directory:", dir); console.log("Files in test dir:", await globEverything(dir)); console.log("Registry:", registryUrl); console.log(); console.log("bunfig:"); console.log(await Bun.file(join(dir, "bunfig.toml")).text()); console.log(); + console.log("----- subprocess output (stderr+stdout) -----"); + console.log(errAndOut); }
279-282: Make partial-install message checks less brittle.CLI strings can change; prefer regex or snapshot.
- expect(errAndOut).toContain("Attempting to install security scanner from npm"); - expect(errAndOut).toContain("Security scanner installed successfully"); + expect(errAndOut).toMatch(/Attempting to install .*security scanner.* from npm/i); + expect(errAndOut).toMatch(/security scanner .*installed successfully/i);
379-389: Typo in comment: “expext” → “expect”.- // but, if we expext the scanner to report failure then we should ONLY see the scanner tarball requested, no others + // but, if we expect the scanner to report failure then we should ONLY see the scanner tarball requested, no others
33-35: Rename: scannerSyncronouslyThrows → scannerSynchronouslyThrows.Fix spelling for clarity; update interface, destructure, usage, and call site.
- scannerSyncronouslyThrows: boolean; + scannerSynchronouslyThrows: boolean;- scannerSyncronouslyThrows, + scannerSynchronouslyThrows,- ${scannerSyncronouslyThrows ? "throw new Error('Scanner error!');" : ""} + ${scannerSynchronouslyThrows ? "throw new Error('Scanner error!');" : ""}- scannerSyncronouslyThrows: false, + scannerSynchronouslyThrows: false,Also applies to: 65-65, 76-76, 493-495
439-504: Consider gating the full matrix to keep CI fast.540 cases is heavy. Run a representative subset by default; enable full matrix with SCANNER_MATRIX_ALL=1.
- describe.each(["install", "update", "add", "remove", "uninstall"] as const)("bun %s", command => { + const RUN_ALL = process.env.SCANNER_MATRIX_ALL === "1"; + const commands = RUN_ALL ? (["install","update","add","remove","uninstall"] as const) : (["install","update"] as const); + const advisoryLevels = RUN_ALL ? (["none","warn","fatal"] as const) : (["none","fatal"] as const); + describe.each(commands)("bun %s", command => { @@ - describe.each(["none", "warn", "fatal"] as const)("(advisories: %s)", scannerReturns => { + describe.each(advisoryLevels)("(advisories: %s)", scannerReturns => {
193-219: Avoid process.exit in tests.This can terminate the entire suite. Throw instead so only this test aborts.
- if (process.env.SCANNER_TEST_DEBUG === "before") { - process.exit(1); - } + if (process.env.SCANNER_TEST_DEBUG === "before") { + throw new Error("DEBUG break (before): inspect the printed directory and command above."); + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
cmake/sources/ZigSources.txt(1 hunks)src/resolver/resolver.zig(1 hunks)test/cli/install/bun-security-scanner-matrix.test.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- cmake/sources/ZigSources.txt
- src/resolver/resolver.zig
🧰 Additional context used
📓 Path-based instructions (8)
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Place tests in test/ and ensure filenames end with .test.ts or .test.tsx
Always use port: 0 in tests; never hardcode port numbers or use custom random-port functions
Prefer snapshot tests using normalizeBunSnapshot(...).toMatchInlineSnapshot(...) over exact string comparisons
Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Put CLI command tests under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Format JavaScript/TypeScript with Prettier (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**/*.test.ts
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.ts: Use bun:test in files that end in *.test.ts
Prefer async/await over callbacks in tests
For single-callback flows in tests, use Promise.withResolvers()
Do not set timeouts on tests; rely on Bun’s built-in timeouts
Use tempDirWithFiles from harness to create temporary directories/files in tests
Organize tests with describe blocks
Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Avoid flaky tests: never wait for arbitrary time; wait for conditions to be met
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/{**/*.test.ts,**/*-fixture.ts}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/{**/*.test.ts,**/*-fixture.ts}: When spawning Bun processes, use bunExe() and bunEnv from harness
Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Never hardcode port numbers; use port: 0 to get a random port
Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix.test.ts
🧠 Learnings (18)
📓 Common learnings
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/js/bun/**/*.test.{ts,tsx} : Put Bun-specific API tests under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Use bun:test in files that end in *.test.ts
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:05:37.983Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:37.983Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Explicitly assert client console logs with c.expectMessage; unasserted logs should not appear
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/**/*.{js,ts} : Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/**/*.test.ts : Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Do not use node:fs APIs in tests; mutate files via dev.write, dev.patch, and dev.delete
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:07:13.612Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.612Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:09:39.087Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.087Z
Learning: Applies to test/bake/dev/ecosystem.test.ts : ecosystem.test.ts should focus on concrete library integration bugs rather than whole-package coverage
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: For Node.js compatibility bugs, validate expected behavior in Node.js first, then confirm failure on Bun canary
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
📚 Learning: 2025-08-30T00:12:56.792Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.792Z
Learning: Applies to test/cli/**/*.{js,ts} : Place CLI command tests (e.g., bun install, bun init) under test/cli/
Applied to files:
test/cli/install/bun-security-scanner-matrix.test.ts
🧬 Code graph analysis (1)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
test/harness.ts (1)
tempDirWithFiles(258-265)test/cli/install/simple-dummy-registry.ts (4)
getRegistry(168-170)SimpleRegistry(6-151)startRegistry(155-159)stopRegistry(161-166)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (2)
test/cli/install/bun-security-scanner-matrix.test.ts (2)
221-229: Good: usingawait usingforBun.spawn()ensures cleanup.
300-372: Good: targeted existence checks over full-tree globs.Using Bun.file(...).exists() avoids expensive globs and reduces flakiness.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
test/cli/install/bun-security-scanner-matrix-runner.ts (5)
41-41: Consider making DEBUG environment variable name more specificThe environment variable name
SCANNER_TEST_DEBUGcould be more specific to avoid potential conflicts. Consider prefixing it withBUN_.-const DO_TEST_DEBUG = process.env.SCANNER_TEST_DEBUG === "true"; +const DO_TEST_DEBUG = process.env.BUN_SCANNER_TEST_DEBUG === "true";
163-165: Inefficient conditional checkThe condition
hasExistingNodeModules || hasLockfileis checked twice - once to setshouldDoInitialInstalland immediately after in the if statement. Simplify by using the variable.const shouldDoInitialInstall = hasExistingNodeModules || hasLockfile; - if (hasExistingNodeModules || hasLockfile) { + if (shouldDoInitialInstall) { if (DO_TEST_DEBUG) console.log(redShellPrefix, `${bunExe()} install`); await runBunInstall(bunEnv, dir); }
464-470: TODO comments need trackingMultiple TODO comments indicate incomplete test coverage. Consider creating GitHub issues to track these items.
Would you like me to help create GitHub issues to track these TODO items for better visibility and follow-up?
480-484: Consider test execution time optimizationSkipping
uninstalltests to save CI time is pragmatic. However, consider running a subset of these tests in a nightly or weekly CI run to ensure coverage.
308-381: Complex nested conditionals could be refactoredThe file existence verification logic has deeply nested conditions that make it hard to follow. Consider extracting helper functions for better readability.
Consider extracting the file existence checks into helper functions:
async function verifyPackageRemoved(dir: string, packageName: string, linker: string) { switch (linker) { case "hoisted": return expect(await Bun.file(join(dir, "node_modules", packageName, "package.json")).exists()).toBe(false); case "isolated": const version = SimpleRegistry.packages[packageName][0]; const path = join(dir, "node_modules", ".bun", `${packageName}@${version}`, "node_modules", packageName, "package.json"); return expect(await Bun.file(path).exists()).toBe(false); } } async function verifyPackageInstalled(dir: string, packageName: string, linker: string) { switch (linker) { case "hoisted": return expect(await Bun.file(join(dir, "node_modules", packageName, "package.json")).exists()).toBe(true); case "isolated": const version = SimpleRegistry.packages[packageName][0]; const path = join(dir, "node_modules", ".bun", `${packageName}@${version}`, "node_modules", packageName, "package.json"); return expect(await Bun.file(path).exists()).toBe(true); } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between cc795073c38f4f7c5208fb688a48c88cc006eb3c and 541364f186f77bc94d85f6e696b7573c7e552959.
⛔ Files ignored due to path filters (3)
test/cli/install/__snapshots__/bun-security-scanner-matrix-runner.ts.snapis excluded by!**/*.snaptest/cli/install/__snapshots__/bun-security-scanner-matrix-with-node-modules.test.ts.snapis excluded by!**/*.snaptest/cli/install/__snapshots__/bun-security-scanner-matrix-without-node-modules.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (5)
test/cli/install/bun-security-scanner-matrix-runner.ts(1 hunks)test/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts(1 hunks)test/cli/install/bun-security-scanner-matrix-without-node-modules.test.ts(1 hunks)test/cli/install/dummy.registry.ts(0 hunks)test/js/bun/test/jest.d.ts(1 hunks)
💤 Files with no reviewable changes (1)
- test/cli/install/dummy.registry.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- test/js/bun/test/jest.d.ts
🧰 Additional context used
📓 Path-based instructions (7)
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Tests must be named with the suffix .test.ts or .test.tsx and live under the test/ directory
In tests, always use port: 0 and never hardcode ports or use custom random-port utilities
Prefer snapshot tests using normalizeBunSnapshot(...) over direct string equality on stdout/stderr
Do not write tests that assert absence of 'panic', 'uncaught exception', or similar strings in output
Avoid shelling out to tools like find or grep in tests; use Bun.Glob and built-in utilities
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
test/cli/**
📄 CodeRabbit inference engine (CLAUDE.md)
Place CLI command tests (install, run, test, etc.) under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (CLAUDE.md)
Run Prettier to format JS/TS files (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
test/**/*.test.ts
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.ts: Name test files*.test.tsand usebun:test
Do not write flaky tests: never wait for arbitrary time; wait for conditions instead
Never hardcode port numbers in tests; useport: 0to get a random port
When spawning Bun in tests, usebunExe()andbunEnvfromharness
Preferasync/awaitin tests; for a single callback, usePromise.withResolvers()
Do not set explicit test timeouts; rely on Bun’s built-in timeouts
UsetempDir/tempDirWithFilesfromharnessfor temporary files and directories in tests
For large/repetitive strings in tests, preferBuffer.alloc(count, fill).toString()over"A".repeat(count)
Import common test utilities fromharness(e.g.,bunExe,bunEnv,tempDirWithFiles,tmpdirSync, platform checks, GC helpers)
In error tests, assert non-zero exit codes for failing processes and usetoThrowfor synchronous errors
Usedescribeblocks for grouping,describe.eachfor parameterized tests, snapshots withtoMatchSnapshot, and lifecycle hooks (beforeAll,beforeEach,afterEach); track resources for cleanup inafterEach
Useusing/await usingwith Bun resources (e.g., Bun.listen/connect/spawn/serve) to ensure cleanup in tests
Files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
🧠 Learnings (17)
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Name test files `*.test.ts` and use `bun:test`
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : When spawning Bun in tests, use `bunExe()` and `bunEnv` from `harness`
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/js/bun/** : Place Bun-specific API tests (http, crypto, ffi, shell, etc.) under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/cli/**/*.{js,ts} : Place CLI command tests (e.g., bun install, bun init) under test/cli/
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shelling out to tools like find or grep in tests; use Bun.Glob and built-in utilities
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Import common test utilities from `harness` (e.g., `bunExe`, `bunEnv`, `tempDirWithFiles`, `tmpdirSync`, platform checks, GC helpers)
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/node/**/*.{js,ts} : Place Node.js module compatibility tests under test/js/node/, separated by module (e.g., test/js/node/assert/)
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Do not use node:fs APIs in tests; mutate files via dev.write, dev.patch, and dev.delete
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Import testing utilities (devTest, prodTest, devAndProductionTest, Dev, Client) from test/bake/bake-harness.ts
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/node/test/** : Vendored Node.js tests under test/js/node/test/ are exceptions and do not follow Bun’s test style
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.tstest/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/bundle.test.ts : bundle.test.ts should contain DevServer-specific bundling tests
Applied to files:
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Do not set explicit test timeouts; rely on Bun’s built-in timeouts
Applied to files:
test/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/plugins.test.ts : plugins.test.ts should contain plugin-related development-mode tests
Applied to files:
test/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Use shared utilities from test/harness.ts where applicable
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
🧬 Code graph analysis (3)
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.ts (1)
test/cli/install/bun-security-scanner-matrix-runner.ts (1)
runSecurityScannerTests(441-514)
test/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts (1)
test/cli/install/bun-security-scanner-matrix-runner.ts (1)
runSecurityScannerTests(441-514)
test/cli/install/bun-security-scanner-matrix-runner.ts (2)
test/harness.ts (2)
tempDirWithFiles(258-265)runBunInstall(1165-1221)test/cli/install/simple-dummy-registry.ts (4)
getRegistry(173-175)SimpleRegistry(6-156)startRegistry(160-164)stopRegistry(166-171)
🔇 Additional comments (5)
test/cli/install/bun-security-scanner-matrix-runner.ts (3)
15-26: Good practice: Referencing GitHub issues for skipped testsNice work documenting why tests are being skipped with links to GitHub issues. This makes it easier to track and resolve these issues later.
225-233: Good use of resource managementExcellent use of
await usingsyntax for automatic cleanup of the spawned process. This ensures proper resource disposal even if the test fails.
75-113: Potential syntax error in scanner code generationThe scanner code template has a syntax error - there's a missing semicolon after the export statement's closing brace.
} return results; } - } + }; }`Likely an incorrect or invalid review comment.
test/cli/install/bun-security-scanner-matrix-with-node-modules.test.ts (1)
1-8: Well-structured test file with clear documentationGood separation of concerns by splitting the matrix tests into with/without node_modules variants. The comment clearly explains the CI time constraints and references the companion test file.
test/cli/install/bun-security-scanner-matrix-without-node-modules.test.ts (1)
1-5: LGTM - Clean test file structureThe test file follows the expected patterns and correctly delegates to the matrix runner with the appropriate parameters.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
test/cli/install/bun-security-scanner-matrix-runner.ts (1)
298-301: Fix incomplete assertion for npm.bunfigonly caseThe expectation
toContain("")is a no-op. Assert a stable failure signal instead (or at minimum non-empty output).Preferred (robust to minor wording changes):
- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + // Should fail when scanner exists only in bunfig.toml and isn't in deps/lockfile + expect(errAndOut).toMatch(/security scanner/i); + expect(errAndOut).toMatch(/(not found|cannot|failed|missing)/i); + }Minimal (fallback):
- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + expect(errAndOut).not.toBe(""); + }
🧹 Nitpick comments (8)
test/cli/install/bun-security-scanner-matrix-runner.ts (8)
44-45: Typo: rename scannerSyncronouslyThrows → scannerSynchronouslyThrowsSpelling nit; keep API consistent in type, destructuring, conditional, and call site.
-interface SecurityScannerTestOptions { - ... - scannerSyncronouslyThrows: boolean; -} +interface SecurityScannerTestOptions { + ... + scannerSynchronouslyThrows: boolean; +} @@ - scannerSyncronouslyThrows, + scannerSynchronouslyThrows, @@ - ${scannerSyncronouslyThrows ? "throw new Error('Scanner error!');" : ""} + ${scannerSynchronouslyThrows ? "throw new Error('Scanner error!');" : ""} @@ - if (scannerType !== "npm.bunfigonly" && !scannerSyncronouslyThrows) { + if (scannerType !== "npm.bunfigonly" && !scannerSynchronouslyThrows) { @@ - scannerSyncronouslyThrows: false, + scannerSynchronouslyThrows: false,Also applies to: 76-77, 88-90, 302-304, 510-512
231-239: Confirm Bun.spawn is async-disposable here
await usingrequires Subprocess to implement Symbol.asyncDispose. If not guaranteed in your target Bun version, switch to try/finally and awaitproc.exited.- await using proc = Bun.spawn({ + const proc = Bun.spawn({ cmd, cwd: dir, stdout: "pipe", stderr: "pipe", stdin: "pipe", env: bunEnv, });Then:
- const exitCode = await proc.exited; + const exitCode = await proc.exited; // in a try/finally if needed to clean upWould you like me to swap this to a try/finally pattern for broader compatibility?
277-287: On mismatch, also print subprocess outputInclude combined stdout/stderr to speed up debugging CI flakes.
if (exitCode !== expectedExitCode) { console.log("Command:", cmd.join(" ")); console.log("Expected exit code:", expectedExitCode, "Got:", exitCode); console.log("Test directory:", dir); console.log("Files in test dir:", await globEverything(dir)); console.log("Registry:", registryUrl); console.log(); + console.log("stdout+stderr:"); + console.log(errAndOut); console.log("bunfig:"); console.log(await Bun.file(join(dir, "bunfig.toml")).text()); console.log(); }
178-181: Make rm of bun.lock resilientIf bun.lock wasn’t created (unexpected failure),
rm()will throw. Addforce: true.- await rm(join(dir, "bun.lock")); + await rm(join(dir, "bun.lock"), { force: true });
19-32: Avoid numeric test IDs for skip logic; derive deterministic keys from matrixNumeric IDs are brittle—any matrix change shifts numbers and invalidates
TESTS_TO_SKIP. Use a signature from parameters to keep skips stable over time.Example:
-const TESTS_TO_SKIP: Set<string> = new Set<TestName>([ - "0289 (without modules)", ... -]); +const TESTS_TO_SKIP = new Set<string>([ + // Example keys: + // "remove|is-even|hoisted|npm|no-lockfile|none|without-modules", + // "remove|left-pad,is-even|isolated|npm|no-lockfile|none|without-modules", +]); @@ -const testName = getTestName(String(++i).padStart(4, "0"), hasExistingNodeModules); +const key = [ + command, + args.join(","), + linker, + scannerType, + hasLockfile ? "lockfile" : "no-lockfile", + scannerReturns, + hasExistingNodeModules ? "with-modules" : "without-modules", +].join("|"); +const testName = getTestName(String(++i).padStart(4, "0"), hasExistingNodeModules); @@ -if (TESTS_TO_SKIP.has(testName)) { +if (TESTS_TO_SKIP.has(key)) {Keep the numeric
testNamefor readability if you like; usekeysolely for skipping.Also applies to: 478-485
448-451: Use the scoped jest APIs from bunTest to avoid mixing globalsDestructure
test(and optionallyexpect) frombunTestfor consistency and isolation.-const { describe, beforeAll, afterAll } = bunTest; +const { describe, beforeAll, afterAll, test /*, expect */ } = bunTest;Also applies to: 481-490
470-476: Fill TODOs: no-args paths and synchronous throw modeTwo valuable cases are stubbed:
- add/remove/uninstall with no args should error without side effects and without invoking the scanner.
- scannerSynchronouslyThrows: true (throw inside scan()).
I can wire both into the matrix and add assertions. Want me to push a patch?
Also applies to: 510-512
291-296: Guard the npm scanner bootstrap assertions with more precise conditionsIf CLI wording shifts, these strict substrings may flake. Consider matching with a regex or asserting for a stable marker (e.g., “security scanner” + “installed”).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between 541364f186f77bc94d85f6e696b7573c7e552959 and 590b909129b48cdb10d98cede5ef1594e4e3e0cc.
⛔ Files ignored due to path filters (2)
test/cli/install/__snapshots__/bun-security-scanner-matrix-with-node-modules.test.ts.snapis excluded by!**/*.snaptest/cli/install/__snapshots__/bun-security-scanner-matrix-without-node-modules.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (1)
test/cli/install/bun-security-scanner-matrix-runner.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
test/cli/**
📄 CodeRabbit inference engine (CLAUDE.md)
Place CLI command tests (install, run, test, etc.) under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (CLAUDE.md)
Run Prettier to format JS/TS files (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
🧠 Learnings (10)
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : When spawning Bun in tests, use `bunExe()` and `bunEnv` from `harness`
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/js/bun/** : Place Bun-specific API tests (http, crypto, ffi, shell, etc.) under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Name test files `*.test.ts` and use `bun:test`
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Explicitly assert client console logs with c.expectMessage; unasserted logs should not appear
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Do not write tests that assert absence of 'panic', 'uncaught exception', or similar strings in output
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shelling out to tools like find or grep in tests; use Bun.Glob and built-in utilities
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
🧬 Code graph analysis (1)
test/cli/install/bun-security-scanner-matrix-runner.ts (2)
test/harness.ts (3)
registryUrl(1630-1632)tempDirWithFiles(258-265)runBunInstall(1165-1221)test/cli/install/simple-dummy-registry.ts (4)
getRegistry(173-175)SimpleRegistry(6-156)startRegistry(160-164)stopRegistry(166-171)
🔇 Additional comments (1)
test/cli/install/bun-security-scanner-matrix-runner.ts (1)
1-521: Overall: Solid matrix harness and good use of Bun test utilitiesGood coverage across commands/linkers/scanner sources, proper use of bunExe/bunEnv per harness guidelines, and realistic registry assertions. The debug mode is handy.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
test/cli/install/bun-security-scanner-matrix-runner.ts (2)
449-452: Avoid global mutable test counter; use a local counter within the suiteA module/global counter is brittle with parallelism and re-imports.
Apply this diff:
-export function runSecurityScannerTests(selfModuleName: string, hasExistingNodeModules: boolean) { - let i = 0; +export function runSecurityScannerTests(selfModuleName: string, hasExistingNodeModules: boolean) { + let testCounter = 0;- const testName = getTestName(String(++i).padStart(4, "0"), hasExistingNodeModules); + const testName = getTestName(String(++testCounter).padStart(4, "0"), hasExistingNodeModules);Also applies to: 481-482
301-304: Fix the incomplete assertion for npm.bunfigonlyThe current check always passes and provides no signal. Assert a stable error and that the scanner did not run.
Apply this diff:
- if (scannerType === "npm.bunfigonly") { - expect(errAndOut).toContain(""); - } + if (scannerType === "npm.bunfigonly") { + // Scanner specified only in bunfig; should fail to resolve and not execute + expect(errAndOut).toMatch(/error:.*security scanner/i); + expect(errAndOut).not.toContain("SCANNER_RAN"); + }
🧹 Nitpick comments (4)
test/cli/install/bun-security-scanner-matrix-runner.ts (4)
453-454: Use Bun.jest’s scopedtestfor consistencyPrevents reliance on globals and keeps the suite self-contained.
- const { describe, beforeAll, afterAll } = bunTest; + const { test, describe, beforeAll, afterAll } = bunTest;
181-184: Useforce: truewhen removing bun.lock to harden setupAvoids occasional ENOENT if file was not created or already removed.
- await rm(join(dir, "bun.lock")); + await rm(join(dir, "bun.lock"), { force: true });
47-48: Fix typo: Syncronously → SynchronouslyKeeps naming consistent and reduces grep friction.
-interface SecurityScannerTestOptions { +interface SecurityScannerTestOptions { command: "install" | "update" | "add" | "remove" | "uninstall"; args: string[]; hasExistingNodeModules: boolean; linker: "hoisted" | "isolated"; scannerType: "local" | "npm" | "npm.bunfigonly"; scannerReturns: "none" | "warn" | "fatal"; shouldFail: boolean; hasLockfile: boolean; - scannerSyncronouslyThrows: boolean; + scannerSynchronouslyThrows: boolean; }- scannerSyncronouslyThrows, + scannerSynchronouslyThrows,- scannerSyncronouslyThrows: false, + scannerSynchronouslyThrows: false,- if (scannerType !== "npm.bunfigonly" && !scannerSyncronouslyThrows) { + if (scannerType !== "npm.bunfigonly" && !scannerSynchronouslyThrows) {Also applies to: 79-80, 524-524
398-407: Clarify comments to match the resolution logicThe comments contradict the condition; update for accuracy.
- // If there is no lockfile, we will resolve packages - !hasLockfile || - // Unless we are updating - (command === "update" && args.length === 0) || - // Unless there are arguments, but it's chill because one of the arguments is the security - // scanner, so we would expect to be resolving + // We resolve if: + // - there is no lockfile, OR + // - we are updating everything (no args), OR + // - args include the security scanner (so resolving is expected) args.includes("test-security-scanner");
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between 590b909129b48cdb10d98cede5ef1594e4e3e0cc and dd8f473423cb8d55579c235da6f03756e0c8450a.
📒 Files selected for processing (4)
test/cli/install/bun-security-scanner-matrix-runner.ts(1 hunks)test/cli/install/bun-update-security-edge-cases.test.ts(1 hunks)test/cli/install/bun-update-security-simple.test.ts(1 hunks)test/cli/install/generate-scanner-tarballs.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- test/cli/install/bun-update-security-simple.test.ts
- test/cli/install/bun-update-security-edge-cases.test.ts
- test/cli/install/generate-scanner-tarballs.ts
🧰 Additional context used
📓 Path-based instructions (5)
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
test/cli/**
📄 CodeRabbit inference engine (CLAUDE.md)
Place CLI command tests (install, run, test, etc.) under test/cli/
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (CLAUDE.md)
Run Prettier to format JS/TS files (bun run prettier)
Files:
test/cli/install/bun-security-scanner-matrix-runner.ts
🧠 Learnings (12)
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : When spawning Bun in tests, use `bunExe()` and `bunEnv` from `harness`
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/js/bun/** : Place Bun-specific API tests (http, crypto, ffi, shell, etc.) under test/js/bun/
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Name test files `*.test.ts` and use `bun:test`
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Explicitly assert client console logs with c.expectMessage; unasserted logs should not appear
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Do not write tests that assert absence of 'panic', 'uncaught exception', or similar strings in output
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shelling out to tools like find or grep in tests; use Bun.Glob and built-in utilities
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Use shared utilities from test/harness.ts where applicable
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Prefer snapshot tests using normalizeBunSnapshot(...) over direct string equality on stdout/stderr
Applied to files:
test/cli/install/bun-security-scanner-matrix-runner.ts
🧬 Code graph analysis (1)
test/cli/install/bun-security-scanner-matrix-runner.ts (2)
test/harness.ts (3)
registryUrl(1630-1632)tempDirWithFiles(258-265)runBunInstall(1165-1221)test/cli/install/simple-dummy-registry.ts (3)
SimpleRegistry(6-156)startRegistry(160-164)stopRegistry(166-171)
🔇 Additional comments (2)
test/cli/install/bun-security-scanner-matrix-runner.ts (2)
420-446: Snapshot naming looks goodMatrix-specific snapshot keys provide useful grouping by command.
188-242: Good end-to-end execution harnessSpawning with bunExe/bunEnv, piping stdout/stderr, and toggled debug is aligned with harness guidelines.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/install/hoisted_install.zig (1)
7-8: Signature change: plumbedpackages_to_installinto install path — verify all callsites.Ensure every call to
installHoistedPackages(...)now passes a 6th argument (?[]const PackageID), ornull. This was flagged earlier; re-running the check is worthwhile after recent merges.Run:
#!/bin/bash # All callsites of installHoistedPackages rg -nP --type=zig -C2 '\binstallHoistedPackages\s*\('
🧹 Nitpick comments (4)
src/install/hoisted_install.zig (1)
193-194: Skip-prefetch toggle is correct; add a debug breadcrumb.
force_install_skip_prefetch_check = packages_to_install != nullis the right gate for partial installs. Consider a scoped debug log to aid traceability in CI and user bug reports.+const log = bun.Output.scoped(.hoisted_install, false); ... - .force_install_skip_prefetch_check = packages_to_install != null, + .force_install_skip_prefetch_check = packages_to_install != null, + // Debug breadcrumb for partial install path + // log("partial-install path: skip_prefetch_check={}", .{packages_to_install != null});src/install/lockfile/Tree.zig (2)
249-250: Document the intent ofpackages_to_install(root-only subset).Add a short comment clarifying that this slice is used to limit root dependencies (pkg_id at parent_pkg_id == 0) during
.filter.- packages_to_install: if (method == .filter) ?[]const PackageID else void, + /// Optional subset of root package IDs to include when filtering. + /// Only applied at the root (parent_pkg_id == 0). + packages_to_install: if (method == .filter) ?[]const PackageID else void,
497-511: Tighten membership check; avoid O(n*m) scan over the slice.For small slices this is fine; for larger subsets this becomes noticeably quadratic. Use
std.mem.indexOfScalarhere (simple), or precompute aDynamicBitSetUnmanagedonce in the builder (faster).Minimal change:
- if (builder.packages_to_install) |packages_to_install| { - if (parent_pkg_id == 0) { - var found = false; - for (packages_to_install) |package_to_install| { - if (pkg_id == package_to_install) { - found = true; - break; - } - } - - if (!found) { - continue; - } - } - } + if (parent_pkg_id == 0) { + if (builder.packages_to_install) |packages_to_install| { + if (std.mem.indexOfScalar(PackageID, packages_to_install, pkg_id) == null) { + continue; + } + } + }If you’d like, I can follow up with a bitset-backed variant for O(1) membership and add deinit hooks.
src/install/lockfile.zig (1)
891-909: Builder init wirespackages_to_install— consider optional set precomputation.Wiring is correct. If the slice can be large, consider precomputing a membership bitset once here (and deinit it in
Tree.Builder.clean) to speed root filtering.I can draft a small helper to build a
DynamicBitSetUnmanagedkeyed byPackageIDand switch the membership test accordingly. Want me to push that?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
src/install/PackageInstaller.zig(2 hunks)src/install/hoisted_install.zig(2 hunks)src/install/lockfile.zig(4 hunks)src/install/lockfile/Tree.zig(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/install/PackageInstaller.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/hoisted_install.zigsrc/install/lockfile/Tree.zigsrc/install/lockfile.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/hoisted_install.zigsrc/install/lockfile/Tree.zigsrc/install/lockfile.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (3)
src/install/hoisted_install.zig (1)
14-14: LGTM: forwards partial-install slice to filtering.Passing
packages_to_installintolockfile.filter(...)aligns with the new filter semantics. No issues spotted.src/install/lockfile.zig (2)
877-880: Approve code changes
All callsites oflockfile.filterhave been updated to include the newpackages_to_installargument.
869-869: Resolve path: extravoidarg added — compile sanity check
The added{}for the newpackages_to_installparameter in the.resolvablespecialization looks correct. Ensure the singlelockfile.hoist(log, .resolvable, {}, {}, {}, {})invocation compiles cleanly across all targets under Zig’svoidparameter rules.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/install/isolated_install.zig (1)
875-877: Bug:.githubcase accesses.gitfield.Under
.github,pkg_res.value.gitis wrong; use.github.Apply:
- const url = manager.allocGitHubURL(&pkg_res.value.git); + const url = manager.allocGitHubURL(&pkg_res.value.github);
♻️ Duplicate comments (1)
src/install/isolated_install.zig (1)
171-174: Wrong root-node sentinel: this branch never executes.
Store.Node.Iddoesn’t have.root(that’s forStore.Entry.Id). Use the queue entry’s parent to detect root.Apply:
- if (packages_to_install) |packages| { - if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) + if (packages_to_install) |packages| { + if (entry.parent_id == .invalid) { // root node
🧹 Nitpick comments (3)
src/install/isolated_install.zig (3)
180-189: Avoid O(D×P) scan: precompute a membership set forpackages_to_install.Current nested loops scale poorly for large roots and large subsets. Build a
AutoHashMap(PackageID, void)once and do O(1) membership checks.Inside function prologue (outside the shown range):
var to_install: ?std.AutoHashMap(PackageID, void) = null; defer if (to_install) |*m| m.deinit(); if (packages_to_install) |pkgs| { var m = std.AutoHashMap(PackageID, void).init(lockfile.allocator); try m.ensureTotalCapacity(@intCast(pkgs.len)); for (pkgs) |p| m.putAssumeCapacityNoClobber(p, {}); to_install = m; }Then replace the inner loop:
- for (packages) |package_to_install| { - if (package_to_install == pkg_id) { + if (to_install) |m| if (m.contains(pkg_id)) { node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); try node_queue.writeItem(.{ .parent_id = node_id, .dep_id = dep_id, .pkg_id = pkg_id, }); - break; - } - } + }
209-216: Guard invalid resolution in non-partial path.Mirror the partial path’s
invalid_package_idguard to avoid enqueuing unresolved deps.Apply:
const pkg_id = resolutions[dep_id]; const dep = dependencies[dep_id]; + if (pkg_id == invalid_package_id) { + continue; + }
1-1: Scoped logger visibility.Guideline suggests
Output.scoped(.IsolatedInstall, false)for debug logs. Current.visibleis chatty; consider switching unless this scope must always print.-const log = Output.scoped(.IsolatedInstall, .visible); +const log = Output.scoped(.IsolatedInstall, false);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/install/isolated_install.zig(4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/isolated_install.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/isolated_install.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (3)
src/install/isolated_install.zig (3)
9-10: API change: thread-through and documentpackages_to_install.Looks good, but please ensure all call sites are updated and the param is documented (semantics: direct deps at root only, or also transitive?). If transitive is out-of-scope, say so explicitly.
175-183: Respect workspace filters in partial-root path.The non-partial path applies
Tree.isFilteredDependencyOrWorkspace(...), but the partial-root path currently doesn’t. This may ignore user-specified workspace filters. Mirror the same filter here.Apply:
- const pkg_id = resolutions[dep_id]; + const pkg_id = resolutions[dep_id]; + if (Tree.isFilteredDependencyOrWorkspace( + dep_id, + entry.pkg_id, + workspace_filters, + install_root_dependencies, + manager, + lockfile, + )) { + continue; + }
845-846: Add the new boolean parameter to allenqueuePackageForDownloadcalls
Update the calls in src/resolver/resolver.zig (around line 2054) and src/install/PackageInstaller.zig (around line 978) to pass the new boolean flag (e.g.packages_to_install != null). Ensure any Git/GitHub/tarball download paths also supply this flag for parity.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/install/PackageManager.zig (2)
157-157: Wire the new Subcommand.scan through helpers (JSON/workspace) and add a tiny debug trace.Likely desirable for
bun pm scanto support--jsonand workspace filters. Also add a lightweight debug line for visibility.Apply:
@@ pub fn supportsWorkspaceFiltering(this: Subcommand) bool { return switch (this) { .outdated => true, .install => true, .update => true, + .scan => true, // .pack => true, // .add => true, else => false, }; } @@ pub fn supportsJsonOutput(this: Subcommand) bool { return switch (this) { .audit, .pm, .info, + .scan, => true, else => false, }; }Optional trace near the start of
init(...)to help diagnose CLI dispatch:@@ pub fn init( ctx: Command.Context, cli: CommandLineArguments, subcommand: Subcommand, ) !struct { *PackageManager, string } { + const pm_log = bun.Output.scoped(.PackageManagerInit, false); + pm_log("subcommand: {s}", .{@tagName(subcommand)});Verification (skim call sites expecting JSON/workspace behavior):
#!/bin/bash # Ensure scan is handled consistently rg -nP -C2 '\bsupports(JsonOutput|WorkspaceFiltering)\b' rg -nP -C3 '\bSubcommand\.scan\b'
583-586: Alias-safe copy: add a bounds assert; consider removing if redundant.Good call guarding self-aliasing. Two nits:
- Guard capacity to prevent silent truncation on extremely long paths.
- If
cwd_bufisn’t read before Line 774, this early copy may be unnecessary.Apply:
- // Avoid memcpy alias when source and dest are the same - if (cwd_buf[0..].ptr != top_level_dir_no_trailing_slash.ptr) { - bun.copy(u8, cwd_buf[0..top_level_dir_no_trailing_slash.len], top_level_dir_no_trailing_slash); - } + // Avoid memcpy alias when source and dest are the same + std.debug.assert(top_level_dir_no_trailing_slash.len <= cwd_buf.len); + if (cwd_buf[0..].ptr != top_level_dir_no_trailing_slash.ptr) { + bun.copy(u8, cwd_buf[0..top_level_dir_no_trailing_slash.len], top_level_dir_no_trailing_slash); + }To verify redundancy:
#!/bin/bash # Check if cwd_buf is referenced before Line 774 in this file rg -nP 'cwd_buf' -n src/install/PackageManager.zig | awk '$1<774{print}'
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
src/cli/scan_command.zig(1 hunks)src/install/PackageManager.zig(2 hunks)src/install/PackageManager/install_with_manager.zig(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- src/cli/scan_command.zig
- src/install/PackageManager/install_with_manager.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/PackageManager.zig
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
src/install/PackageManager/install_with_manager.zig (2)
569-603: Gate prefetch under the same condition as running the scanner.prefetch_resolved_tarballs is set even when no scan will run. Move it inside the is_subcommand_to_run_scanner block to avoid behavior changes. (Same as earlier note.)
if (manager.options.security_scanner != null) { const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove; if (is_subcommand_to_run_scanner) { if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| { @@ } + // Enable prefetch only when a scan has been attempted + manager.options.do.prefetch_resolved_tarballs = true; } - - manager.options.do.prefetch_resolved_tarballs = true; }
983-1037: Memory ownership bug: returning a slice tied to a local ArrayListUnmanaged.Returning workspace_filters.items without transferring or duplicating ownership risks invalid-free or leaks. Return an owned slice and free the internal list before returning.
pub fn getWorkspaceFilters(manager: *PackageManager, original_cwd: []const u8) !struct { []const WorkspaceFilter, bool, } { - const path_buf = bun.path_buffer_pool.get(); - defer bun.path_buffer_pool.put(path_buf); + const path_buf = bun.path_buffer_pool.get(); + defer bun.path_buffer_pool.put(path_buf); var workspace_filters: std.ArrayListUnmanaged(WorkspaceFilter) = .{}; @@ - return .{ workspace_filters.items, install_root_dependencies }; + // Hand back an owned slice; caller frees it. + const out_filters = try manager.allocator.dupe(WorkspaceFilter, workspace_filters.items); + workspace_filters.deinit(manager.allocator); + return .{ out_filters, install_root_dependencies }; }
🧹 Nitpick comments (1)
src/install/PackageManager/install_with_manager.zig (1)
569-603: Add a scoped debug log around scanner execution.Tiny trace helps triage CI/customer reports when scans gate installs.
- if (is_subcommand_to_run_scanner) { + if (is_subcommand_to_run_scanner) { + const log = bun.Output.scoped(.pm_scan, false); + log("running security scan after resolution (subcommand={s})", .{@tagName(manager.subcommand)});
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/install/PackageManager/install_with_manager.zig(4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager/install_with_manager.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/PackageManager/install_with_manager.zig
🔇 Additional comments (4)
src/install/PackageManager/install_with_manager.zig (4)
740-744: Verify both installers use filters identically.Hoisted and isolated paths now both receive workspace_filters and a trailing null param. Confirm that parameter order and null semantics match their signatures and that partial-install behavior is consistent across both paths.
Also applies to: 746-752
1008-1009: Remove incorrect suggestion aboutPath.pathToPosixBufargument
The function’s signature expects a pointer to a buffer slice, and existing calls (e.g. line 581) use&cwd_buf; using&path_bufhere is consistent and correct.Likely an incorrect or invalid review comment.
725-727: Verify slice ownership returned by getWorkspaceFilters before freeing
Confirm that getWorkspaceFilters was updated to allocate and return an owned slice; if it still returns a view over an internal ArrayListUnmanaged buffer, defer-freeing workspace_filters will lead to an invalid free—either adjust getWorkspaceFilters to return a newly allocated slice or remove the manual free.
569-603: Subcommand enum has no.uninstallvariant—no changes needed.
…tions to prevent memory issues
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/install/isolated_install.zig (4)
175-195: Handle unsupported workspace-scanner case instead of TODOAt the moment we silently fall through when
packages_to_installis set butnode_id != .root. Emit a visible warning (or hard error) so users understand why partial install filtering didn’t apply.Apply:
- if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) + if (node_id == .root) { for (dep_ids_sort_buf.items) |dep_id| { ... } break :queue_deps; - } + } else { + // Scanner should not run as a workspace dependency; ignore per-package filtering. + log("warning: ignoring packages_to_install for non-root node (scanner unsupported as workspace dep)\n", .{}); + }
176-194: Avoid O(n·m) nested loops; precompute a set for membership testsThe inner loop over
packagesis linear for each dep. Convertpackages_to_installto aHashSet(PackageID)once and use O(1) membership checks.Within this hunk:
- for (dep_ids_sort_buf.items) |dep_id| { + for (dep_ids_sort_buf.items) |dep_id| { const pkg_id = resolutions[dep_id]; if (pkg_id == invalid_package_id) { continue; } - - for (packages) |package_to_install| { - if (package_to_install == pkg_id) { + if (packages_to_install_set.contains(pkg_id)) { node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); try node_queue.writeItem(.{ .parent_id = node_id, .dep_id = dep_id, .pkg_id = pkg_id, }); - break; - } - } + } }Outside this hunk (supporting change): initialize the set once near other locals in the
store:block.var packages_to_install_set: ?std.AutoHashMap(PackageID, void) = null; defer if (packages_to_install_set) |*m| m.deinit(); if (packages_to_install) |packages| { var m = std.AutoHashMap(PackageID, void).init(lockfile.allocator); try m.ensureTotalCapacity(@intCast(packages.len)); for (packages) |pid| _ = try m.put(pid, {}); packages_to_install_set = m; }
198-207: Optional: add debug logs when dependencies are filtered outWhen scanning or partially installing, it helps to understand why deps are skipped. Consider logging filter decisions under verbose mode.
- )) { - continue; - } + )) { + if (manager.options.log_level.isVerbose()) { + log("filtered dep {d} for pkg {d}\n", .{ dep_id, entry.pkg_id }); + } + continue; + }
210-227: Nit: assert resolution is valid before usingpkg_idIn the generic path we don’t guard
resolutions[dep_id]againstinvalid_package_idlike we do in the partial-root path. A debug assert helps catch unexpected state without affecting release builds.Apply:
- const pkg_id = resolutions[dep_id]; + const pkg_id = resolutions[dep_id]; + bun.debugAssert(pkg_id != invalid_package_id);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/install/isolated_install.zig(4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/isolated_install.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/isolated_install.zig
🔇 Additional comments (3)
src/install/isolated_install.zig (3)
171-176: Good fix: peer list now cleared even on early block exitAdding
defer peer_dep_ids.clearRetainingCapacity();insidequeue_depsavoids stale peers when breaking early. This addresses the previously raised issue about leftover peers leaking intonext_peer.
9-10: New parameterpackages_to_install: verify all call-sites and semanticsEnsure all invocations of
installIsolatedPackagesnow pass the new?[]const PackageIDargument and thatnullvs. empty slice semantics are intentional (null = full install behavior; empty = install none?). Also validate hoisted/manager entry points are updated consistently.#!/usr/bin/env bash set -euo pipefail # 1) Find all call-sites and show surrounding context rg -nC3 -P '\binstallIsolatedPackages\s*\(' # 2) Confirm definition arity rg -n -P 'pub\s+fn\s+installIsolatedPackages\s*\(' -C2 # 3) Audit related pipeline for param threading rg -n -P '\binstallHoistedPackages\s*\(' -C3 rg -n -P '\bgetWorkspaceFilters\s*\(' -C3
846-847: New flag toenqueuePackageForDownload: confirm intent and propagate if neededPassing
packages_to_install != nulllikely toggles “force install / skip prefetch check” for partial installs. Please confirm the parameter name/semantics and whether similar treatment is needed for.github/.remote_tarballpaths.#!/usr/bin/env bash set -euo pipefail # Inspect definition and param names rg -nP 'fn\s+enqueuePackageForDownload\s*\(' -C5 # Find all call-sites to ensure last-arg usage is consistent with intent rg -nP '\benqueuePackageForDownload\s*\(' -C3 # Check whether non-npm enqueue functions gained analogous flags rg -nP '\benqueueTarballForDownload\s*\(' -C5 rg -nP '\benqueueGitForCheckout\s*\(' -C5
There was a problem hiding this comment.
Actionable comments posted: 4
♻️ Duplicate comments (3)
src/install/isolated_install.zig (1)
171-173: Good fix: peers are always cleared even on early break.The defer avoids stale peers when breaking the block. Matches prior feedback.
src/install/PackageManager/install_with_manager.zig (2)
569-599: Encapsulate the predicate as Subcommand.runsScanner().Keeps logic centralized and consistent with other Subcommand helpers.
- const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove; + const is_subcommand_to_run_scanner = manager.subcommand.runsScanner();Add on Subcommand (separate file):
pub fn runsScanner(self: Subcommand) bool { return self == .add or self == .update or self == .install or self == .remove or self == .uninstall; }
569-599: Prefetch tarballs only when a scan will run.If scanning consumes tarballs, enable prefetch under the same condition to avoid behavior changes for other subcommands.
Please confirm where prefetch_resolved_tarballs is set now. If it moved, ignore; else add:
if (is_subcommand_to_run_scanner) { + manager.options.do.prefetch_resolved_tarballs = true; if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| {Verify whether scanning actually needs prefetch:
#!/bin/bash rg -nP 'prefetch_resolved_tarballs|performSecurityScanAfterResolution' -C2 --type=zig
🧹 Nitpick comments (3)
src/install/isolated_install.zig (2)
174-195: Partial-install root path works; consider faster membership checks.Current O(N*M) nested loop scans packages_to_install for each dep. If packages_to_install can be large, precompute a hash set for O(1) membership.
Example (sketch within function scope before the loop):
+var requested: ?std.AutoHashMap(PackageID, void) = null; +if (packages_to_install) |packages| { + var map = std.AutoHashMap(PackageID, void).init(lockfile.allocator); + try map.ensureTotalCapacity(@intCast(packages.len)); + for (packages) |pid| _ = try map.put(pid, {}); + requested = map; + // ... and use requested.?.contains(pkg_id) below +}Remember to deinit the map.
175-175: Prefer checking root via parent_id rather than node_id sentinel.Use entry.parent_id == .invalid for root to align with surrounding code and avoid depending on a Node.Id .root sentinel.
- if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) + if (entry.parent_id == .invalid) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this)src/install/PackageManager/install_with_manager.zig (1)
1010-1031: Root-deps inference via glob match — edge-case note.The first negated-but-no-match pattern forces install_root_dependencies = false and breaks; if later patterns would match root, they won’t be considered. If order precedence should mirror glob semantics (last match wins), process all patterns and apply last outcome.
- for (workspace_filters.items) |filter| { + for (workspace_filters.items, 0..) |filter, i| { ... - switch (bun.glob.walk.matchImpl(manager.allocator, pattern, path_or_name)) { - .match, .negate_match => install_root_dependencies = true, - .negate_no_match => { install_root_dependencies = false; break; }, - .no_match => {}, - } + const res = bun.glob.walk.matchImpl(manager.allocator, pattern, path_or_name); + if (res == .match or res == .negate_match) install_root_dependencies = true; + if (res == .negate_no_match) install_root_dependencies = false; ... }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
src/install/PackageManager/PackageManagerEnqueue.zig(0 hunks)src/install/PackageManager/install_with_manager.zig(4 hunks)src/install/hoisted_install.zig(1 hunks)src/install/isolated_install.zig(3 hunks)
💤 Files with no reviewable changes (1)
- src/install/PackageManager/PackageManagerEnqueue.zig
🚧 Files skipped from review as they are similar to previous changes (1)
- src/install/hoisted_install.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/isolated_install.zigsrc/install/PackageManager/install_with_manager.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/isolated_install.zigsrc/install/PackageManager/install_with_manager.zig
🧠 Learnings (1)
📚 Learning: 2025-09-08T04:44:59.101Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-08T04:44:59.101Z
Learning: Applies to **/*.zig : In Zig, manage memory carefully with allocators and use defer for cleanup
Applied to files:
src/install/PackageManager/install_with_manager.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (4)
src/install/PackageManager/install_with_manager.zig (4)
723-725: Good: caller frees the returned filters slice.Matches the ownership transfer from getWorkspaceFilters.
981-987: Correct use of path buffer pool with defer return.Nice allocator hygiene.
1034-1034: Return value lifetime matches caller free — OK.Returning the owned slice (allocated via manager.allocator in append) and freeing it at the callsite is consistent. Just ensure elements don’t need deinit (see above).
569-599: Omit.uninstallcase—Subcommandhas no.uninstallvariant. TheSubcommandenum in src/install/PackageManager.zig only defines.install,.update,.add,.remove, etc., but not.uninstall, so no change is needed.Likely an incorrect or invalid review comment.
| packages_to_install: ?[]const PackageID, | ||
| ) OOM!PackageInstall.Summary { |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Plumbed packages_to_install through installIsolatedPackages — verify all call sites updated.
Confirm every call passes the new arg (or null) and the parameter order matches across hoisted/isolated paths.
Run to find call sites:
🏁 Script executed:
#!/bin/bash
rg -nP '\binstallIsolatedPackages\s*\(' -C2 --type=zigLength of output: 1087
Add missing packages_to_install argument to all installIsolatedPackages calls
- src/install/PackageManager/install_with_manager.zig:744 – update call to
installIsolatedPackages(manager, ctx, packages_to_install)(ornull) - src/install/PackageManager/security_scanner.zig:82 – likewise pass the third
packages_to_installparameter in correct order
| for (dep_ids_sort_buf.items) |dep_id| { | ||
| if (Tree.isFilteredDependencyOrWorkspace( | ||
| dep_id, | ||
| entry.pkg_id, | ||
| workspace_filters, | ||
| install_root_dependencies, | ||
| manager, | ||
| lockfile, | ||
| )) { | ||
| continue; | ||
| } | ||
|
|
||
| // TODO: handle duplicate dependencies. should be similar logic | ||
| // like we have for dev dependencies in `hoistDependency` | ||
| const pkg_id = resolutions[dep_id]; | ||
| const dep = dependencies[dep_id]; | ||
|
|
||
| // TODO: handle duplicate dependencies. should be similar logic | ||
| // like we have for dev dependencies in `hoistDependency` | ||
|
|
||
| if (!dep.behavior.isPeer()) { | ||
| // simple case: | ||
| // - add it as a dependency | ||
| // - queue it | ||
| node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); | ||
| try node_queue.writeItem(.{ | ||
| .parent_id = node_id, | ||
| .dep_id = dep_id, | ||
| .pkg_id = pkg_id, | ||
| }); | ||
| continue; | ||
| } | ||
|
|
||
| if (!dep.behavior.isPeer()) { | ||
| // simple case: | ||
| // - add it as a dependency | ||
| // - queue it | ||
| node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); | ||
| try node_queue.writeItem(.{ | ||
| .parent_id = node_id, | ||
| .dep_id = dep_id, | ||
| .pkg_id = pkg_id, | ||
| }); | ||
| continue; | ||
| try peer_dep_ids.append(dep_id); | ||
| } |
There was a problem hiding this comment.
Guard against invalid resolutions before enqueueing non-peer deps.
In the general path we don’t check pkg_id for invalid_package_id (unlike the partial-install branch). This can enqueue invalid entries and cascade into later failures.
Apply:
- const pkg_id = resolutions[dep_id];
- const dep = dependencies[dep_id];
+ const pkg_id = resolutions[dep_id];
+ if (pkg_id == invalid_package_id) {
+ continue;
+ }
+ const dep = dependencies[dep_id];📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| for (dep_ids_sort_buf.items) |dep_id| { | |
| if (Tree.isFilteredDependencyOrWorkspace( | |
| dep_id, | |
| entry.pkg_id, | |
| workspace_filters, | |
| install_root_dependencies, | |
| manager, | |
| lockfile, | |
| )) { | |
| continue; | |
| } | |
| // TODO: handle duplicate dependencies. should be similar logic | |
| // like we have for dev dependencies in `hoistDependency` | |
| const pkg_id = resolutions[dep_id]; | |
| const dep = dependencies[dep_id]; | |
| // TODO: handle duplicate dependencies. should be similar logic | |
| // like we have for dev dependencies in `hoistDependency` | |
| if (!dep.behavior.isPeer()) { | |
| // simple case: | |
| // - add it as a dependency | |
| // - queue it | |
| node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); | |
| try node_queue.writeItem(.{ | |
| .parent_id = node_id, | |
| .dep_id = dep_id, | |
| .pkg_id = pkg_id, | |
| }); | |
| continue; | |
| } | |
| if (!dep.behavior.isPeer()) { | |
| // simple case: | |
| // - add it as a dependency | |
| // - queue it | |
| node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); | |
| try node_queue.writeItem(.{ | |
| .parent_id = node_id, | |
| .dep_id = dep_id, | |
| .pkg_id = pkg_id, | |
| }); | |
| continue; | |
| try peer_dep_ids.append(dep_id); | |
| } | |
| for (dep_ids_sort_buf.items) |dep_id| { | |
| if (Tree.isFilteredDependencyOrWorkspace( | |
| dep_id, | |
| entry.pkg_id, | |
| workspace_filters, | |
| install_root_dependencies, | |
| manager, | |
| lockfile, | |
| )) { | |
| continue; | |
| } | |
| - const pkg_id = resolutions[dep_id]; | |
| const pkg_id = resolutions[dep_id]; | |
| if (pkg_id == invalid_package_id) { | |
| continue; | |
| } | |
| const dep = dependencies[dep_id]; | |
| // TODO: handle duplicate dependencies. should be similar logic | |
| // like we have for dev dependencies in `hoistDependency` | |
| if (!dep.behavior.isPeer()) { | |
| // simple case: | |
| // - add it as a dependency | |
| // - queue it | |
| node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); | |
| try node_queue.writeItem(.{ | |
| .parent_id = node_id, | |
| .dep_id = dep_id, | |
| .pkg_id = pkg_id, | |
| }); | |
| continue; | |
| } | |
| try peer_dep_ids.append(dep_id); | |
| } |
🤖 Prompt for AI Agents
In src/install/isolated_install.zig around lines 198 to 230, the code does not
validate pkg_id for non-peer dependencies before appending to node_dependencies
and enqueueing, which can insert invalid_package_id entries; add a guard
mirroring the partial-install branch: after resolving pkg_id check if it equals
invalid_package_id and if so skip (or handle as the partial-install path does)
so you do not append to node_dependencies or write the node_queue entry for that
dep_id; ensure the same skip behavior is used for both appending and queueing to
prevent invalid entries from propagating.
| workspace_filters, | ||
| install_root_dependencies, | ||
| log_level, | ||
| null, | ||
| ), |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
API parity check with hoisted/isolated installers.
Ensure both installers interpret workspace_filters the same way and that the extra packages_to_install arg defaults to null consistently.
🏁 Script executed:
#!/bin/bash
rg -nP 'pub\s+fn\s+installHoistedPackages\(|pub\s+fn\s+installIsolatedPackages\(' -C3 --type=zigLength of output: 728
🏁 Script executed:
#!/bin/bash
sed -n '1,40p' src/install/hoisted_install.zig
sed -n '1,40p' src/install/isolated_install.zigLength of output: 2985
🏁 Script executed:
#!/bin/bash
ls -R src/install/PackageManagerLength of output: 459
Fix installIsolatedPackages call signature (install_with_manager.zig:738–742)
Swap workspace_filters and install_root_dependencies, drop the log_level argument, and leave packages_to_install as null so the call matches
installIsolatedPackages(
manager,
command_ctx,
install_root_dependencies, // ← first
workspace_filters, // ← second
null // packages_to_install
)🤖 Prompt for AI Agents
In src/install/PackageManager/install_with_manager.zig around lines 738 to 742,
the call to installIsolatedPackages uses the wrong argument order and an extra
argument; swap workspace_filters and install_root_dependencies, remove the
log_level argument, and pass packages_to_install as null so the call becomes
installIsolatedPackages(manager, command_ctx, install_root_dependencies,
workspace_filters, null).
| var workspace_filters: std.ArrayListUnmanaged(WorkspaceFilter) = .{}; | ||
| // only populated when subcommand is `.install` | ||
| if (manager.subcommand == .install and manager.options.filter_patterns.len > 0) { | ||
| try workspace_filters.ensureUnusedCapacity(manager.allocator, manager.options.filter_patterns.len); | ||
| for (manager.options.filter_patterns) |pattern| { | ||
| try workspace_filters.append(manager.allocator, try WorkspaceFilter.init(manager.allocator, pattern, original_cwd, path_buf[0..])); | ||
| } | ||
| } | ||
|
|
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Ownership of WorkspaceFilter elements — confirm no per-element deinit needed.
We free the backing slice at the callsite, but if WorkspaceFilter owns heap data, element-level deinit may be required to avoid leaks.
Run to inspect the type:
If deinit is required, switch to returning ArrayListUnmanaged and let the caller loop deinit each element before freeing the buffer.
🏁 Script executed:
#!/bin/bash
rg -nP 'pub\s+const\s+WorkspaceFilter\b|struct\s+WorkspaceFilter\b' -C5 --type=zig
rg -nP '\b(deinit|destroy)\b.*WorkspaceFilter' --type=zigLength of output: 752
Implement per‐element cleanup for WorkspaceFilter before freeing the list
Before deallocating workspace_filters, loop over its elements and call WorkspaceFilter.deinit(filter, allocator) to free any heap‐owned data (e.g. the name or path strings), then deinit the list itself.
Example:
for (workspace_filters.toSlice()) |filter| {
WorkspaceFilter.deinit(filter, manager.allocator);
}
workspace_filters.deinit(manager.allocator);🤖 Prompt for AI Agents
In src/install/PackageManager/install_with_manager.zig around lines 988 to 996,
workspace_filters is populated with WorkspaceFilter instances but never
per-element deinitialized before the list is freed; iterate over
workspace_filters.toSlice() and call WorkspaceFilter.deinit(filter,
manager.allocator) for each element to release heap-owned fields (like
name/path), then call workspace_filters.deinit(manager.allocator) to free the
list itself.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
src/install/PackageManager/install_with_manager.zig (1)
573-582: Emit error details on unexpected scan failuresRight now non-
SecurityScannerInWorkspaceerrors exit silently. Print the error for visibility.- else => {}, + else => { + Output.prettyErrorln("Security scan failed: {s}", .{@errorName(err)}); + },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/install/PackageManager/install_with_manager.zig(4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/PackageManager/install_with_manager.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/PackageManager/install_with_manager.zig
🧠 Learnings (1)
📚 Learning: 2025-09-08T04:44:59.101Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-08T04:44:59.101Z
Learning: Applies to **/*.zig : In Zig, manage memory carefully with allocators and use defer for cleanup
Applied to files:
src/install/PackageManager/install_with_manager.zig
🔇 Additional comments (2)
src/install/PackageManager/install_with_manager.zig (2)
738-742: Hoisted install callsite: argument order looks good
workspace_filterstheninstall_root_dependencies, followed bylog_levelandnullmatches expectations.
744-750: Isolated install callsite fix: LGTMSwapping order and dropping
log_levelaligns with the noted signature.
| if (manager.options.security_scanner != null) { | ||
| const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove; | ||
|
|
||
| if (is_subcommand_to_run_scanner) { | ||
| if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| { | ||
| switch (err) { | ||
| error.SecurityScannerInWorkspace => { |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Run scanner on uninstall too
PR title promises scan on uninstall; include the alias if Subcommand distinguishes .remove and .uninstall.
- const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove;
+ const is_subcommand_to_run_scanner =
+ manager.subcommand == .add or
+ manager.subcommand == .update or
+ manager.subcommand == .install or
+ manager.subcommand == .remove or
+ manager.subcommand == .uninstall;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (manager.options.security_scanner != null) { | |
| const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove; | |
| if (is_subcommand_to_run_scanner) { | |
| if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| { | |
| switch (err) { | |
| error.SecurityScannerInWorkspace => { | |
| if (manager.options.security_scanner != null) { | |
| const is_subcommand_to_run_scanner = | |
| manager.subcommand == .add or | |
| manager.subcommand == .update or | |
| manager.subcommand == .install or | |
| manager.subcommand == .remove or | |
| manager.subcommand == .uninstall; | |
| if (is_subcommand_to_run_scanner) { | |
| if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| { | |
| switch (err) { | |
| error.SecurityScannerInWorkspace => { |
🤖 Prompt for AI Agents
In src/install/PackageManager/install_with_manager.zig around lines 569 to 575,
the current condition only treats manager.subcommand == .remove as the uninstall
case so the security scanner won't run for the `.uninstall` variant; update the
condition to include the `.uninstall` enum value (or its alias) alongside
`.remove` so both uninstall synonyms trigger the scanner, i.e., extend the
is_subcommand_to_run_scanner boolean to also check for `.uninstall`.
| if (manager.options.security_scanner != null) { | ||
| const is_subcommand_to_run_scanner = manager.subcommand == .add or manager.subcommand == .update or manager.subcommand == .install or manager.subcommand == .remove; | ||
|
|
||
| if (is_subcommand_to_run_scanner) { | ||
| if (security_scanner.performSecurityScanAfterResolution(manager, ctx, original_cwd) catch |err| { | ||
| switch (err) { | ||
| error.SecurityScannerInWorkspace => { | ||
| Output.pretty("<red>Security scanner cannot be a dependency of a workspace package. It must be a direct dependency of the root package.<r>\n", .{}); | ||
| }, | ||
| else => {}, | ||
| } | ||
|
|
||
| Global.exit(1); | ||
| }) |results| { | ||
| defer { | ||
| var results_mut = results; | ||
| results_mut.deinit(); | ||
| } | ||
|
|
||
| security_scanner.printSecurityAdvisories(manager, &results); | ||
|
|
||
| if (results.hasFatalAdvisories()) { | ||
| Output.pretty("<red>Installation aborted due to fatal security advisories<r>\n", .{}); | ||
| Global.exit(1); | ||
| } else if (results.hasWarnings()) { | ||
| if (!security_scanner.promptForWarnings()) { | ||
| Global.exit(1); | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Confirm prefetch behavior change
Earlier versions toggled manager.options.do.prefetch_resolved_tarballs = true when scanning. It's now removed. If scans depend on prefetched tarballs, this may regress performance/coverage. Please verify where prefetch is enabled or re-add it gated on is_subcommand_to_run_scanner.
🏁 Script executed:
#!/bin/bash
# Find any assignments to prefetch_resolved_tarballs in the repo
rg -nP '\bprefetch_resolved_tarballs\s*=' --type=zig -C2
# Confirm all scanner entry points
rg -nP 'performSecurityScanAfterResolution\(' --type=zig -n -C3Length of output: 2560
🏁 Script executed:
#!/bin/bash
# Show default Do struct including prefetch flag default
rg -nP 'pub const Do = struct' -C20 src/install/PackageManager/PackageManagerOptions.zig
rg -nP 'prefetch_resolved_tarballs' -C3 src/install/PackageManager/PackageManagerOptions.zigLength of output: 657
Restore prefetch for security scans
The current options setup unconditionally disables do.prefetch_resolved_tarballs when a security scanner is configured (see PackageManagerOptions.zig line 287), so any scan in install_with_manager.zig runs without the tarballs fetched first. Add back
manager.options.do.prefetch_resolved_tarballs = true;immediately before invoking performSecurityScanAfterResolution(...) (gated on is_subcommand_to_run_scanner) to ensure scans have the resolved packages available.
🤖 Prompt for AI Agents
In src/install/PackageManager/install_with_manager.zig around lines 569 to 599,
restore prefetching before running the security scanner: immediately before
calling security_sc<codegen_instructions>
In src/install/PackageManager/install_with_manager.zig around lines 569 to 599,
before invoking performSecurityScanAfterResolution(...) (inside the
is_subcommand_to_run_scanner branch where manager.options.security_scanner !=
null), set manager.options.do.prefetch_resolved_tarballs = true so resolved
tarballs are prefetched for the scan; add this single assignment immediately
before the performSecurityScanAfterResolution call, keeping the gating logic
unchanged.
| const workspace_filters, const install_root_dependencies = (try getWorkspaceFilters(manager, original_cwd)); | ||
| defer manager.allocator.free(workspace_filters); | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Avoid leaking WorkspaceFilter internals; deinit each element before free
Each WorkspaceFilter may own heap data. Freeing the slice without per-element deinit leaks. Also return a mutable slice from getWorkspaceFilters so deinit is possible.
- const workspace_filters, const install_root_dependencies = (try getWorkspaceFilters(manager, original_cwd));
- defer manager.allocator.free(workspace_filters);
+ var workspace_filters, const install_root_dependencies = try getWorkspaceFilters(manager, original_cwd);
+ defer {
+ // release per-element resources, then free the buffer
+ for (workspace_filters) |*filter| {
+ WorkspaceFilter.deinit(filter, manager.allocator);
+ }
+ manager.allocator.free(workspace_filters);
+ }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/install/PackageManager/install_with_manager.zig around lines 723 to 725,
the code frees the workspace_filters slice directly which leaks any heap-owned
fields inside each WorkspaceFilter; change getWorkspaceFilters to return a
mutable slice so callers can deinit elements, then replace the single free with
a small loop that calls workspace_filters[i].deinit() for every element
(handling errors if deinit can fail or making it fallible at callsite), and only
after all elements are deinitialized call
manager.allocator.free(workspace_filters).
| pub fn getWorkspaceFilters(manager: *PackageManager, original_cwd: []const u8) !struct { | ||
| []const WorkspaceFilter, | ||
| bool, | ||
| } { | ||
| const path_buf = bun.path_buffer_pool.get(); | ||
| defer bun.path_buffer_pool.put(path_buf); | ||
|
|
||
| var workspace_filters: std.ArrayListUnmanaged(WorkspaceFilter) = .{}; | ||
| // only populated when subcommand is `.install` | ||
| if (manager.subcommand == .install and manager.options.filter_patterns.len > 0) { | ||
| try workspace_filters.ensureUnusedCapacity(manager.allocator, manager.options.filter_patterns.len); | ||
| for (manager.options.filter_patterns) |pattern| { | ||
| try workspace_filters.append(manager.allocator, try WorkspaceFilter.init(manager.allocator, pattern, original_cwd, path_buf[0..])); | ||
| } | ||
| } | ||
|
|
||
| var install_root_dependencies = workspace_filters.items.len == 0; | ||
| if (!install_root_dependencies) { | ||
| const pkg_names = manager.lockfile.packages.items(.name); | ||
|
|
||
| const abs_root_path = abs_root_path: { | ||
| if (comptime !Environment.isWindows) { | ||
| break :abs_root_path strings.withoutTrailingSlash(FileSystem.instance.top_level_dir); | ||
| } | ||
|
|
||
| var abs_path = Path.pathToPosixBuf(u8, FileSystem.instance.top_level_dir, path_buf); | ||
| break :abs_root_path strings.withoutTrailingSlash(abs_path[Path.windowsVolumeNameLen(abs_path)[0]..]); | ||
| }; | ||
|
|
||
| for (workspace_filters.items) |filter| { | ||
| const pattern, const path_or_name = switch (filter) { | ||
| .name => |pattern| .{ pattern, pkg_names[0].slice(manager.lockfile.buffers.string_bytes.items) }, | ||
| .path => |pattern| .{ pattern, abs_root_path }, | ||
| .all => { | ||
| install_root_dependencies = true; | ||
| continue; | ||
| }, | ||
| }; | ||
|
|
||
| switch (bun.glob.walk.matchImpl(manager.allocator, pattern, path_or_name)) { | ||
| .match, .negate_match => install_root_dependencies = true, | ||
|
|
||
| .negate_no_match => { | ||
| // always skip if a pattern specifically says "!<name>" | ||
| install_root_dependencies = false; | ||
| break; | ||
| }, | ||
|
|
||
| .no_match => {}, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return .{ workspace_filters.items, install_root_dependencies }; | ||
| } | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Return a mutable slice and document ownership; add a sanity check
- Return
[]WorkspaceFilter(not[]const) so callers can deinit elements. - Add a brief doc comment clarifying ownership.
- Assert root package presence before
pkg_names[0].
-pub fn getWorkspaceFilters(manager: *PackageManager, original_cwd: []const u8) !struct {
- []const WorkspaceFilter,
- bool,
-} {
+/// Computes workspace filters for `.install`.
+/// Returns: (filters: []WorkspaceFilter, install_root_dependencies: bool).
+/// Ownership: caller must call `WorkspaceFilter.deinit(&filter, allocator)` for each element
+/// and then `allocator.free(filters)`.
+pub fn getWorkspaceFilters(manager: *PackageManager, original_cwd: []const u8) !struct {
+ []WorkspaceFilter,
+ bool,
+} {
@@
- if (!install_root_dependencies) {
+ if (!install_root_dependencies) {
+ bun.debugAssert(manager.lockfile.packages.len > 0);
const pkg_names = manager.lockfile.packages.items(.name);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| pub fn getWorkspaceFilters(manager: *PackageManager, original_cwd: []const u8) !struct { | |
| []const WorkspaceFilter, | |
| bool, | |
| } { | |
| const path_buf = bun.path_buffer_pool.get(); | |
| defer bun.path_buffer_pool.put(path_buf); | |
| var workspace_filters: std.ArrayListUnmanaged(WorkspaceFilter) = .{}; | |
| // only populated when subcommand is `.install` | |
| if (manager.subcommand == .install and manager.options.filter_patterns.len > 0) { | |
| try workspace_filters.ensureUnusedCapacity(manager.allocator, manager.options.filter_patterns.len); | |
| for (manager.options.filter_patterns) |pattern| { | |
| try workspace_filters.append(manager.allocator, try WorkspaceFilter.init(manager.allocator, pattern, original_cwd, path_buf[0..])); | |
| } | |
| } | |
| var install_root_dependencies = workspace_filters.items.len == 0; | |
| if (!install_root_dependencies) { | |
| const pkg_names = manager.lockfile.packages.items(.name); | |
| const abs_root_path = abs_root_path: { | |
| if (comptime !Environment.isWindows) { | |
| break :abs_root_path strings.withoutTrailingSlash(FileSystem.instance.top_level_dir); | |
| } | |
| var abs_path = Path.pathToPosixBuf(u8, FileSystem.instance.top_level_dir, path_buf); | |
| break :abs_root_path strings.withoutTrailingSlash(abs_path[Path.windowsVolumeNameLen(abs_path)[0]..]); | |
| }; | |
| for (workspace_filters.items) |filter| { | |
| const pattern, const path_or_name = switch (filter) { | |
| .name => |pattern| .{ pattern, pkg_names[0].slice(manager.lockfile.buffers.string_bytes.items) }, | |
| .path => |pattern| .{ pattern, abs_root_path }, | |
| .all => { | |
| install_root_dependencies = true; | |
| continue; | |
| }, | |
| }; | |
| switch (bun.glob.walk.matchImpl(manager.allocator, pattern, path_or_name)) { | |
| .match, .negate_match => install_root_dependencies = true, | |
| .negate_no_match => { | |
| // always skip if a pattern specifically says "!<name>" | |
| install_root_dependencies = false; | |
| break; | |
| }, | |
| .no_match => {}, | |
| } | |
| } | |
| } | |
| return .{ workspace_filters.items, install_root_dependencies }; | |
| } | |
| /// Computes workspace filters for `.install`. | |
| /// Returns: (filters: []WorkspaceFilter, install_root_dependencies: bool). | |
| /// Ownership: caller must call `WorkspaceFilter.deinit(&filter, allocator)` for each element | |
| /// and then `allocator.free(filters)`. | |
| pub fn getWorkspaceFilters(manager: *PackageManager, original_cwd: []const u8) !struct { | |
| []WorkspaceFilter, | |
| bool, | |
| } { | |
| const path_buf = bun.path_buffer_pool.get(); | |
| defer bun.path_buffer_pool.put(path_buf); | |
| var workspace_filters: std.ArrayListUnmanaged(WorkspaceFilter) = .{}; | |
| // only populated when subcommand is `.install` | |
| if (manager.subcommand == .install and manager.options.filter_patterns.len > 0) { | |
| try workspace_filters.ensureUnusedCapacity(manager.allocator, manager.options.filter_patterns.len); | |
| for (manager.options.filter_patterns) |pattern| { | |
| try workspace_filters.append( | |
| manager.allocator, | |
| try WorkspaceFilter.init(manager.allocator, pattern, original_cwd, path_buf[0..]) | |
| ); | |
| } | |
| } | |
| var install_root_dependencies = workspace_filters.items.len == 0; | |
| if (!install_root_dependencies) { | |
| bun.debugAssert(manager.lockfile.packages.len > 0); | |
| const pkg_names = manager.lockfile.packages.items(.name); | |
| const abs_root_path = abs_root_path: { | |
| if (comptime !Environment.isWindows) { | |
| break :abs_root_path strings.withoutTrailingSlash(FileSystem.instance.top_level_dir); | |
| } | |
| var abs_path = Path.pathToPosixBuf(u8, FileSystem.instance.top_level_dir, path_buf); | |
| break :abs_root_path strings.withoutTrailingSlash(abs_path[Path.windowsVolumeNameLen(abs_path)[0]..]); | |
| }; | |
| for (workspace_filters.items) |filter| { | |
| const pattern, const path_or_name = switch (filter) { | |
| .name => |pattern| .{ pattern, pkg_names[0].slice(manager.lockfile.buffers.string_bytes.items) }, | |
| .path => |pattern| .{ pattern, abs_root_path }, | |
| .all => { | |
| install_root_dependencies = true; | |
| continue; | |
| }, | |
| }; | |
| switch (bun.glob.walk.matchImpl(manager.allocator, pattern, path_or_name)) { | |
| .match, .negate_match => install_root_dependencies = true, | |
| .negate_no_match => { | |
| // always skip if a pattern specifically says "!<name>" | |
| install_root_dependencies = false; | |
| break; | |
| }, | |
| .no_match => {}, | |
| } | |
| } | |
| } | |
| return .{ workspace_filters.items, install_root_dependencies }; | |
| } |
🤖 Prompt for AI Agents
In src/install/PackageManager/install_with_manager.zig around lines 981-1036,
change the function signature to return a mutable slice ([]WorkspaceFilter,
bool) and add a brief doc comment above the function stating that ownership of
the returned slice elements transfers to the caller who must deinit them; also
replace the direct access to pkg_names[0] with a sanity check (e.g., if
pkg_names.len == 0 then return an appropriate error or assert) before using
pkg_names[0], and update any call sites/types accordingly so callers can
mutate/deinit workspace filters.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
src/install/isolated_install.zig (2)
173-195: Always clear peers for this node, even on early break.Add a defer at the start of this block to future-proof against early exits adding peers later.
- queue_deps: { + queue_deps: { + defer peer_dep_ids.clearRetainingCapacity(); if (packages_to_install) |packages| {
198-230: Skip invalid resolutions before enqueueing non-peer deps.Missing guard can enqueue
invalid_package_id, leading to downstream failures.for (dep_ids_sort_buf.items) |dep_id| { if (Tree.isFilteredDependencyOrWorkspace( dep_id, entry.pkg_id, workspace_filters, install_root_dependencies, manager, lockfile, )) { continue; } - const pkg_id = resolutions[dep_id]; - const dep = dependencies[dep_id]; + const pkg_id = resolutions[dep_id]; + const dep = dependencies[dep_id]; // TODO: handle duplicate dependencies. should be similar logic // like we have for dev dependencies in `hoistDependency` if (!dep.behavior.isPeer()) { + if (pkg_id == invalid_package_id) { + continue; + } // simple case: // - add it as a dependency // - queue it node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); try node_queue.writeItem(.{ .parent_id = node_id, .dep_id = dep_id, .pkg_id = pkg_id, }); continue; } try peer_dep_ids.append(dep_id); }
🧹 Nitpick comments (3)
src/install/isolated_install.zig (3)
173-195: Preserve filtering semantics in partial-install root path.Currently, root partial-install bypasses
Tree.isFilteredDependencyOrWorkspace(...), which may unintentionally include filtered/dev deps. Apply the same filter here for consistency.queue_deps: { - if (packages_to_install) |packages| { + if (packages_to_install) |packages| { if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) for (dep_ids_sort_buf.items) |dep_id| { + if (Tree.isFilteredDependencyOrWorkspace( + dep_id, + entry.pkg_id, + workspace_filters, + install_root_dependencies, + manager, + lockfile, + )) { + continue; + } const pkg_id = resolutions[dep_id]; if (pkg_id == invalid_package_id) { continue; } for (packages) |package_to_install| { if (package_to_install == pkg_id) {Does partial-install intend to honor the same filters (workspaces/dev) as the general path? If not, ignore this change.
173-195: Avoid O(N×M) lookups when matching requested packages.Build a set of
PackageIDonce, then do O(1) membership checks.- if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) - for (dep_ids_sort_buf.items) |dep_id| { + if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) + var install_set = std.AutoHashMap(PackageID, void).init(lockfile.allocator); + defer install_set.deinit(); + try install_set.ensureTotalCapacity(lockfile.allocator, @intCast(packages.len)); + for (packages) |p| { + _ = try install_set.getOrPut(p); + } + for (dep_ids_sort_buf.items) |dep_id| { const pkg_id = resolutions[dep_id]; if (pkg_id == invalid_package_id) { continue; } - - for (packages) |package_to_install| { - if (package_to_install == pkg_id) { + if (install_set.contains(pkg_id)) { node_dependencies[node_id.get()].appendAssumeCapacity(.{ .dep_id = dep_id, .pkg_id = pkg_id }); try node_queue.writeItem(.{ .parent_id = node_id, .dep_id = dep_id, .pkg_id = pkg_id, }); - break; - } - } + } } break :queue_deps; }
173-195: Resolve the TODO: emit a user-facing error on non-root partial-install.If partial-install is triggered below root, print an error and abort (or at least warn and skip). Example:
- if (node_id == .root) { // TODO: print an error when scanner is actually a dependency of a workspace (we should not support this) + if (node_id == .root) { // partial-install only supported at root ... break :queue_deps; - } + } else { + Output.prettyErrorln( + "Partial install is only supported at the root workspace; refusing to proceed under a workspace node.", + .{}, + ); + Global.exit(1); + }I can wire this to a feature flag if you prefer a soft warning instead of exit.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/install/isolated_install.zig(3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
Implement debug logs in Zig using
const log = bun.Output.scoped(.${SCOPE}, false);and invokinglog("...", .{})
Files:
src/install/isolated_install.zig
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup
Files:
src/install/isolated_install.zig
🔇 Additional comments (1)
src/install/isolated_install.zig (1)
9-10: Signature change looks good.New
packages_to_installparameter is clear and unlocks partial installs.
What does this PR do?
bun pm scanHow did you verify your code works?
large test matrix