Skip to content

Commit 44f4b76

Browse files
ryansolidclaude
andcommitted
fix(web): hydrate() waits for the shell records when a stylesheet delays them (#3610)
A still-loading <link rel="stylesheet"> blocks every parser-inserted classic <script> after it, but not an `async` module entry, so hydrate() could run against the bootstrap's empty `_$HY.r`: a streamed <Loading> found neither its record nor its `_fr` declaration and fell through to the core boundary — a `Hydration key miss` on the fallback, a real client refetch, and a `$df` swap nobody claimed. Readiness gate on `_$HY`: - Server: `generateHydrationScript()` (hand-built documents, where the host places the bootstrap apart from the records script the render appends to its output) marks the bootstrap `p:1` — records may be parser-pending. `<HydrationScript />` omits it: assembleDocument splices the shell's records script immediately after it at `<!--xs-->`, so the two execute back to back and nothing can be pending between them. A hand-constructed `_$HY` keeps the same default: absent means ready. - Client: with the flag set, the parser still running, and no record landed, hydrate() parks its start on the first `_$HY.r` write (a Proxy that hands the object back on that write; the start rides a microtask so the whole records script is visible) or DOMContentLoaded — the parser finishing is the proof that no records script is coming. The dispose function is still returned synchronously and cancels a parked start. Post-load hydrate() (module/deferred entries) never waits. Size: +137 B / +129 B brotli on the two hydrating scenarios (web only, in hydrate() itself); caps 20.95 -> 21.10 KB and 31.2 -> 31.30 KB with dated ledger notes. Fixes #3610 Co-authored-by: Claude <[email protected]>
1 parent eb3d699 commit 44f4b76

7 files changed

Lines changed: 573 additions & 4 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
fix(web): `hydrate()` waits for the document's records when a stylesheet delays them (#3610)
6+
7+
A still-loading stylesheet blocks the classic records `<script>` but not an `async` module entry, so `hydrate()` could start against the bootstrap's empty `_$HY.r`: a streamed `<Loading>` fell through to a fresh boundary (a `Hydration key miss` on its fallback, a client refetch, a `$df` swap nobody claimed). `generateHydrationScript()` — hand-built documents, where the bootstrap and the records are placed apart — now marks the bootstrap `p:1`; with that flag, mid-parse, and no record landed, `hydrate()` parks its start until the first `_$HY.r` write or `DOMContentLoaded`. `<HydrationScript />` omits the flag (its records are spliced right after it), so JSX documents and post-load hydration are unchanged. The dispose function is still returned synchronously and cancels a parked start.

‎documentation/solid-2.0/12-ssr-http.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ Server (`@solidjs/web` under the `node`/`deno`/`worker` conditions):
2828

2929
For hydration, the document needs the hydration script ahead of the app markup: `generateHydrationScript({ nonce?, eventNames? })` returns it as a string for hand-built documents, and `<HydrationScript />` renders it in JSX documents.
3030

31+
The serialized hydration records (`_$HY.r`) are written by classic inline `<script>`s; a still-loading `<link rel="stylesheet">` blocks every parser-inserted classic script after it but not an `async` module entry, so `hydrate()` can run before the records have. `hydrate()` therefore has a readiness gate (#3610). In a JSX document the shell's records script is spliced immediately after `<HydrationScript />`, so the two can never be separated and hydration starts on the spot — with or without records, even mid-parse. A hand-built document places `generateHydrationScript()` itself, apart from the records script appended to the render output; its bootstrap declares that records may still be pending (`_$HY.p`), and when `hydrate()` runs while the parser is still working and no record has landed, it parks its start until the first record write or `DOMContentLoaded`, whichever comes first — the parser finishing is the proof that no records script is coming. Deferred and module (non-`async`) entries run after parsing and never wait; islands integrations that only ship the bootstrap and hydrate after load are unaffected. `hydrate()` still returns its dispose function synchronously, and disposing cancels a parked start.
32+
3133
### Consuming the stream: `pipe`, `pipeTo`, `readable`
3234

3335
`renderToStream` returns a result with three consumption surfaces — **exactly one may be used per render** (a second consumer throws with a directed message):

‎packages/web/src/client.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2065,6 +2065,12 @@ function loadModuleAssets(mapping) {
20652065
* Pass `options.renderId` to hydrate one of multiple roots emitted by a
20662066
* server render that used the same id.
20672067
*
2068+
* The start may be deferred: in a hand-built document (bootstrapped by
2069+
* `generateHydrationScript()`) whose records `<script>` has not run yet
2070+
* while the parser is still working, hydration begins once the records land
2071+
* or the parser finishes. The returned dispose is synchronous either way and
2072+
* cancels a deferred start.
2073+
*
20682074
* When the server renders a full document but the client hydrates only the
20692075
* app subtree, the server must give that subtree its own id namespace: wrap
20702076
* the document shell in `<NoHydration>` and re-enter with `<Hydration>`
@@ -2080,6 +2086,73 @@ export function hydrate(
20802086
export function hydrate(code, element, options = {}) {
20812087
enableHydration();
20822088
installHydrationRuntime();
2089+
const hy = globalThis._$HY;
2090+
// Readiness gate (#3610). The bootstrap of a hand-built document
2091+
// (`generateHydrationScript()`, `_$HY.p`) is placed by the host, apart from
2092+
// the records script the render appends to its output — so a stylesheet
2093+
// between them blocks the classic records script while an `async` module
2094+
// entry runs on arrival, and this call would claim against an empty
2095+
// `_$HY.r`: a streamed <Loading> finds neither its record nor its `_fr`
2096+
// declaration and falls through to a fresh boundary (key miss on the
2097+
// fallback, a client refetch, a `$df` swap nobody claims). The bootstrap
2098+
// cannot know whether records follow, but the parser can prove it either
2099+
// way: while `readyState` is "loading" a parser-inserted script may still
2100+
// be pending, and once the parser finishes none can be (the same proof the
2101+
// truncation sweep rests on). So with the flag set, mid-parse, and no
2102+
// record landed yet, park the start on whichever comes first — the first
2103+
// `_$HY.r` write (the records script executing; a microtask later, so the
2104+
// whole script's writes are visible to the claim walk) or
2105+
// `DOMContentLoaded`. The dispose function is still returned synchronously
2106+
// and cancels a parked start. Nothing else holds hydration open: a
2107+
// JSX document's `<HydrationScript />` omits the flag (its records are
2108+
// spliced right after it and cannot be separated from it), every post-load
2109+
// `hydrate()` sees the parser finished, and later `$df`/record scripts
2110+
// register into a runtime that is already live.
2111+
if (hy.p && !hy.done && document.readyState === "loading" && !hasRecords(hy.r)) {
2112+
const records = hy.r;
2113+
let started = false;
2114+
let disposer;
2115+
const release = () => {
2116+
hy.r = records;
2117+
document.removeEventListener("DOMContentLoaded", start);
2118+
};
2119+
const start = () => {
2120+
if (started) return;
2121+
started = true;
2122+
release();
2123+
disposer = hydrateRoot(code, element, options);
2124+
};
2125+
// The records script writes `_$HY.r[key]` statement by statement (and
2126+
// re-reads `_$HY.r` each time), so intercept only the first write and
2127+
// hand the bootstrap's own object straight back.
2128+
hy.r = new Proxy(records, {
2129+
set(target, key, value) {
2130+
target[key] = value;
2131+
if (hy.r !== target) {
2132+
hy.r = target;
2133+
queueMicrotask(start);
2134+
}
2135+
return true;
2136+
}
2137+
});
2138+
document.addEventListener("DOMContentLoaded", start, { once: true });
2139+
return () => {
2140+
if (!started) {
2141+
started = true;
2142+
release();
2143+
}
2144+
disposer && disposer();
2145+
};
2146+
}
2147+
return hydrateRoot(code, element, options);
2148+
}
2149+
2150+
function hasRecords(r) {
2151+
for (const key in r) return true;
2152+
return false;
2153+
}
2154+
2155+
function hydrateRoot(code, element, options) {
20832156
if (globalThis._$HY.done) return render(code, element, [...element.childNodes], options);
20842157
// #3081: the server splices useHead's charset/base prelude immediately
20852158
// after the <head> open tag — a byte-placement constraint (charset within

‎packages/web/src/server.ts‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3089,7 +3089,10 @@ export function HydrationScript(props: { nonce?: string; eventNames?: string[] }
30893089
// components
30903090
export function HydrationScript(props) {
30913091
const nonce = scriptNonce(sharedConfig.context && sharedConfig.context.nonce);
3092-
return ssr(generateHydrationScript({ nonce, ...props }));
3092+
// In-render: the shell's records are spliced right after this script (the
3093+
// `<!--xs-->` marker), so no `p` flag — see hydrationBootstrap.
3094+
const { eventNames = ["click", "input"], nonce: n } = { nonce, ...props };
3095+
return ssr(hydrationBootstrap(eventNames, n, false));
30933096
}
30943097
export function ssrGroup<T extends () => any[]>(fn: T, n: number): T;
30953098

@@ -4733,11 +4736,40 @@ export function generateHydrationScript(options?: {
47334736
}): string;
47344737

47354738
export function generateHydrationScript({ eventNames = ["click", "input"], nonce } = {}) {
4739+
return hydrationBootstrap(eventNames, nonce, true);
4740+
}
4741+
4742+
// The hydration bootstrap: `_$HY`, the client runtime's page-global.
4743+
// events — captured before hydration, replayed by the claim walk
4744+
// completed — elements whose replay is done
4745+
// r — the records: serialized hydration data, keyed by id,
4746+
// written by the render's classic <script>s
4747+
// fe — fragment-revealed hook, installed by the client
4748+
// p — records may be parser-pending (#3610). Set only by
4749+
// `generateHydrationScript()`: a hand-built document places
4750+
// this bootstrap itself, apart from the records script the
4751+
// render appends to its output, so a stylesheet between them
4752+
// can stall the records behind an `async` module entry.
4753+
// `hydrate()` then waits — while the parser is still running
4754+
// and no record has landed — for the first `_$HY.r` write or
4755+
// `DOMContentLoaded`, whichever comes first. `<HydrationScript />`
4756+
// omits it: `assembleDocument` splices the shell's records
4757+
// script immediately after this one at `<!--xs-->`, so the
4758+
// two execute back to back and nothing can be pending between
4759+
// them; a JSX document with no records hydrates on the spot,
4760+
// even mid-parse. Hosts that construct `_$HY` themselves get
4761+
// the same default: absent means ready.
4762+
// Later keys (`f`, `h`, `hp`, `dq`, `dlq`, `v`, `sc`, `sd`, `sg`, `done`,
4763+
// `modules`, `loading`) are installed by the stream's own scripts or the
4764+
// client runtime; see REPLACE_SCRIPT and HEAD_SCRIPT.
4765+
function hydrationBootstrap(eventNames, nonce, outOfBand) {
47364766
return `<script${
47374767
nonce ? ` nonce="${escape(String(nonce), true)}"` : ""
47384768
}>window._$HY||(e=>{let t=e=>e&&e.hasAttribute&&(e.hasAttribute("_hk")?e:t(e.host&&e.host.nodeType?e.host:e.parentNode));["${eventNames.join(
47394769
'","'
4740-
)}"].forEach((o=>document.addEventListener(o,(o=>{if(!e.events)return;let s=t(o.composedPath&&o.composedPath()[0]||o.target);s&&!e.completed.has(s)&&e.events.push([s,o])}))))})(_$HY={events:[],completed:new WeakSet,r:{},fe(){}});</script><!--xs-->`;
4770+
)}"].forEach((o=>document.addEventListener(o,(o=>{if(!e.events)return;let s=t(o.composedPath&&o.composedPath()[0]||o.target);s&&!e.completed.has(s)&&e.events.push([s,o])}))))})(_$HY={events:[],completed:new WeakSet,r:{},fe(){}${
4771+
outOfBand ? ",p:1" : ""
4772+
}});</script><!--xs-->`;
47414773
}
47424774

47434775
function queue(fn) {

0 commit comments

Comments
 (0)