Repository navigation
feat(server): experimental prepareTemplate - #830
Conversation
…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.
📝 WalkthroughWalkthroughAdds immutable ChangesPrepared Template Reuse
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
… 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.
📦 Bundle Size✅ No notable changes All bundles (14)
⚡ Performance (directional)✅ No significant change (within CI noise) All benchmarks (14)
Baseline: main @ 1d8b0e1 · 2026-07-19 · gzipped is the headline size metric · perf is directional (shared-runner, gated) |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/unhead/src/server/transformHtmlTemplate.ts (1)
7-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winFreeze the cached extracted template to protect shared state.
Since the
extractedtemplate is cached and reused across requests, consider freezing it (along with itsinputandindexes) before storing it in theWeakMap. This perfectly aligns with the immutability guarantees introduced inprepareTemplateand 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
📒 Files selected for processing (25)
bench/prepared-template.bench.tsdocs/0.react/head/guides/1.core-concepts/5.streaming.mddocs/0.solid-js/head/guides/1.core-concepts/5.streaming.mddocs/0.svelte/head/guides/1.core-concepts/5.streaming.mddocs/0.typescript/head/guides/1.core-concepts/5.streaming.mddocs/0.vue/head/guides/1.core-concepts/5.streaming.mdpackages/react/src/server.tspackages/react/src/stream/server.tspackages/solid-js/src/server.tspackages/solid-js/src/stream/server.tspackages/svelte/src/server.tspackages/svelte/src/stream/server.tspackages/unhead/src/parser/index.tspackages/unhead/src/server/index.tspackages/unhead/src/server/transformHtmlTemplate.tspackages/unhead/src/stream/server.tspackages/unhead/test/unit/server/prepare-streaming-template-parity.test.tspackages/unhead/test/unit/server/prepared-template.test.tspackages/vue/src/server.tspackages/vue/src/stream/server.tstest/exports/react.yamltest/exports/solid-js.yamltest/exports/svelte.yamltest/exports/unhead.yamltest/exports/vue.yaml
There was a problem hiding this comment.
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
📒 Files selected for processing (11)
bench/prepared-template.bench.tsdocs/0.react/head/guides/1.core-concepts/5.streaming.mddocs/0.solid-js/head/guides/1.core-concepts/5.streaming.mddocs/0.svelte/head/guides/1.core-concepts/5.streaming.mddocs/0.typescript/head/guides/1.core-concepts/5.streaming.mddocs/0.vue/head/guides/1.core-concepts/5.streaming.mdpackages/unhead/src/parser/index.tspackages/unhead/src/server/transformHtmlTemplate.tspackages/unhead/src/stream/server.tspackages/unhead/src/unhead.tspackages/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
prepareTemplate
prepareTemplateprepareTemplate
🔗 Linked issue
N/A
❓ Type of 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 immutablePreparedTemplatethat can be shared across request-scoped head instances.API
These functions now accept
string | PreparedTemplate:transformHtmlTemplatetransformHtmlTemplateRawrenderSSRHeadShellprepareStreamingTemplatewrapStream, including the Vue, React, Solid, and Svelte wrappersprepareTemplateand its type are exported fromunhead/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.prepareTemplateandPreparedTemplateare marked@experimental; their public shape may change in a future minor release.transformHtmlTemplatecaches 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
prepareStreamingTemplatepreviously 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.tsuses a 104 KB template with about 105 head tags and a per-request head payload.transformHtmlTemplatetransformHtmlTemplateRawprepareStreamingTemplateDocumentation 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.vue-tsc, changed-doc Markdown lint, and case checks passattwpasses forunhead, Vue, React, Solid, and SvelteSummary by CodeRabbit
prepareTemplate()andPreparedTemplatefor building a reusable, immutable template once, then reusing it for server rendering and streaming.