Skip to content

perf(bundler): broaden static useSeoMeta lowering - #834

Merged
harlan-zw merged 1 commit into
feat/unified-transform-pipelinefrom
feat/broader-seo-lowering
Jul 14, 2026
Merged

harlan-zw merged 1 commit into
feat/unified-transform-pipelinefrom
feat/broader-seo-lowering

Conversation

@harlan-zw

Copy link
Copy Markdown
Collaborator

Stacks on #831 (feat/unified-transform-pipeline).

What

Broadens the static useSeoMeta/useServerSeoMeta lowering in the unified transform pipeline and closes the runtime-parity gaps it exposed.

Safe recursive AST-value decoder

materializeStaticStringObject's string-only value decoder is replaced with decodeStaticValue, supporting exactly:

  • string/number/boolean/null literals
  • unary -/+ on numeric literals (-1, +1.5)
  • template literals with zero expressions
  • arrays of supported values (source order preserved)
  • plain object literals with static identifier/string keys (source order preserved), built with Object.create(null)
  • nested combinations of the above

Always rejected via a sentinel (never throws): spreads, computed keys, getters/setters/methods (kind !== 'init'), __proto__/constructor/prototype keys, identifiers/calls/member expressions, regexp/bigint literals, array holes, anything else. robots: { maxSnippet: -1, maxImagePreview: 'large', noindex: false } now lowers instead of forfeiting the whole call.

Runtime parity fixes (verified against unpackMeta)

The equivalence suite (below) exposed places where the existing lowering diverged from runtime rendering; these are fixed so compiled output is byte-identical to what runtime produces:

  • sanitizeObject semantics: runtime drops top-level packed-object entries whose value stringifies to 'false' before packing; the transform now replicates this (noindex: false disappears, matching runtime).
  • [...extras, ...meta] ordering: runtime renders structural expansions (media objects/arrays, array values) before scalar/packed props regardless of source order. Lowered meta lines are now grouped the same way (previously { description, ogImage: {…} } compiled to source order but rendered media-first at runtime).
  • url/secureUrl-first inside static media object expansions (runtime hoists them); array elements hoist only url, matching the runtime array branch.
  • Arrayable meta keys (themeColor, author, googleSiteVerification) with object values now bail to runtime: unpackMeta routes them through handleObjectEntry (sibling tags), not resolvePackedMetaObjectValue (packed string), so the old lowering produced wrong content for them.
  • http-equiv emission: previously emitted { http-equiv: … }, which is invalid JS (any contentType/refresh/contentSecurityPolicy lowering produced unparseable output). Now quoted.

Per-prop residual fallback (done, tightly guarded)

On a value-level failure (dynamic media value, undecodable nested object), the unsupported tail is now kept on the original composable adjacent to the lowered call:

useSeoMeta({ title: 'T', description: 'D', robots: { noindex: flag } })
// ->
useHead({ title: 'T', meta: [ { name: 'description', content: 'D' } ] });
useSeoMeta({ robots: { noindex: flag } })

This creates a second head entry, so it is only emitted when provably render-identical:

  • call is a statement (result unused) and has no options argument
  • title/titleTemplate never appear after the failure point (they are hoisted regardless of position; last-wins order would change)
  • residual props are plain identifier-keyed key: value pairs whose resolved meta names are disjoint from the lowered props' names (a shared name, e.g. ogImageUrl + ogImage -> og:image, would dedupe across entries and reorder tags -> whole-call bail, tested)
  • residual props must be provably primitives-routed at runtime (plain object literal on a non-media, non-arrayable key), unless nothing was lowered into meta (failedAt === 0, the issue Unable to resolve dynamic ogImage object value #769 { title, ogImage: ref } shape). A dynamic media value after lowered scalar props stays a whole-call bail: at runtime it could resolve to an object and render before the lowered props (extras ordering), which a trailing residual entry cannot reproduce — covered by an explicit bail fixture.

MEDIA_KEYS dynamic-value bail rules are unchanged; the residual mechanism only relocates already-bailing props, it never lowers them.

Tests

  • Runtime-vs-compiled equivalence corpus (seoMetaRuntimeEquivalence.test.ts): 37 fixtures rendered through the real unhead server runtime twice — once from the original useSeoMeta call, once from the transformed output — asserting identical headTags, including overlapping-dedupe and ordering cases.
  • Eligibility floor: the same corpus asserts ≥22 fully lowered and ≥26 full+partial, and prints a per-fixture summary, so a future size "win" can't come from silently narrowing supported input. Current: 22 full / 4 partial (residual) / 11 runtime-only.
  • Differential pipeline fixtures for packed robots and residual splits (client/server/unknown targets).
  • 222 bundler tests pass; exports snapshot unchanged; lint clean.

Bundle evidence

bench/bundle static-SEO fixtures rebuilt on base (096f0de9) and this branch — byte-identical, the saving holds exactly (the fixture is all flat keys, unaffected by the broadened decoder):

build raw gzip
baseline (no plugin), base & branch 19041 B 7454 B
with plugin, base & branch 14471 B 5791 B

Saving: 22.3% gzip (unchanged). last.json untouched.

Notes

  • Runtime does not specially validate __proto__/constructor/prototype keys inside packed meta objects — they are only serialized into a content string via Object.entries (no object writes), and normalizeProps already skips unsafe keys on tag props, so there is no runtime pollution path. The transform rejects them at decode time so it never materializes such objects at build time; no runtime behavior was added.
  • Pre-existing divergences left as-is (out of scope, noted for follow-up): dynamic values on packable keys (robots: someRef) still inline as content and would render [object Object] if they resolve to an object at runtime (same class of problem as Unable to resolve dynamic ogImage object value #769 but for packed keys); the runtime array-branch secureUrl colon-casing quirk (og:image:secure:url) is not replicated.
  • pnpm typecheck fails on base with a pre-existing error in packages/bundler/test/fixtures/vite-build/entry.ts (unrelated to this change).

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.
@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: 8cb28254-0f5b-4f78-9910-764262bc6b40

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/broader-seo-lowering

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.

@harlan-zw harlan-zw changed the title feat(bundler): broaden static useSeoMeta lowering perf(bundler): broaden static useSeoMeta lowering Jul 14, 2026
@harlan-zw
harlan-zw merged commit 9e050b7 into feat/unified-transform-pipeline Jul 14, 2026
harlan-zw added a commit that referenced this pull request Jul 14, 2026
* perf(bundler): unify AST transforms into one parse/walk pipeline

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).

* perf(bundler): broaden static useSeoMeta lowering (#834)

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.
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