Skip to content

test --changed: let tsconfig paths win over packages=external - #29591

Merged
Jarred-Sumner merged 5 commits into
mainfrom
farm/ba37b025/test-changed-tsconfig-paths
Apr 23, 2026
Merged

Jarred-Sumner merged 5 commits into
mainfrom
farm/ba37b025/test-changed-tsconfig-paths

Conversation

@robobun

@robobun robobun commented Apr 22, 2026

Copy link
Copy Markdown
Collaborator

Fixes #29590

Bug

bun test --changed silently skips tests whose only path to a changed
source file goes through a tsconfig paths alias whose key looks bare.

// tsconfig.json
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./*"] } } }
// tests/alias.test.ts
import { add } from "@/src/adder";

Edit src/adder.ts, run bun test --changed, and tests/alias.test.ts
is absent from the selected set. The sibling tests/relative.test.ts
(same import, relative path) runs.

Cause

src/cli/test/ChangedFilesFilter.zig builds the module graph with
scan_transpiler.options.packages = .external so bare specifiers
aren't followed into node_modules. In the resolver, the
packages = external check fires before tsconfig paths:

// resolver.zig — old
pub fn isExternalPattern(r: *ThisResolver, import_path: string) bool {
    if (r.opts.packages == .external and isPackagePath(import_path)) {
        return true; // ← catches "@/src/adder" before paths runs
    }
    …
}

isPackagePath("@/src/adder") is true (not absolute, no .//../
prefix), so the import is marked external before
matchTSConfigPaths (resolver.zig ≈1716) ever runs. No import edge
is recorded, and the reverse-BFS in ChangedFilesFilter can't see
that the test file is affected. The same happens for any bare-looking
alias key — @/*, ~/*, components/*, etc.

Fix

Consult the enclosing tsconfig's paths before the
packages = external short-circuit. Only the
packages = external + isPackagePath path is gated on tsconfig;
user-supplied --external patterns and URL-style specifiers
(http://, //, CSS #id) still win, and nothing changes for
projects without tsconfig paths.

A new hasTSConfigPathsMatch helper does a cheap pattern-only check
(exact or * glob on the paths keys). The full matchTSConfigPaths
also verifies the target file exists on disk, which would make this
hot-path check stat every aliased import; we only need to know
whether tsconfig would claim the specifier, so the existence check
is left to the regular resolver when control falls through.

Verification

$ bun bd test test/cli/test/test-changed.test.ts
 19 pass
 0 fail

New regression test tsconfig paths alias is followed when computing the module graph covers both the aliased importer and the sibling
relative importer; it fails on main and passes with this change.

All 112 tests in test/bundler/bundler_edgecase.test.ts (incl. the
existing PackageExternalDoNotBundleNodeModules and
EntrypointWithoutPrefixSlashOrDotIsNotConsideredExternal#12734
cases) still pass.

The --changed module-graph scanner runs the bundler with
packages=external so bare specifiers aren't followed into node_modules.
isExternalPattern marks anything that looks bare (no ./ or ../ prefix)
as external before tsconfig.json "paths" is consulted, which made
every alias key like @/*, ~/*, components/* look like a package name
and silently dropped the import edge.

Consult the enclosing tsconfig's paths first: if a paths key matches
the specifier, defer to the normal resolver so the alias follows into
the project source. User-supplied --external patterns and URL-style
specifiers are unchanged.

Fixes #29590
@robobun

robobun commented Apr 22, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:41 AM PT - Apr 22nd, 2026

❌ @robobun, your commit a9fe730 has 1 failures in Build #47268 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 29591

That installs a local version of the PR into your bun-29591 executable, so you can run:

bun-29591 --bun

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Add TSConfig paths-aware resolution and user --external wildcard matching to the module resolver; try tsconfig-based resolution before treating bare package specifiers as external when opts.packages == .external. Add regression tests for --changed and bundler edge cases validating the new behavior.

Changes

Cohort / File(s) Summary
Resolver: TSConfig & external-pattern logic
src/resolver/resolver.zig
Add pub fn matchesUserExternalPattern(r, import_path) bool to check opts.external.patterns, add pub fn resolveViaTSConfigPaths(r, source_dir, import_path, kind) ?MatchResult to attempt resolution via enclosing tsconfig.json paths, and update resolveAndAutoInstall() to consult resolveViaTSConfigPaths for non-entrypoint, package-like imports when opts.packages == .external before treating them as external.
Tests: changed selection (regression)
test/cli/test/test-changed.test.ts
Add a concurrent test that creates a temporary git repo with tsconfig.json compilerOptions.paths alias ("@/*": ["./*"]), makes an uncommitted change to src/adder.ts, and asserts bun test --changed selects both the alias-importing and relative-importing tests.
Tests: bundler edge cases
test/bundler/bundler_edgecase.test.ts
Add two bundler edge-case tests: one ensuring a catch-all paths mapping doesn't cause inlining of bare imports when packages: "external", and another ensuring an explicit --external wildcard ("@/src/*") takes precedence over tsconfig paths so aliased imports remain external.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main fix: making tsconfig paths resolution take priority over packages=external logic in the module graph scanning for bun test --changed.
Description check ✅ Passed The description provides clear sections covering the bug reproduction, root cause analysis, the fix approach, and verification steps, matching the template structure.
Linked Issues check ✅ Passed The code changes directly address the linked issue #29590 by modifying resolver logic to consult tsconfig paths before applying packages=external, and adding regression tests to verify the fix works correctly.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the tsconfig paths alias resolution in the module graph scanning: resolver updates, a regression test, and bundler edge-case tests to prevent regression.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/resolver/resolver.zig`:
- Around line 631-633: The call to dirInfoCached in hasTSConfigPathsMatch must
be guarded so it never receives an empty or non-absolute source_dir; before
calling r.dirInfoCached(source_dir) validate source_dir is non-empty and
absolute (or replace it with the resolver's normalized top-level/fallback
directory used elsewhere) and only then call dirInfoCached, returning false if
there is no valid resolved dir; make the identical guard/update for the other
dirInfoCached usage noted around the second occurrence (the block at ~751-754)
so both probe sites use the same normalization/fallback logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8e3419c2-1800-4a14-8337-c1d8e5cbc7b1

📥 Commits

Reviewing files that changed from the base of the PR and between 3453c22 and 3385536.

📒 Files selected for processing (2)
  • src/resolver/resolver.zig
  • test/cli/test/test-changed.test.ts

Comment thread src/resolver/resolver.zig Resolved
Comment thread src/resolver/resolver.zig Resolved
Comment thread src/resolver/resolver.zig Resolved
… file

The first version of this fix gated the packages=external short-circuit
on a pattern-only check of tsconfig paths keys. That worked for the
reported "@/*" case but broke an idiomatic use of paths: a catch-all
entry like "*": ["./types/*"] used for ambient .d.ts stubs matches
every bare specifier, so every dependency silently bypassed
--packages=external and got bundled.

Resolve the alias via matchTSConfigPaths (which requires the target to
exist on disk) and only then skip the external short-circuit. If the
alias has no file behind it the specifier falls through to the normal
packages=external path unchanged.

Also adds an edgecase bundler test that imports a real node_modules
package under a tsconfig with '*': ['./types/*']; the package must stay
external.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/resolver/resolver.zig`:
- Around line 734-737: The tsconfig paths probe (resolveViaTSConfigPaths) is
running before the external/URL short-circuit and can override explicit
externals or URL-like specifiers; modify the resolver logic so that before
calling r.resolveViaTSConfigPaths(source_dir, import_path, kind) you first check
and preserve explicit externals and URL-like specifiers (use r.opts.packages,
isPackagePath(import_path), and any existing URL/externals checks used
elsewhere) — either move the resolveViaTSConfigPaths invocation to after the
external/URL short-circuit block or add a guard that returns/skips the tsconfig
probe when the import matches an explicit external pattern or is a URL-style
specifier (apply the same change for the other occurrence at the block around
lines 758-770).
- Around line 737-752: The fast-path return from r.resolveViaTSConfigPaths
bypasses r.finalizeResult, returning a partially populated Result and skipping
module-type inference, side-effect/package metadata, symlink canonicalization,
and enclosing-tsconfig JSX/decorator merges; change the branch that handles the
resolveViaTSConfigPaths hit to call r.finalizeResult(...) on the intermediate
result (the value bound to "res") and return the finalized Result instead of
returning "res" directly—use the same parameters finalizeResult expects (the
intermediate Result, import kind, import_path/source_dir context and any
relevant flags like r.opts.jsx) so the behavior is identical to the normal path
that calls finalizeResult around the same code paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 03bb7072-f9ba-4bc5-b05c-833c36aa323e

📥 Commits

Reviewing files that changed from the base of the PR and between 2353f9e and 10d1932.

📒 Files selected for processing (2)
  • src/resolver/resolver.zig
  • test/bundler/bundler_edgecase.test.ts

Comment thread src/resolver/resolver.zig Resolved
Comment thread src/resolver/resolver.zig Resolved
Comment thread src/resolver/resolver.zig Resolved
Comment thread src/resolver/resolver.zig Resolved
The follow-up fix for #29590 tried tsconfig paths before the
packages=external short-circuit, but that block also ran ahead of the
user-supplied --external wildcard check in isExternalPattern. With
--packages=external --external '@/src/*' plus a tsconfig paths entry
for @/*, the alias silently bundled @/src/* instead of leaving it
external — contrary to the PR's documented intent.

Skip the tsconfig-paths fast path when the specifier already matches a
user --external wildcard. Isolates the new behaviour (tsconfig-aliased
local files should not be externalised by packages=external) from user
config (explicit --external patterns still win).

Also adds an edgecase bundler test that exercises the overlap:
--packages=external plus --external '@/src/*' over a tsconfig that
aliases @/* to ./*; the import must stay external.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
src/resolver/resolver.zig (1)

750-765: ⚠️ Potential issue | 🟠 Major

Run the tsconfig-paths fast path through finalizeResult().

The early return at Lines 750-765 bypasses the normal post-resolution pipeline at Lines 943-946, so alias hits skip module-type inference, side-effect/package metadata, symlink canonicalization, and the resolved file's enclosing-tsconfig JSX/decorator merges.

🐛 Minimal fix
         {
             if (r.resolveViaTSConfigPaths(source_dir, import_path, kind)) |res| {
+                var result = Result{
+                    .import_kind = kind,
+                    .path_pair = res.path_pair,
+                    .diff_case = res.diff_case,
+                    .package_json = res.package_json,
+                    .dirname_fd = res.dirname_fd,
+                    .file_fd = res.file_fd,
+                    .jsx = r.opts.jsx,
+                    .module_type = res.module_type,
+                    .flags = .{
+                        .is_external = res.is_external,
+                        .is_external_and_rewrite_import_path = res.is_external,
+                        .is_from_node_modules = res.is_node_module,
+                    },
+                };
+                r.finalizeResult(&result, kind) catch |err| return .{ .failure = err };
+
                 if (r.debug_logs) |*debug| {
                     debug.addNote("Resolved via tsconfig.json \"paths\" before applying packages=external");
                     r.flushDebugLogs(.success) catch {};
                 }
-                return .{
-                    .success = Result{
-                        .import_kind = kind,
-                        .path_pair = res.path_pair,
-                        .diff_case = res.diff_case,
-                        .package_json = res.package_json,
-                        .dirname_fd = res.dirname_fd,
-                        .file_fd = res.file_fd,
-                        .jsx = r.opts.jsx,
-                    },
-                };
+                return .{ .success = result };
             }
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/resolver/resolver.zig` around lines 750 - 765, The tsconfig-paths fast
path currently returns the raw Result directly after r.resolveViaTSConfigPaths,
skipping the normal post-resolution pipeline; instead, call the same
finalizeResult(...) code used by the main resolution path with the resolved info
from r.resolveViaTSConfigPaths (preserving r.debug_logs and calling
r.flushDebugLogs as before) so that module-type inference, side-effect/package
metadata, symlink canonicalization, and enclosing-tsconfig JSX/decorator merges
are applied before returning; replace the early return with invoking
finalizeResult on the res payload (using the same fields: res.path_pair,
res.diff_case, res.package_json, res.dirname_fd, res.file_fd, and r.opts.jsx)
and return its result.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/resolver/resolver.zig`:
- Around line 750-765: The tsconfig-paths fast path currently returns the raw
Result directly after r.resolveViaTSConfigPaths, skipping the normal
post-resolution pipeline; instead, call the same finalizeResult(...) code used
by the main resolution path with the resolved info from
r.resolveViaTSConfigPaths (preserving r.debug_logs and calling r.flushDebugLogs
as before) so that module-type inference, side-effect/package metadata, symlink
canonicalization, and enclosing-tsconfig JSX/decorator merges are applied before
returning; replace the early return with invoking finalizeResult on the res
payload (using the same fields: res.path_pair, res.diff_case, res.package_json,
res.dirname_fd, res.file_fd, and r.opts.jsx) and return its result.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ae77c6c0-290c-459f-9283-7172091e1d26

📥 Commits

Reviewing files that changed from the base of the PR and between 10d1932 and e4cdb47.

📒 Files selected for processing (2)
  • src/resolver/resolver.zig
  • test/bundler/bundler_edgecase.test.ts

Comment thread src/resolver/resolver.zig
Comment on lines +746 to +748
if (kind != .entry_point_build and kind != .entry_point_run and
r.opts.packages == .external and isPackagePath(import_path) and
!r.matchesUserExternalPattern(import_path))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 The e4cdb47 guard only checks r.opts.external.patterns (wildcard --external entries), but exact-match --external args like --external @scope/pkg are stored in r.opts.external.node_modules (options.zig:164-165), so they still lose to a resolving tsconfig paths alias under --packages=external. Same precedence gap as the wildcard case just fixed, just for the other storage bucket — consider also consulting r.opts.external.node_modules (with the trailing-segment-stripping loop from line 1332-1350) before entering this block.

Extended reasoning...

What the bug is

Commit e4cdb47 added !r.matchesUserExternalPattern(import_path) to the guard at the top of the new tsconfig-paths probe so that an explicit user --external wins over a tsconfig paths alias. But matchesUserExternalPattern (resolver.zig:607-619) only iterates r.opts.external.patterns — the wildcard bucket. Per ExternalModules.init (options.zig:152-165), an --external argument that contains no * and satisfies isPackagePath is inserted into result.node_modules (a BufSet), not into .patterns. So an exact-form external like --external @scope/pkg is invisible to the new guard.

Step-by-step proof

Project:

// tsconfig.json
{ "compilerOptions": { "baseUrl": ".", "paths": { "@scope/pkg": ["./local-shim.ts"] } } }
// entry.ts
import { x } from "@scope/pkg";   // ./local-shim.ts exists on disk

Run bun build entry.ts --packages=external --external @scope/pkg:

  1. ExternalModules.init sees "@scope/pkg": no *, isPackagePath true → result.node_modules.insert("@scope/pkg"). .patterns stays empty.
  2. resolveAndAutoInstall reaches the new block: kind == .stmt, r.opts.packages == .external, isPackagePath("@scope/pkg") → true, matchesUserExternalPattern("@scope/pkg") iterates an empty .patterns → false. Guard passes.
  3. resolveViaTSConfigPaths finds the enclosing tsconfig, matchTSConfigPaths exact-matches key "@scope/pkg", loadAsFileOrDirectory("./local-shim.ts") succeeds → returns a MatchResult.
  4. The block returns .success with the resolved local file. ./local-shim.ts is bundled.
  5. The r.opts.external.node_modules.contains(query) check at resolver.zig:1328-1350 — which would have matched "@scope/pkg" and returned is_external = true — lives inside resolveWithoutSymlinks and is never reached.

Before this PR, step 2's block didn't exist; isExternalPattern short-circuited on packages == .external and the import stayed external. Without --packages=external, the new block's gate is false and resolution flows through resolveWithoutSymlinks → line 1328 (which runs before loadNodeModules/matchTSConfigPaths at line ~1786), so the exact external correctly wins. The regression is specific to the --packages=external + exact --external combination.

Why nothing else catches it

r.opts.external.node_modules is consulted in exactly one place on the resolver hot path: the loop at lines 1328-1350 inside resolveWithoutSymlinks's check_package branch. The early return at lines 750-767 bypasses resolveWithoutSymlinks entirely. The new ExternalWildcardBeatsTSConfigPaths#29590 test only exercises external: ["@/src/*"] (wildcard → .patterns), so it doesn't cover this bucket. The comment at lines 742-745 ("A user-supplied --external wildcard still wins") is accurate as written but inadvertently documents the gap — only wildcards win.

Impact

Low / nit. Triggering it requires: --packages=external (which already externalises every bare specifier on its own) plus a redundant exact --external <pkg> for that same specifier plus a tsconfig paths entry whose key is exactly that specifier and whose target resolves on disk. That's a narrow, somewhat contrived configuration. But it is a real behavioural regression that silently overrides explicit user intent, and it's inconsistent with both the wildcard handling just added in e4cdb47 and the non---packages=external flow.

Suggested fix

Extend the guard to consult both stores, e.g. before calling resolveViaTSConfigPaths:

if (r.opts.external.node_modules.count() > 0 and
    !strings.hasSuffixComptime(import_path, "/"))
{
    var query = import_path;
    while (true) {
        if (r.opts.external.node_modules.contains(query)) break :probe; // skip tsconfig probe
        const slash = strings.lastIndexOfChar(query, '/') orelse break;
        query = query[0..slash];
    }
}

(or fold the node_modules lookup into matchesUserExternalPattern so both call sites stay in sync). A sibling test alongside ExternalWildcardBeatsTSConfigPaths#29590 with external: ["@scope/pkg"] and paths: { "@scope/pkg": ["./shim.ts"] } would lock this down.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
src/resolver/resolver.zig (1)

733-752: ⚠️ Potential issue | 🟠 Major

Run tsconfig-path hits through finalizeResult() before returning.

Line 742 returns before the normal Resolver.finalizeResult() call at Line 932, so this path drops extension-based module_type, side-effects/package metadata, symlink canonicalization, and the resolved file’s enclosing-tsconfig JSX/decorator merge. Line 750 hard-codes r.opts.jsx, which is wrong when the aliased target lives under a more specific tsconfig.

🐛 Minimal fix
         {
             if (r.resolveViaTSConfigPaths(source_dir, import_path, kind)) |res| {
+                var result: Result = .{
+                    .import_kind = kind,
+                    .path_pair = res.path_pair,
+                    .diff_case = res.diff_case,
+                    .package_json = res.package_json,
+                    .dirname_fd = res.dirname_fd,
+                    .file_fd = res.file_fd,
+                    .jsx = r.opts.jsx,
+                    .module_type = res.module_type,
+                    .flags = .{
+                        .is_external = res.is_external,
+                        .is_external_and_rewrite_import_path = res.is_external,
+                        .is_from_node_modules = res.is_node_module,
+                    },
+                };
+                r.finalizeResult(&result, kind) catch |err| return .{ .failure = err };
+
                 if (r.debug_logs) |*debug| {
                     debug.addNote("Resolved via tsconfig.json \"paths\" before applying packages=external");
                     r.flushDebugLogs(.success) catch {};
                 }
-                return .{
-                    .success = Result{
-                        .import_kind = kind,
-                        .path_pair = res.path_pair,
-                        .diff_case = res.diff_case,
-                        .package_json = res.package_json,
-                        .dirname_fd = res.dirname_fd,
-                        .file_fd = res.file_fd,
-                        .jsx = r.opts.jsx,
-                    },
-                };
+                return .{ .success = result };
             }
         }

Based on learnings: Resolver.finalizeResult is the established path that merges the resolved file’s enclosing tsconfig JSX/decorator options, matching the runtime transpiler’s behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/resolver/resolver.zig` around lines 733 - 752, The early return inside
the r.resolveViaTSConfigPaths branch bypasses Resolver.finalizeResult, losing
extension-based module_type, side-effects/package metadata, symlink
canonicalization, and tsconfig-merged JSX/decorator options; instead of
returning the constructed Result there (and hard-coding r.opts.jsx), pass the
resolution (res and its path_pair/package_json/dirname_fd/file_fd/diff_case)
into Resolver.finalizeResult (the same call path used at Line 932) so it can
merge enclosing-tsconfig JSX/decorator options and other metadata, then return
whatever finalizeResult returns; update the branch around
resolveViaTSConfigPaths to call r.finalizeResult(...) and return that value
rather than building and returning a Result manually.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/resolver/resolver.zig`:
- Around line 733-752: The early return inside the r.resolveViaTSConfigPaths
branch bypasses Resolver.finalizeResult, losing extension-based module_type,
side-effects/package metadata, symlink canonicalization, and tsconfig-merged
JSX/decorator options; instead of returning the constructed Result there (and
hard-coding r.opts.jsx), pass the resolution (res and its
path_pair/package_json/dirname_fd/file_fd/diff_case) into
Resolver.finalizeResult (the same call path used at Line 932) so it can merge
enclosing-tsconfig JSX/decorator options and other metadata, then return
whatever finalizeResult returns; update the branch around
resolveViaTSConfigPaths to call r.finalizeResult(...) and return that value
rather than building and returning a Result manually.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4cddb06f-4372-49e4-9ee8-b78453ea756e

📥 Commits

Reviewing files that changed from the base of the PR and between e4cdb47 and a9fe730.

📒 Files selected for processing (3)
  • src/resolver/resolver.zig
  • test/bundler/bundler_edgecase.test.ts
  • test/cli/test/test-changed.test.ts

@Jarred-Sumner
Jarred-Sumner merged commit 30faa28 into main Apr 23, 2026
64 of 65 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/ba37b025/test-changed-tsconfig-paths branch April 23, 2026 00:44
structwafel pushed a commit to structwafel/bun that referenced this pull request Apr 25, 2026
…h#29591)

Fixes oven-sh#29590

## Bug

`bun test --changed` silently skips tests whose only path to a changed
source file goes through a tsconfig `paths` alias whose key looks bare.

```jsonc
// tsconfig.json
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./*"] } } }
```

```ts
// tests/alias.test.ts
import { add } from "@/src/adder";
```

Edit `src/adder.ts`, run `bun test --changed`, and `tests/alias.test.ts`
is absent from the selected set. The sibling `tests/relative.test.ts`
(same import, relative path) runs.

## Cause

`src/cli/test/ChangedFilesFilter.zig` builds the module graph with
`scan_transpiler.options.packages = .external` so bare specifiers
aren't followed into `node_modules`. In the resolver, the
`packages = external` check fires before tsconfig `paths`:

```zig
// resolver.zig — old
pub fn isExternalPattern(r: *ThisResolver, import_path: string) bool {
    if (r.opts.packages == .external and isPackagePath(import_path)) {
        return true; // ← catches "@/src/adder" before paths runs
    }
    …
}
```

`isPackagePath("@/src/adder")` is true (not absolute, no `./`/`../`
prefix), so the import is marked external before
`matchTSConfigPaths` (resolver.zig ≈1716) ever runs. No import edge
is recorded, and the reverse-BFS in `ChangedFilesFilter` can't see
that the test file is affected. The same happens for any bare-looking
alias key — `@/*`, `~/*`, `components/*`, etc.

## Fix

Consult the enclosing tsconfig's `paths` before the
`packages = external` short-circuit. Only the
`packages = external + isPackagePath` path is gated on tsconfig;
user-supplied `--external` patterns and URL-style specifiers
(`http://`, `//`, CSS `#id`) still win, and nothing changes for
projects without tsconfig paths.

A new `hasTSConfigPathsMatch` helper does a cheap pattern-only check
(exact or `*` glob on the paths keys). The full `matchTSConfigPaths`
also verifies the target file exists on disk, which would make this
hot-path check stat every aliased import; we only need to know
whether tsconfig *would* claim the specifier, so the existence check
is left to the regular resolver when control falls through.

## Verification

```console
$ bun bd test test/cli/test/test-changed.test.ts
 19 pass
 0 fail
```

New regression test `tsconfig paths alias is followed when computing
the module graph` covers both the aliased importer and the sibling
relative importer; it fails on `main` and passes with this change.

All 112 tests in `test/bundler/bundler_edgecase.test.ts` (incl. the
existing `PackageExternalDoNotBundleNodeModules` and
`EntrypointWithoutPrefixSlashOrDotIsNotConsideredExternal#12734`
cases) still pass.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
xhjkl pushed a commit to xhjkl/bun that referenced this pull request May 14, 2026
…h#29591)

Fixes oven-sh#29590

## Bug

`bun test --changed` silently skips tests whose only path to a changed
source file goes through a tsconfig `paths` alias whose key looks bare.

```jsonc
// tsconfig.json
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["./*"] } } }
```

```ts
// tests/alias.test.ts
import { add } from "@/src/adder";
```

Edit `src/adder.ts`, run `bun test --changed`, and `tests/alias.test.ts`
is absent from the selected set. The sibling `tests/relative.test.ts`
(same import, relative path) runs.

## Cause

`src/cli/test/ChangedFilesFilter.zig` builds the module graph with
`scan_transpiler.options.packages = .external` so bare specifiers
aren't followed into `node_modules`. In the resolver, the
`packages = external` check fires before tsconfig `paths`:

```zig
// resolver.zig — old
pub fn isExternalPattern(r: *ThisResolver, import_path: string) bool {
    if (r.opts.packages == .external and isPackagePath(import_path)) {
        return true; // ← catches "@/src/adder" before paths runs
    }
    …
}
```

`isPackagePath("@/src/adder")` is true (not absolute, no `./`/`../`
prefix), so the import is marked external before
`matchTSConfigPaths` (resolver.zig ≈1716) ever runs. No import edge
is recorded, and the reverse-BFS in `ChangedFilesFilter` can't see
that the test file is affected. The same happens for any bare-looking
alias key — `@/*`, `~/*`, `components/*`, etc.

## Fix

Consult the enclosing tsconfig's `paths` before the
`packages = external` short-circuit. Only the
`packages = external + isPackagePath` path is gated on tsconfig;
user-supplied `--external` patterns and URL-style specifiers
(`http://`, `//`, CSS `#id`) still win, and nothing changes for
projects without tsconfig paths.

A new `hasTSConfigPathsMatch` helper does a cheap pattern-only check
(exact or `*` glob on the paths keys). The full `matchTSConfigPaths`
also verifies the target file exists on disk, which would make this
hot-path check stat every aliased import; we only need to know
whether tsconfig *would* claim the specifier, so the existence check
is left to the regular resolver when control falls through.

## Verification

```console
$ bun bd test test/cli/test/test-changed.test.ts
 19 pass
 0 fail
```

New regression test `tsconfig paths alias is followed when computing
the module graph` covers both the aliased importer and the sibling
relative importer; it fails on `main` and passes with this change.

All 112 tests in `test/bundler/bundler_edgecase.test.ts` (incl. the
existing `PackageExternalDoNotBundleNodeModules` and
`EntrypointWithoutPrefixSlashOrDotIsNotConsideredExternal#12734`
cases) still pass.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
robobun added a commit that referenced this pull request Oct 31, 2026
…s and finalize its result

Under `packages = external`, the tsconfig `paths` lookup of #29591 ran at
the top of resolve. It answered before the URL rules, the `data:` rule and
the NUL check, and its result skipped `finalize_result`.

The lookup now runs where the package lookup starts, and a file that it
finds takes the tail of every other resolve. `sideEffects` keeps its
default for that route.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: bun test --changed ignores tsconfig paths aliases, silently skipping affected tests

2 participants