Skip to content

fix(unhead): align Promise handling with sync rendering - #839

Merged
harlan-zw merged 7 commits into
mainfrom
fix/synchronous-hook-promises-split
Jul 19, 2026
Merged

harlan-zw merged 7 commits into
mainfrom
fix/synchronous-hook-promises-split

Conversation

@harlan-zw

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

Copy link
Copy Markdown
Collaborator

🔗 Linked issue

Related to #828 and #619

❓ Type of change

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

📚 Description

The v3 renderer is synchronous, but PromisesPlugin still used an async entries:resolve listener that Unhead could not await. Schema.org metadata resolution also accepted a Promise even though the result was consumed synchronously.

PromisesPlugin now runs synchronously, omits pending entries from the current pass, resolves their values in the background, and invalidates the client after they settle. A later server render can use the resolved value; inputs needed during the first SSR render should still be awaited upstream. Stale patch results are ignored and rejections can be retried.

Modern entrypoints keep Promise resolution opt-in. Legacy createHead and createServerHead continue registering PromisesPlugin for v2 compatibility. ValidatePlugin reports ignored Promise-returning hooks during development.

The migration and hook docs now match the synchronous contract. Tests cover legacy compatibility, listener ordering, client invalidation, later SSR renders, stale resolutions, rejected thenables, and dev-only warnings.

@harlan-zw harlan-zw mentioned this pull request Jul 15, 2026
1 of 6 tasks
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The synchronous hook pipeline now avoids awaiting promise-based listeners and promise entry resolution. Async hook returns emit a deduplicated per-head warning, while rejected entries remain eligible for retry. Schema.org resolution is explicitly synchronous.

Changes

Synchronous pipeline behavior

Layer / File(s) Summary
Synchronous hook contract and diagnostics
packages/schema-org/src/plugin.ts, packages/unhead/src/types/head.ts, packages/unhead/src/utils/hooks.ts, packages/unhead/test/unit/hooks/*
Schema.org resolution is synchronous, and thenable hook results produce one warning per head instance.
Non-blocking promise entry processing
packages/unhead/src/plugins/promises.ts, packages/unhead/test/unit/plugins/*
Promise entry resolution runs without delaying later listeners; fulfilled entries update their input, while rejected entries reset _promisesProcessed for retry.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SSRRender
  participant HookPipeline
  participant PromisesPlugin
  participant PromiseEntry
  participant Console

  SSRRender->>HookPipeline: resolve tags and entries synchronously
  HookPipeline->>PromisesPlugin: process entries
  PromisesPlugin->>PromiseEntry: start walkPromises
  HookPipeline-->>SSRRender: continue without awaiting
  PromiseEntry-->>PromisesPlugin: fulfillment or rejection
  PromisesPlugin->>PromisesPlugin: update input or reset processing flag
  HookPipeline->>Console: warn once for thenable hook listener
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 It clearly summarizes the main change: aligning Promise handling with synchronous rendering.
Description check ✅ Passed It includes linked issues, type of change, and a detailed description of the synchronous Promise-handling fix and related test/docs updates.
✨ 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/synchronous-hook-promises-split

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/schema-org/src/plugin.ts (1)

124-132: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Fix spreading a potential Promise in synchronous code.

The meta function is typed as returning Partial<MetaInput> | Promise<Partial<MetaInput>> (line 43). Now that this hook is synchronous, if meta?.() returns a Promise, spreading it with ... will spread the Promise object (resulting in an empty object or unintended behavior) instead of the resolved metadata.

If meta must support returning a Promise, you'll need to either resolve it before the synchronous pipeline begins (e.g. during a separate async initialization step) or update the contract so meta is strictly synchronous.

🤖 Prompt for 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.

In `@packages/schema-org/src/plugin.ts` around lines 124 - 132, The synchronous
'tags:resolve' hook must not spread the potentially asynchronous result of
meta?.(). Ensure metadata is resolved before this hook runs, or update the meta
contract and implementation to be strictly synchronous; then pass only resolved
metadata into graph.resolveGraph while preserving the existing merge with config
and resolvedMeta.
🧹 Nitpick comments (1)
packages/unhead/src/plugins/promises.ts (1)

36-37: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefer for...of when iterating over arrays.

ctx.entries is an array. Iterating over an array with for...in can iterate over unexpected enumerable properties and yields string indices, which is generally discouraged in favor of for...of.

♻️ Proposed refactor
-      for (const k in ctx.entries) {
-        const entry = ctx.entries[k]
+      for (const entry of ctx.entries) {
🤖 Prompt for 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.

In `@packages/unhead/src/plugins/promises.ts` around lines 36 - 37, Update the
iteration over the array ctx.entries to use for...of, binding each element
directly as entry instead of iterating string indices with for...in. Preserve
the existing processing inside the loop.
🤖 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.

Outside diff comments:
In `@packages/schema-org/src/plugin.ts`:
- Around line 124-132: The synchronous 'tags:resolve' hook must not spread the
potentially asynchronous result of meta?.(). Ensure metadata is resolved before
this hook runs, or update the meta contract and implementation to be strictly
synchronous; then pass only resolved metadata into graph.resolveGraph while
preserving the existing merge with config and resolvedMeta.

---

Nitpick comments:
In `@packages/unhead/src/plugins/promises.ts`:
- Around line 36-37: Update the iteration over the array ctx.entries to use
for...of, binding each element directly as entry instead of iterating string
indices with for...in. Preserve the existing processing inside the loop.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 19bde276-66d2-4987-9089-78806bb5ceee

📥 Commits

Reviewing files that changed from the base of the PR and between ea14841 and a6167c1.

📒 Files selected for processing (6)
  • packages/schema-org/src/plugin.ts
  • packages/unhead/src/plugins/promises.ts
  • packages/unhead/src/types/head.ts
  • packages/unhead/src/utils/hooks.ts
  • packages/unhead/test/unit/hooks/async-listener-warn.test.ts
  • packages/unhead/test/unit/plugins/promises.test.ts

@github-actions

github-actions Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

📦 Bundle Size

✅ No notable changes

All bundles (14)
Bundle Gzipped Brotli Raw
Core
Client (Minimal) 5.2 kB 4.7 kB 12.9 kB ✅
Client (Full) 8.6 kB 7.8 kB 22.1 kB ✅
Client (Self-Contained) 5.6 kB 5 kB 13.7 kB ✅
Server (Minimal) 4.7 kB 4.3 kB 11.8 kB ✅
Server (Self-Contained) 5.1 kB 4.5 kB 12.4 kB ✅
Vue
Vue Client (Minimal) 5.7 kB 5.2 kB 14 kB ✅
Vue Client (Full) 9.3 kB 8.5 kB 24.1 kB ✅
Vue Server (Minimal) 5.2 kB 4.7 kB 12.8 kB ✅
React
React Client (Minimal) 5.6 kB 5.1 kB 14 kB ✅
React Client (Full) 9.4 kB 8.5 kB 24.6 kB ✅
React Server (Minimal) 5 kB 4.5 kB 12.5 kB ✅
Schema.org
Schema.org (Minimal) 9.7 kB 8.8 kB 26.8 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)

⚠️ 1 slower · past the per-metric noise gate

Benchmark base → PR Δ
Schema.org cached allocated / render 144.6 KiB → 152.5 KiB 🔴 +7.8 KiB (+5.4%)
All benchmarks (14)
Benchmark PR Δ RME
SSR render (CPU) 0.399 ms ~ noise ±11.0%
SSR render (wall) 0.271 ms ~ noise ±5.9%
SSR allocated / render 258.1 KiB ~ noise —
Schema.org cached render (CPU) 0.351 ms ~ noise ±7.0%
Schema.org cached render (wall) 0.256 ms ~ noise ±2.5%
Schema.org cached allocated / render 152.5 KiB 🔴 +7.8 KiB (+5.4%) —
Streaming wrapStream drain (CPU) 0.244 ms ~ noise ±3.5%
Streaming wrapStream drain (wall) 0.151 ms ~ noise ±4.0%
Streaming allocated / drain 161.8 KiB ~ noise —
Streaming suspense chunk (CPU) 0.011 ms ~ noise ±2.5%
Streaming allocated / suspense chunk 4.6 KiB ~ noise —
CSR DOM mutations / nav 38 ~ noise —
CSR re-render (CPU) 0.822 ms ~ noise ±5.4%
CSR re-render (wall) 0.474 ms ~ noise ±2.3%

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

@harlan-zw

Copy link
Copy Markdown
Collaborator Author

The async meta() concern is valid, but it predates this PR. Before this change, schema.org's tags:resolve listener was async with no await; it invoked meta() and spread the result synchronously before returning its wrapper Promise, so Promise metadata was already ignored. This PR only removes that wrapper so later synchronous listeners are not deferred. Narrowing the public type would be breaking, while awaiting it would require changing Unhead's synchronous render contract, so that contract needs a separate schema.org change.

@harlan-zw harlan-zw changed the title fix(unhead): surface ignored async hook listeners fix(unhead)!: remove leftover promise input support Jul 15, 2026
@harlan-zw

Copy link
Copy Markdown
Collaborator Author

Follow-up to the earlier schema.org thread: after checking the v3 release and sync-engine PR, this branch now treats both leftovers as part of the same missed cleanup. The meta() contract is synchronous, and the obsolete PromisesPlugin path has been removed. The async-hook warning has also moved out of core and into ValidatePlugin only.

@harlan-zw harlan-zw changed the title fix(unhead)!: remove leftover promise input support fix(unhead)!: make promise resolution opt-in Jul 15, 2026
@harlan-zw

Copy link
Copy Markdown
Collaborator Author

Correction after reviewing the intended core/add-on boundary: PromisesPlugin should remain publicly available, but it must not rely on an async hook. The latest commit restores it as an explicit opt-in plugin, keeps it out of legacy/default entrypoints, and makes pending entries resolve outside the synchronous pipeline with deterministic client invalidation and later-render SSR behavior.

@harlan-zw harlan-zw changed the title fix(unhead)!: make promise resolution opt-in fix(unhead): align Promise handling with synchronous rendering Jul 19, 2026
@harlan-zw harlan-zw changed the title fix(unhead): align Promise handling with synchronous rendering fix(unhead): align Promise handling with sync rendering Jul 19, 2026
@harlan-zw
harlan-zw merged commit c594054 into main Jul 19, 2026
9 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Aug 11, 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