Skip to content

Commit 01e80a6

Browse files
fix(web): the hydration payload owns the rejections of the records it files (#3769) (#3803)
An async read that rejected under <Errored> still raised unhandledrejection in the browser: its record is in the inline payload, the promise seroval builds for it rejects, and the client never reads a record under a boundary that showed its fallback (nor one keyed outside any boundary, e.g. a router query cache key). A handler attached later only revokes the report. The bootstrap's _$HY.r now attaches a no-op rejection handler to each promise as it is assigned; a consumer reading the record still sees the rejection. Co-authored-by: Cursor <[email protected]>
1 parent b07fed5 commit 01e80a6

3 files changed

Lines changed: 154 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
The hydration bootstrap marks every promise the inline payload files under `_$HY.r` as handled when it lands, so a serialized async read that rejected under an `<Errored>` (which already rendered its fallback) no longer raises `unhandledrejection` in the browser. A consumer reading the record still receives the rejection.

‎packages/web/src/server.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5654,12 +5654,17 @@ export function generateHydrationScript(options?: {
56545654
eventNames?: string[];
56555655
}): string;
56565656

5657+
// `r` owns every promise the payload files under it the moment it lands
5658+
// (#3769): a record the client never reads — under an <Errored> that showed
5659+
// its fallback, or keyed outside any boundary — would otherwise raise
5660+
// `unhandledrejection` from the inline script alone, and a handler attached
5661+
// later only revokes the report. A consumer still meets the rejection.
56575662
export function generateHydrationScript({ eventNames = ["click", "input"], nonce } = {}) {
56585663
return `<script${
56595664
nonce ? ` nonce="${escape(String(nonce), true)}"` : ""
56605665
}>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(
56615666
'","'
5662-
)}"].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-->`;
5667+
)}"].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:new Proxy({},{set:(r,k,v)=>(v instanceof Promise&&v.catch(()=>{}),r[k]=v,!0)}),fe(){}});</script><!--xs-->`;
56635668
}
56645669

56655670
function queue(fn) {
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* #3769 — an async read that rejects under `<Errored>`: the boundary renders
5+
* its fallback and serializes the error, but the source's own record is in
6+
* the inline payload too, and the promise the payload builds for it rejects
7+
* with nothing attached. The browser raised `unhandledrejection` from the
8+
* inline script alone, for an error a boundary already handled.
9+
*
10+
* The payload runs here the way a browser runs it — the real bootstrap
11+
* (`HydrationScript`) and every inline script, in their own realm — with
12+
* this test owning the process's `unhandledRejection` listeners, so a leak
13+
* from the payload fails THIS test.
14+
*/
15+
import vm from "node:vm";
16+
import { describe, expect, test } from "vitest";
17+
import { HydrationScript, renderToStream, Errored, Loading } from "@solidjs/web";
18+
import { createMemo } from "solid-js";
19+
20+
const delay = (ms: number) => new Promise(r => setTimeout(r, ms));
21+
22+
async function watchRejections(run: () => Promise<void> | void) {
23+
const previous = process.listeners("unhandledRejection");
24+
process.removeAllListeners("unhandledRejection");
25+
const escaped: unknown[] = [];
26+
const capture = (reason: unknown) => escaped.push(reason);
27+
process.on("unhandledRejection", capture);
28+
try {
29+
await run();
30+
for (let turn = 0; turn < 4; turn++) await delay(20);
31+
return escaped;
32+
} finally {
33+
process.off("unhandledRejection", capture);
34+
for (const listener of previous) process.on("unhandledRejection", listener as any);
35+
}
36+
}
37+
38+
/** Runs the document's inline scripts in a fresh realm; returns its `_$HY`. */
39+
function runPayload(html: string) {
40+
const sandbox: any = {
41+
document: { getElementById: () => null, addEventListener() {} }
42+
};
43+
sandbox.window = sandbox.self = sandbox;
44+
vm.createContext(sandbox);
45+
for (const [, src] of html.matchAll(/<script[^>]*>([\s\S]*?)<\/script>/g)) {
46+
vm.runInContext(src, sandbox);
47+
}
48+
return sandbox._$HY;
49+
}
50+
51+
function useRead(ms: number) {
52+
return createMemo(async () => {
53+
await delay(ms);
54+
throw new Error("boom");
55+
});
56+
}
57+
58+
function Read(props: { ms: number }) {
59+
const value = useRead(props.ms);
60+
return <p>{value()}</p>;
61+
}
62+
63+
function Page(props: { children: any }) {
64+
return (
65+
<html>
66+
<head>
67+
<HydrationScript />
68+
</head>
69+
<body>{props.children}</body>
70+
</html>
71+
);
72+
}
73+
74+
async function render(code: () => any) {
75+
let html = "";
76+
await new Promise<void>(end =>
77+
renderToStream(code).pipe({ write: (c: unknown) => void (html += String(c)), end } as any)
78+
);
79+
return html;
80+
}
81+
82+
describe("#3769 a rejection an <Errored> handled", () => {
83+
test("rejecting before the shell raises no unhandled rejection from the payload", async () => {
84+
let html = "";
85+
const escaped = await watchRejections(async () => {
86+
html = await render(() => (
87+
<Page>
88+
<Errored fallback={<p>fallback</p>}>
89+
<Read ms={0} />
90+
</Errored>
91+
</Page>
92+
));
93+
expect(html).toMatch(/<p[^>]*>fallback<\/p>/);
94+
expect(html).toMatch(/_\$HY\.r\[/);
95+
runPayload(html);
96+
});
97+
expect(escaped).toEqual([]);
98+
});
99+
100+
test("rejecting after the shell, under a <Loading>, raises none either", async () => {
101+
let html = "";
102+
const escaped = await watchRejections(async () => {
103+
html = await render(() => (
104+
<Page>
105+
<Loading fallback={<p>loading</p>}>
106+
<Errored fallback={<p>fallback</p>}>
107+
<Read ms={30} />
108+
</Errored>
109+
</Loading>
110+
</Page>
111+
));
112+
expect(html).toMatch(/<p[^>]*>fallback<\/p>/);
113+
runPayload(html);
114+
});
115+
expect(escaped).toEqual([]);
116+
});
117+
118+
test("a consumer reading the record still sees the rejection", async () => {
119+
let seen: unknown;
120+
const escaped = await watchRejections(async () => {
121+
const html = await render(() => (
122+
<Page>
123+
<Errored fallback={<p>fallback</p>}>
124+
<Read ms={0} />
125+
</Errored>
126+
</Page>
127+
));
128+
const hy = runPayload(html);
129+
const records = Object.values(hy.r).filter(
130+
(v: any) => v && typeof v.then === "function"
131+
) as Promise<unknown>[];
132+
expect(records.length).toBeGreaterThan(0);
133+
await delay(0);
134+
seen = await Promise.allSettled(records);
135+
});
136+
expect(escaped).toEqual([]);
137+
expect(
138+
(seen as PromiseSettledResult<unknown>[]).some(
139+
r => r.status === "rejected" && (r.reason as Error).message === "boom"
140+
)
141+
).toBe(true);
142+
});
143+
});

0 commit comments

Comments
 (0)