Skip to content

feat(server): experimental prepareTemplate - #830

Merged
harlan-zw merged 13 commits into
mainfrom
feat/prepared-templates
Jul 19, 2026
Merged

harlan-zw merged 13 commits into
mainfrom
feat/prepared-templates

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

Server and streaming template functions parse the same HTML on every request, even when a production integration reuses one built template. prepareTemplate(html) parses that template once and returns an immutable PreparedTemplate that can be shared across request-scoped head instances.

API

const template = prepareTemplate(await readFile('dist/client/index.html', 'utf8'))

// Per request
const html = transformHtmlTemplateRaw(head, template)

These functions now accept string | PreparedTemplate:

  • transformHtmlTemplate
  • transformHtmlTemplateRaw
  • renderSSRHeadShell
  • prepareStreamingTemplate
  • wrapStream, including the Vue, React, Solid, and Svelte wrappers

prepareTemplate and its type are exported from unhead/parser, unhead/server, unhead/stream/server, and the regular and streaming server entry points for all four framework packages. The prepared value is frozen and nominally typed. prepareTemplate and PreparedTemplate are marked @experimental; their public shape may change in a future minor release. transformHtmlTemplate caches its extraction parse and normalized static tags by prepared-object identity. Heads with hooks or dynamic resolvers receive a request-local input clone and skip the static fast path. Both derived caches use weak keys, contain no head or request state, and are released when callers drop the prepared value.

Streaming parser cleanup

prepareStreamingTemplate previously rebuilt its static outlet split and synthetic shell layout for every request. Prepared templates now keep that derived layout in a weak identity cache, while raw strings retain the existing per-call path. The optimized path derives shell indexes from the original parse. A 5,000-template fuzz test checks byte-for-byte parity with the previous implementation, including malformed input; the </body> before <body> case still uses the literal fallback.

Performance

bench/prepared-template.bench.ts uses a 104 KB template with about 105 head tags and a per-request head payload.

Function String per request Prepared once Speedup
transformHtmlTemplate 5,774 ops/s (173 µs) 21,616 ops/s (46 µs) 3.7x
transformHtmlTemplateRaw 18,360 ops/s (54 µs) 156,912 ops/s (6.4 µs) 8.6x
prepareStreamingTemplate 21,192 ops/s (47 µs) 338,702 ops/s (3.0 µs) 16.0x

Documentation and validation

The TypeScript, Vue, React, Solid, and Svelte streaming guides now show production reuse, require a request-scoped head instance, and explain the development invalidation rule: prepare after transformIndexHtml() and prepare again whenever the HTML changes.

  • 1,681 tests pass across 205 files; 8 are skipped
  • A compiled-output GC stress test retained no heap after 50,000 requests and finalized 500/500 short-lived prepared templates
  • 19 package export tests pass
  • All packages build
  • ESLint, vue-tsc, changed-doc Markdown lint, and case checks pass
  • All 48 checked entry points remain import-inert
  • attw passes for unhead, Vue, React, Solid, and Svelte

Summary by CodeRabbit

  • New Features
    • Added prepareTemplate() and PreparedTemplate for building a reusable, immutable template once, then reusing it for server rendering and streaming.
    • Updated server and streaming helpers (including framework adapters) to accept either a raw HTML string or a prepared template.
    • Added benchmarks comparing prepared vs raw template performance.
  • Documentation
    • Added “Reuse a Production Template” guidance for supported frameworks.
  • Bug Fixes
    • Improved request safety around per-request options/index handling.
  • Tests
    • Added unit tests for reuse, immutability, and parity, plus fuzzing coverage for streaming behavior.

…entries on failure

Two bug classes in the streaming SSR server helpers:

1. wrapStream drained the entire upstream inside start() regardless of
   downstream demand, had no cancel handler, and never propagated
   cancellation upstream. It now uses a standard pull/cancel
   implementation: the shell is enqueued once in start(), pull() reads at
   most one upstream chunk per downstream request, cancel(reason) is
   propagated to the upstream reader exactly once, and the reader is
   released on completion, cancellation, and failure. An upstream error
   errors the wrapped stream without emitting the closing suffix.
   Successful output remains byte-identical.

2. renderSSRHeadSuspenseChunk, renderSSRHeadShell, and
   prepareStreamingTemplate cleared head.entries before the output was
   safely produced, so a serialization failure (cyclic value, BigInt) or
   template failure lost the entries. They now clear only after the
   output is successfully produced; failures leave entries intact for
   retry and the original error propagates.
… read

cancel() clears the shared reader while pull() may still be awaiting
reader.read(); when the cancelled read resolves, pull would touch an
undefined reader and enqueue the closing suffix on a cancelled stream.
pull() now captures the reader locally and re-checks ownership after the
awaited read: if cancel() won the race it returns immediately, leaving
reader teardown to cancel().
Server and streaming template functions re-parsed the same HTML template on
every request. prepareTemplate(html) parses once and returns a
PreparedTemplate that owns the exact string its indexes describe, so stale
index/string pairs are unrepresentable. transformHtmlTemplate,
transformHtmlTemplateRaw, renderSSRHeadShell, prepareStreamingTemplate and
wrapStream (core + vue/react/solid/svelte wrappers) now accept
string | PreparedTemplate; string call sites are unchanged and byte-identical.

Also removes the synthetic second parse in prepareStreamingTemplate: the
shell indexes are derived from the original parse (shellPart is a prefix of
the template), with a fuzzed parity test locking byte-identical output
against the previous re-parse implementation, malformed inputs included.

~100KB template bench: transformHtmlTemplateRaw 8.7x, prepareStreamingTemplate
13.5x faster on the prepared path.
@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds immutable PreparedTemplate creation and reuse across server and streaming rendering, exposes the APIs through framework adapters, documents production usage, adds benchmarks, and validates output parity, immutability, reuse, and exports.

Changes

Prepared Template Reuse

Layer / File(s) Summary
Prepared template contract and rendering
packages/unhead/src/parser/index.ts, packages/unhead/src/server/*, packages/unhead/src/unhead.ts
Defines frozen prepared templates and lets server transformations reuse parsed indexes and cached extraction data.
Streaming template reuse
packages/unhead/src/stream/server.ts
Accepts prepared templates in shell rendering, streaming preparation, and stream wrapping while preserving streaming output behavior.
Framework adapter APIs
packages/{react,solid-js,svelte,vue}/src/{server.ts,stream/server.ts}
Re-exports preparation APIs and broadens framework streaming template parameters to `string
Export contract validation
test/exports/*.yaml
Adds prepareTemplate to parser, server, and streaming export fixtures.
Prepared template validation
packages/unhead/test/unit/server/*prepared-template*.test.ts
Tests immutability, raw/prepared output parity, repeated reuse, streaming behavior, and randomized streaming parity.
Prepared template usage documentation
docs/0.*/head/guides/1.core-concepts/5.streaming.md
Documents prepared template types, production reuse, and development re-preparation across supported integrations.
Prepared template benchmarks
bench/prepared-template.bench.ts
Benchmarks raw versus prepared processing for large templates in server and streaming scenarios.

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

Sequence Diagram(s)

sequenceDiagram
  participant Application
  participant prepareTemplate
  participant Head
  participant prepareStreamingTemplate
  participant wrapStream
  Application->>prepareTemplate: prepare index.html once
  prepareTemplate-->>Application: PreparedTemplate
  Application->>Head: create per-request head
  Application->>prepareStreamingTemplate: render with PreparedTemplate
  prepareStreamingTemplate->>wrapStream: provide prepared shell metadata
  wrapStream-->>Application: streamed HTML
Loading

Possibly related PRs

  • unjs/unhead#752: Modifies the same streaming template splitting and marker handling.
  • unjs/unhead#804: Modifies the Solid streaming wrapStream API and implementation.
  • unjs/unhead#827: Modifies streaming template preparation and head entry handling.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.17% 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 and directly reflects the main change: adding experimental prepareTemplate support.
Description check ✅ Passed The description follows the template sections and clearly explains the change, its API impact, and validation details.
✨ 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 feat/prepared-templates

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.

… core

Adversarial review findings:

- wrapStream: acquire the upstream reader in an async start() so a locked
  or invalid upstream yields an errored stream instead of a synchronous
  throw, and head.entries stay intact for retry on any start failure
- wrapStream: swallow upstream cancel() rejections (an errored upstream
  rejects with its stored error) so fire-and-forget cancellation cannot
  surface an unhandled rejection
- wrapStream: single cancel-race check in pull() via a tagged read result,
  skip enqueueing an empty end chunk, hoist the stateless TextEncoder
- renderSSRHeadSuspenseChunk: drop only unserializable entries on failure
  so one cyclic/BigInt input cannot poison every subsequent chunk render
- add an optional flushChunk hook to wrapStream and delete the Vue
  package's pre-fix fork of the implementation, so Vue streaming gets
  backpressure and cancellation propagation too
- dedupe shell construction shared by renderSSRHeadShell and the
  prepareStreamingTemplate no-split fallback
…prepared-templates

# Conflicts:
#	packages/unhead/src/stream/server.ts
# Conflicts:
#	packages/unhead/src/stream/server.ts
Keep prepared templates immutable and nominal so their parsed indexes cannot drift from the source HTML. Complete the framework exports and document when production templates can be reused safely.
@harlan-zw
harlan-zw changed the base branch from fix/stream-lifecycle to main July 19, 2026 01:11
@harlan-zw harlan-zw closed this Jul 19, 2026
@harlan-zw harlan-zw reopened this Jul 19, 2026
@github-actions

github-actions Bot commented Jul 19, 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.8 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)

✅ No significant change (within CI noise)

All benchmarks (14)
Benchmark PR Δ RME
SSR render (CPU) 0.407 ms ~ noise ±11.1%
SSR render (wall) 0.275 ms ~ noise ±6.0%
SSR allocated / render 258.2 KiB ~ noise —
Schema.org cached render (CPU) 0.373 ms ~ noise ±6.3%
Schema.org cached render (wall) 0.243 ms ~ noise ±2.9%
Schema.org cached allocated / render 144.5 KiB ~ noise —
Streaming wrapStream drain (CPU) 0.254 ms ~ noise ±3.5%
Streaming wrapStream drain (wall) 0.155 ms ~ noise ±3.9%
Streaming allocated / drain 162.2 KiB ~ noise —
Streaming suspense chunk (CPU) 0.011 ms ~ noise ±3.7%
Streaming allocated / suspense chunk 4.6 KiB ~ noise —
CSR DOM mutations / nav 38 ~ noise —
CSR re-render (CPU) 0.858 ms ~ noise ±5.3%
CSR re-render (wall) 0.479 ms ~ noise ±1.9%

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

@harlan-zw

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

🧹 Nitpick comments (1)
packages/unhead/src/server/transformHtmlTemplate.ts (1)

7-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Freeze the cached extracted template to protect shared state.

Since the extracted template is cached and reused across requests, consider freezing it (along with its input and indexes) before storing it in the WeakMap. This perfectly aligns with the immutability guarantees introduced in prepareTemplate and provides strong protection against downstream logic accidentally mutating shared state.

❄️ Proposed refactor
 function extractPreparedTemplate(template: PreparedTemplate): PreparedHtmlTemplateWithIndexes {
   const cache = extractedTemplates ||= new WeakMap()
   let extracted = cache.get(template)
   if (!extracted) {
     extracted = parseHtmlForUnheadExtraction(template.html)
+    Object.freeze(extracted.input)
+    Object.freeze(extracted.indexes)
+    Object.freeze(extracted)
     cache.set(template, extracted)
   }
   return extracted
 }
🤖 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/server/transformHtmlTemplate.ts` around lines 7 - 15,
Update extractPreparedTemplate so the result from parseHtmlForUnheadExtraction
is deeply frozen before being stored in the extractedTemplates WeakMap,
including its input and indexes fields. Preserve the existing cache lookup and
return behavior while ensuring all cached shared state is immutable.
🤖 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 `@docs/0.typescript/head/guides/1.core-concepts/5.streaming.md`:
- Around line 149-155: Change the wrapStream snippet to a declaration-style
TypeScript signature rather than a function invocation, preserving the existing
Unhead, ReadableStream, template, and return-type annotations so the API
reference is valid and copyable.

---

Nitpick comments:
In `@packages/unhead/src/server/transformHtmlTemplate.ts`:
- Around line 7-15: Update extractPreparedTemplate so the result from
parseHtmlForUnheadExtraction is deeply frozen before being stored in the
extractedTemplates WeakMap, including its input and indexes fields. Preserve the
existing cache lookup and return behavior while ensuring all cached shared state
is immutable.
🪄 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: 075df79a-0b7b-4af9-ac46-4263c0e15871

📥 Commits

Reviewing files that changed from the base of the PR and between 1d8b0e1 and 42e009c.

📒 Files selected for processing (25)
  • bench/prepared-template.bench.ts
  • docs/0.react/head/guides/1.core-concepts/5.streaming.md
  • docs/0.solid-js/head/guides/1.core-concepts/5.streaming.md
  • docs/0.svelte/head/guides/1.core-concepts/5.streaming.md
  • docs/0.typescript/head/guides/1.core-concepts/5.streaming.md
  • docs/0.vue/head/guides/1.core-concepts/5.streaming.md
  • packages/react/src/server.ts
  • packages/react/src/stream/server.ts
  • packages/solid-js/src/server.ts
  • packages/solid-js/src/stream/server.ts
  • packages/svelte/src/server.ts
  • packages/svelte/src/stream/server.ts
  • packages/unhead/src/parser/index.ts
  • packages/unhead/src/server/index.ts
  • packages/unhead/src/server/transformHtmlTemplate.ts
  • packages/unhead/src/stream/server.ts
  • packages/unhead/test/unit/server/prepare-streaming-template-parity.test.ts
  • packages/unhead/test/unit/server/prepared-template.test.ts
  • packages/vue/src/server.ts
  • packages/vue/src/stream/server.ts
  • test/exports/react.yaml
  • test/exports/solid-js.yaml
  • test/exports/svelte.yaml
  • test/exports/unhead.yaml
  • test/exports/vue.yaml

@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/unhead/src/server/transformHtmlTemplate.ts`:
- Around line 64-68: Update extractPreparedTemplate so the !extracted branch
reuses the existing prepared PreparedTemplate object directly instead of calling
parseHtmlForUnheadExtraction(prepared.html) or re-freezing its fields. Preserve
the existing extraction flow while relying on prepareTemplate()’s already-frozen
input and indexes.
🪄 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: f84831db-4785-4284-a5f7-e7ed4637035a

📥 Commits

Reviewing files that changed from the base of the PR and between 868232d and bcb7b56.

📒 Files selected for processing (11)
  • bench/prepared-template.bench.ts
  • docs/0.react/head/guides/1.core-concepts/5.streaming.md
  • docs/0.solid-js/head/guides/1.core-concepts/5.streaming.md
  • docs/0.svelte/head/guides/1.core-concepts/5.streaming.md
  • docs/0.typescript/head/guides/1.core-concepts/5.streaming.md
  • docs/0.vue/head/guides/1.core-concepts/5.streaming.md
  • packages/unhead/src/parser/index.ts
  • packages/unhead/src/server/transformHtmlTemplate.ts
  • packages/unhead/src/stream/server.ts
  • packages/unhead/src/unhead.ts
  • packages/unhead/test/unit/server/prepared-template.test.ts
🚧 Files skipped from review as they are similar to previous changes (9)
  • docs/0.vue/head/guides/1.core-concepts/5.streaming.md
  • docs/0.react/head/guides/1.core-concepts/5.streaming.md
  • docs/0.solid-js/head/guides/1.core-concepts/5.streaming.md
  • bench/prepared-template.bench.ts
  • docs/0.typescript/head/guides/1.core-concepts/5.streaming.md
  • packages/unhead/test/unit/server/prepared-template.test.ts
  • docs/0.svelte/head/guides/1.core-concepts/5.streaming.md
  • packages/unhead/src/parser/index.ts
  • packages/unhead/src/stream/server.ts

@harlan-zw harlan-zw changed the title feat(server): reusable prepared HTML templates via prepareTemplate feat(server): prepareTemplate Jul 19, 2026
@harlan-zw harlan-zw changed the title feat(server): prepareTemplate feat(server): experimental prepareTemplate Jul 19, 2026
@harlan-zw
harlan-zw merged commit 0b8cac8 into main Jul 19, 2026
9 checks passed
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