Skip to content

fix(bundler): correct build-target detection for transforms - #829

Merged
harlan-zw merged 4 commits into
mainfrom
fix/bundler-transform-targeting
Jul 14, 2026
Merged

harlan-zw merged 4 commits into
mainfrom
fix/bundler-transform-targeting

Conversation

@harlan-zw

@harlan-zw harlan-zw commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

N/A

❓ Type of change

  • 📖 Documentation
  • 🐞 Bug fix
  • 👌 Enhancement
  • ✨ New feature
  • 🧹 Chore
  • ⚠️ Breaking change

📚 Description

Dead plugin: TreeshakeServerComposables never ran under Vite

vite.apply() returned false unless env.isSsrBuild, so client builds (where treeshaking should happen) never installed the plugin, and SSR builds installed it with options.enabled = false so it no-oped. Net effect: the plugin did nothing in any Vite build. Unit tests passed only because they invoked the transform handler directly.

Scope safety

The transform previously deleted any statement-level call whose callee name matched useServerHead|useServerHeadSafe|useServerSeoMeta|useSchemaOrg, with no proof the identifier was an unhead binding; a local function named useServerHead was deleted too. It now uses ScopeTracker/ScopeTrackerImport (same pattern as UseSeoMetaTransform) and removes a call only when:

  • the callee resolves to an ImportSpecifier from unhead / unhead/* / @unhead/* (aliased imports like import { useServerHead as x } are handled), or
  • the callee has no declaration in scope and matches a known name (Nuxt auto-import case).

Locally declared or shadowed names are retained. Declarations are collected in a pre-pass (preserveExitedScopes + freeze()) so hoisted locals (function useServerHead() {} below a call site) are visible before any removal happens; the same pre-pass guards UseSeoMetaTransform's auto-import branch.

Per-environment targeting

TreeshakeServerComposables mutated the user-supplied options object and SSRStaticReplace used closure let ssr/enabled flags. Under the Vite 6+ Environment API one plugin instance can serve the client and server environments in a single pipeline, so a single flag corrupts one of them. The target is now resolved per transform call via this.environment.config.consumer, with an instance-local fallback captured from vite.apply(config, env) / webpack(ctx.name === 'server') for bundlers that create one instance per build. Both vite plugins are marked sharedDuringBuild: true, and user options are never mutated.

Unknown-target policy

Plain rollup (or any context where neither hook fires and no environment exists) previously replaced head.ssr with false. On an unknown target both transforms now retain the source: head.ssr stays dynamic and server composables are kept, so output is correct but unoptimized. SSRStaticReplace stays disabled during command === 'serve' (unchanged, conservative), and treeshaking remains build-only.

imports: false

UseSeoMetaTransform used options.imports = options.imports || true, making imports: false impossible and mutating the passed options. Now options.imports ?? true into a local const.

Test changes

Existing tests updated where they encoded the old behavior:

  • test/treeshakeServerComposables.test.ts: the transform helper now passes a mocked plugin context with environment.config.consumer: 'client' (previously {}), since an unknown target now correctly retains code instead of removing it.
  • test/ssrStaticReplace.test.ts: the dev-mode test asserted the handler returned undefined while apply() returned true with a disabled flag; the plugin now opts out via apply() === false in serve, so the test asserts that instead.

New coverage:

  • Scope tracking: proven import removed, aliased import removed, bare auto-import removed, local/shadowed declarations retained, non-unhead imports retained.
  • Per-environment: client and server transforms on the same plugin instance produce independent results (both plugins), environment consumer takes precedence over the apply() fallback, unknown target retains.
  • imports: false respected and options object not mutated.
  • Integration: programmatic vite.build() (Vite 8/rolldown) on a fixture through the public Unhead() vite factory, asserting the client bundle drops the useServerSeoMeta call and the SSR bundle keeps it.

pnpm vitest run packages/bundler green (128 tests), full repo suite green (1581 passed), pnpm lint clean.

Summary by CodeRabbit

  • Bug Fixes

    • Improved SSR vs client target detection so head.ssr replacement is applied only when the build target is known.
    • Refined treeshaking to remove only true unhead server composable usages, while keeping shadowed or unrelated imports.
    • Disabled these build transforms in development mode.
    • Ensured useSeoMeta respects imports: false without changing the import specifier.
  • Tests

    • Added environment-aware unit tests and expanded scope-tracking and build-target cases.
    • Added Vite client/SSR integration tests to validate expected bundled output.
  • Documentation

    • Clarified bundling behavior for unknown SSR target detection.

TreeshakeServerComposables never ran under Vite: `vite.apply()` returned
false for client builds (where treeshaking should happen) and installed
the plugin disabled for SSR builds, so it was a no-op everywhere.

- Resolve the build target per transform call via
  `this.environment.config.consumer` (Vite 6+ Environment API) so one
  shared plugin instance serves client and server environments
  independently; mark the vite plugins `sharedDuringBuild`.
- Fall back to instance-local state captured from `vite.apply()` /
  `webpack()` for bundlers that create one instance per build; never
  mutate the user-supplied options object.
- Unknown target (plain rollup): retain server composables and keep
  `head.ssr` dynamic instead of hard-coding `false`.
- Only remove server composable calls proven to be unhead imports
  (including aliases) or undeclared bare names (Nuxt auto-imports) using
  ScopeTracker; locally declared/shadowed names are retained.
- `imports: false` is now respected in UseSeoMetaTransform
  (`||` -> `??`).
- Add scope-tracking, per-environment, and unknown-target unit tests
  plus a programmatic `vite.build()` integration test for client/SSR.
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Bundler transforms now resolve SSR/client targets per transform, preserve code for unknown targets, safely treeshake server composables using scope tracking, and honor explicit SEO import rewrite options. Tests cover environment precedence, shared plugin instances, Vite builds, scope behavior, and option immutability.

Changes

Bundler target-aware transforms

Layer / File(s) Summary
Target resolution and SSR replacement
packages/bundler/src/unplugin/utils.ts, packages/bundler/src/unplugin/SSRStaticReplace.ts, packages/bundler/src/unplugin/framework.ts, packages/bundler/test/ssrStaticReplace.test.ts
Build consumers are resolved from transform environments or fallbacks; SSR replacement is skipped for unknown targets and disabled during Vite serve mode.
Scope-safe server composable treeshaking
packages/bundler/src/unplugin/TreeshakeServerComposables.ts, packages/bundler/test/treeshakeServerComposables.test.ts, packages/bundler/test/fixtures/vite-build/entry.ts, packages/bundler/test/viteBuild.integration.test.ts
Client-target transforms remove eligible unhead server composables while retaining shadowed or non-unhead calls; Vite client and SSR output assertions cover the behavior.
SEO import rewrite option
packages/bundler/src/unplugin/UseSeoMetaTransform.ts, packages/bundler/test/useSeoMetaTransform.test.ts
imports: false is preserved without mutating the options object, while call rewriting continues and hoisted declarations are recognized.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ViteEnvironment
  participant UnheadPlugins
  participant BuildConsumerResolver
  participant BundledOutput
  ViteEnvironment->>UnheadPlugins: transform source with build environment
  UnheadPlugins->>BuildConsumerResolver: resolve client or server consumer
  BuildConsumerResolver-->>UnheadPlugins: resolved consumer or fallback
  UnheadPlugins->>BundledOutput: replace head.ssr or treeshake server composables
Loading

Possibly related PRs

  • unjs/unhead#739: Both changes disable SSR static replacement during Vite serve mode.
  • unjs/unhead#749: Both changes modify UseSeoMetaTransform import-rewrite behavior.

Suggested reviewers: thealexlichter

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise, conventional, and accurately summarizes the main change: fixing build-target detection in bundler transforms.
Description check ✅ Passed The description follows the template closely and includes linked issue, change type, and a detailed explanation of the bug and fixes.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/bundler-transform-targeting

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle Size

✅ No notable changes

All bundles (14)
Bundle Gzipped Brotli Raw
Core
Client (Minimal) 5.1 kB 4.7 kB 12.8 kB ✅
Client (Full) 8.5 kB 7.7 kB 22 kB ✅
Client (Self-Contained) 5.5 kB 4.9 kB 13.5 kB ✅
Server (Minimal) 4.5 kB 4.1 kB 11.3 kB ✅
Server (Self-Contained) 4.9 kB 4.4 kB 12 kB ✅
Vue
Vue Client (Minimal) 5.6 kB 5.1 kB 13.8 kB ✅
Vue Client (Full) 9.2 kB 8.4 kB 23.9 kB ✅
Vue Server (Minimal) 5 kB 4.5 kB 12.3 kB ✅
React
React Client (Minimal) 5.6 kB 5 kB 13.8 kB ✅
React Client (Full) 9.4 kB 8.5 kB 24.4 kB ✅
React Server (Minimal) 4.8 kB 4.4 kB 12 kB ✅
Schema.org
Schema.org (Minimal) 9.6 kB 8.7 kB 26.4 kB ✅
Schema.org Imports 0.1 kB 0.1 kB 0.1 kB ✅
Schema.org Vue Meta 0.4 kB 0.3 kB 0.8 kB ✅

⚡ Performance (directional)

✅ No significant change (within CI noise)

All benchmarks (14)
Benchmark PR Δ RME
SSR render (CPU) 0.420 ms ~ noise ±11.2%
SSR render (wall) 0.282 ms ~ noise ±5.7%
SSR allocated / render 277.8 KiB ~ noise —
Schema.org cached render (CPU) 0.377 ms ~ noise ±5.6%
Schema.org cached render (wall) 0.257 ms ~ noise ±2.1%
Schema.org cached allocated / render 145.4 KiB ~ noise —
Streaming wrapStream drain (CPU) 0.240 ms ~ noise ±4.0%
Streaming wrapStream drain (wall) 0.154 ms ~ noise ±4.8%
Streaming allocated / drain 162.8 KiB ~ noise —
Streaming suspense chunk (CPU) 0.010 ms ~ noise ±5.8%
Streaming allocated / suspense chunk 4.6 KiB ~ noise —
CSR DOM mutations / nav 38 ~ noise —
CSR re-render (CPU) 0.817 ms ~ noise ±4.8%
CSR re-render (wall) 0.462 ms ~ noise ±2.1%

Baseline: main @ 179db94 · 2026-07-14 · gzipped is the headline size metric · perf is directional (shared-runner, gated)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/bundler/src/unplugin/TreeshakeServerComposables.ts`:
- Around line 99-142: Update the scope analysis around ScopeTracker and
getDeclaration() to collect hoisted function and var declarations for each scope
before the removal walk begins. Ensure earlier statement-level calls resolve
those later local bindings and remain unchanged, while genuinely undeclared
known composables still use the existing auto-import removal path.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: f40e1a18-64a0-4dc9-b9a1-ea64f0aab3d0

📥 Commits

Reviewing files that changed from the base of the PR and between 179db94 and b87809c.

📒 Files selected for processing (10)
  • packages/bundler/src/unplugin/SSRStaticReplace.ts
  • packages/bundler/src/unplugin/TreeshakeServerComposables.ts
  • packages/bundler/src/unplugin/UseSeoMetaTransform.ts
  • packages/bundler/src/unplugin/framework.ts
  • packages/bundler/src/unplugin/utils.ts
  • packages/bundler/test/fixtures/vite-build/entry.ts
  • packages/bundler/test/ssrStaticReplace.test.ts
  • packages/bundler/test/treeshakeServerComposables.test.ts
  • packages/bundler/test/useSeoMetaTransform.test.ts
  • packages/bundler/test/viteBuild.integration.test.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant