Skip to content

perf(bundler): unify AST transforms into one parse/walk pipeline - #831

Merged
harlan-zw merged 5 commits into
fix/bundler-transform-targetingfrom
feat/unified-transform-pipeline
Jul 14, 2026
Merged

harlan-zw merged 5 commits into
fix/bundler-transform-targetingfrom
feat/unified-transform-pipeline

Conversation

@harlan-zw

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

Copy link
Copy Markdown
Collaborator

Stacks on #829 (fix/bundler-transform-targeting).

🔗 Linked issue

N/A

❓ Type of change

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

📚 Description

What

TreeshakeServerComposables, UseSeoMetaTransform and MinifyTransform each ran their own parseSync (oxc-parser) + oxc-walker walk + MagicString + sourcemap over the same modules, with duplicated shouldTransformId/shouldTransformCode. A module matching all three code filters parsed three times per build.

This merges the three concerns into one private createTransformPipeline module (src/unplugin/createTransformPipeline.ts, not exported from any public entry): one combined prefilter, one parse, one ScopeTracker walk dispatching per node to the three concerns, one MagicString, one sourcemap.

Architecture

  • Filtering, rolldown-first: the unified plugin's transform.filter uses the union code regex (SEO_META_RE | SERVER_COMPOSABLE_RE | HEAD_RE sources joined) and the shared createJsVueTransformIdFilter id filter, so rolldown/Vite run these natively and skip the JS hook. Inside the handler, cheap per-concern regex + id checks decide which phases run (per-concern filter.include/exclude overrides still apply per phase). transformInclude is kept for webpack/rspack.
  • Phase order per call site: server-composable removal runs first and claims the removed ExpressionStatement range; the seoMeta and minify phases skip any node inside a claimed range. This reproduces what plugin registration order used to guarantee (a useServerSeoMeta call treeshaken from the client build is never seoMeta-rewritten or minified — the differential test asserts the minifier is not even invoked for removed nodes). Then seoMeta lowering, then static content minify (still async: pending minifications are collected during the walk and awaited after).
  • Per-target dispatch stays per transform call: treeshake only when resolveBuildConsumer(...) === 'client'; seoMeta + minify run for both; unknown targets retain server code. sharedDuringBuild: true and the vite.apply()/webpack() fallbacks are preserved; on serve the pipeline still installs for the seoMeta/minify concerns but hard-disables the treeshake phase (and returns false from apply when treeshake is the only concern, matching the old plugin).
  • Overlapping-edit safety: all edits are collected during the walk and applied at the end; if two phases would edit overlapping ranges the pipeline throws one contextual error (file + offsets) and produces no partial output. Parser failure returns undefined (no transform), matching the previous MinifyTransform behavior.
  • Public surface unchanged: Unhead() / createFrameworkPlugin() keep their interfaces and options (treeshake, transformSeoMeta, minify, filter, imports, importPaths, ...); resolveCoreDefs collapses to a single def wiring the pipeline. TreeshakeServerComposables, UseSeoMetaTransform and MinifyTransform remain exported and functional as thin single-concern adapters constructing the same pipeline. Export snapshots pass unchanged. SSRStaticReplace and CreateHeadTransform are untouched.

Performance (same machine, vitest bench bench/unplugin-transform.bench.ts)

Base branch numbers measured with the pristine base plugin sources.

case base (three-pass) this PR (unified) delta
transform-positive module hitting all three concerns 374.9 ops/s (2.67 ms) 744.6 ops/s (1.34 ms) ~2.0x faster
prefiltered unrelated module 333,216 ops/s (3.0 µs) 539,047 ops/s (1.9 µs) 1.62x faster (regression budget ≤5%: no regression — one union prefilter replaces three per-plugin prefilters)

New bench cases (combined module / prefiltered module, three-pass vs unified) are committed in bench/unplugin-transform.bench.ts.

Tests

  • All 120 pre-existing bundler tests pass unchanged (snapshots, sourcemaps, vite build integration, per-environment same-instance tests), plus exports snapshot (test/exports.test.ts --pool=threads), full repo suite (1622 tests) and lint.
  • New packages/bundler/test/transformPipeline.test.ts:
    • differential test: 11 fixtures x 3 targets (client/server/unknown) run through the sequential three-plugin composition and the unified pipeline, asserting byte-identical output
    • phase-ordering, serve/apply semantics, per-environment shared-instance dispatch, conflicting-edit error, parser-failure behavior

Consolidation notes

  • importPaths threading (done): TreeshakeServerComposablesOptions now accepts importPaths; inside the unified pipeline the treeshake provenance check defaults to the seoMeta importPaths, so e.g. transformSeoMeta: { importPaths: ['#imports'] } also lets treeshake prove import { useServerHead } from '#imports' removable. The standalone TreeshakeServerComposables adapter only uses its own option, so default behavior is unchanged.
  • Auto-selecting @unhead/bundler/minify/rolldown vs .../esbuild (skipped): would require dynamic imports inside resolveCoreDefs (the minifier subpaths pull optional peer deps), which didn't fall out naturally; noting per task.

TreeshakeServerComposables, UseSeoMetaTransform and MinifyTransform each
ran their own oxc parseSync + oxc-walker walk + MagicString over the same
modules, so a module matching all three code filters parsed three times
per build.

The new private createTransformPipeline runs all three concerns over a
single parse, ScopeTracker walk, MagicString and sourcemap:

- rolldown-first filtering: the unified plugin's transform.filter uses the
  union code regex and the shared JS/Vue id filter so rolldown/Vite skip
  the JS hook natively; cheap per-concern regexes re-gate phases inside
  the handler
- phase order per call site is preserved: treeshake claims removed
  statement ranges first, and the seoMeta/minify phases skip any node
  inside a claimed range (previously guaranteed by plugin registration
  order)
- per-target dispatch stays per transform call via resolveBuildConsumer;
  unknown targets retain server code, sharedDuringBuild stays on
- overlapping edits from two phases are detected up front and throw one
  contextual error (file + offsets) with no partial output
- parser failures return undefined (no transform), matching the previous
  MinifyTransform behavior
- the treeshake provenance check accepts importPaths, defaulting to the
  seoMeta importPaths inside the unified pipeline

The public factories (TreeshakeServerComposables, UseSeoMetaTransform,
MinifyTransform) remain exported as thin single-concern adapters over the
pipeline; Unhead()/createFrameworkPlugin() now register one plugin.

Combined transform-positive module: 375 -> 745 ops/s (~2.0x); prefiltered
unrelated module: 333k -> 539k ops/s (no regression).
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5a8f610d-a5da-4f2d-9da5-4978cb25c59f

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/unified-transform-pipeline

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.

Replace the string-only nested-object decoder with a safe recursive AST
value decoder (string/number/boolean/null literals, unary +/- on numeric
literals, expression-free template literals, arrays and plain objects with
static keys; everything else returns a bail sentinel). Nested robots-style
objects with numbers, negative numbers and booleans now compile.

Match runtime `unpackMeta` exactly for the lowered output:
- replicate `sanitizeObject` (top-level entries stringifying to 'false'
  are dropped before packing)
- render structural expansions (media objects/arrays, array values) before
  scalar/packed props, mirroring `[...extras, ...meta]`
- hoist `url`/`secureUrl` first inside media object expansions
- bail arrayable meta keys (themeColor, ...) whose objects route through
  `handleObjectEntry` at runtime
- emit `'http-equiv'` quoted (was previously invalid JS output)

Add a per-prop residual fallback: when a value-level failure occurs, the
unsupported tail is kept on the original composable adjacent to the
lowered call, but only when provably render-identical (statement position,
no options arg, no title after the failure point, disjoint resolved meta
names, and residual props primitives-routed unless nothing was lowered).

Verified by a runtime-vs-compiled equivalence corpus (37 fixtures rendered
through the real unhead server runtime from both the original call and the
transformed output) doubling as an eligibility floor so future changes
can't silently narrow supported input.
… into feat/unified-transform-pipeline

# Conflicts:
#	packages/bundler/src/unplugin/TreeshakeServerComposables.ts
#	packages/bundler/src/unplugin/UseSeoMetaTransform.ts
@harlan-zw
harlan-zw merged commit c969532 into fix/bundler-transform-targeting Jul 14, 2026
@harlan-zw harlan-zw mentioned this pull request Jul 19, 2026
1 of 6 tasks
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