diff --git a/.changeset/errored-nested-loading-preflush-fallback.md b/.changeset/errored-nested-loading-preflush-fallback.md new file mode 100644 index 000000000..04aa3227e --- /dev/null +++ b/.changeset/errored-nested-loading-preflush-fallback.md @@ -0,0 +1,8 @@ +--- +"solid-js": patch +"@solidjs/web": patch +--- + +During `renderToStream`, an `` whose `` fails before the shell is sent now draws its error fallback in the shell even when the `` is not all of its content: markup between them (`
`), a sibling beside the ``, or another `` inside the ``. The fallback replaces the ``'s whole content, as a client render shows it, and the error is serialized at the ``, so the hydrating client adopts that markup without asking again and recovers when the content's inputs change (#4287). The server error hook hears `fallback`. Before, the shell kept the content with the failed ``'s position empty (`` for ``), and the fallback appeared only once the client hydrated, or never without JavaScript. The same applies to the awaited form (`await renderToStream(...)`). + +The fallback is drawn only when it is ready as it renders; the shell never waits for it. A fallback with an async or client-only hole, or one that throws with no `` above it, leaves the shell as before: the client renders the failure, and the hook hears `client`. So does an `` whose markup has no place of its own in the shell: one that put no element and no `` placeholder into the page (text alone, or nothing), or that was itself never inserted. A fallback that throws inside an outer `` is that boundary's failure, drawn in the shell the same way. When the hook maps the error to another value, a fallback that reads the error is rendered again with that value; if that second render throws or is not ready, nothing is drawn, although the hook has already heard `fallback`. Whatever the replaced content still had pending goes with it. A `` still pending inside it streams nothing, and its head tags (`useHead`) never reach the document head, whether they come from a settled `` or from the content itself. A later failure inside the replaced content is still reported to the hook as `client`. After the shell has been sent, a nested `` failure still streams an empty fragment and the client renders the failure, as before. diff --git a/documentation/solid-2.0/12-ssr-http.md b/documentation/solid-2.0/12-ssr-http.md index a20b1ab83..d89c491a5 100644 --- a/documentation/solid-2.0/12-ssr-http.md +++ b/documentation/solid-2.0/12-ssr-http.md @@ -199,7 +199,7 @@ renderToStream(code, { onError }); handleServerFunctionRequest(request, { onError }); ``` -- **Called once per error object per `kind` per request, at first sight** (per render when no request is in scope — never once per process: an error object reused across requests is heard, and mapped, by each), with where the failure was met. A direct server-function call that throws during SSR inside an `` is heard twice, as `server-function` and then as `render`, so `kind: "render"` alone tells you a render failed; the wire value is the first one the hook returned. `kind: "render"` — `fallback` (an `` rendered its fallback; `boundary` is its hydration id and `boundaryPath` its component labels — where the error was **met** — while `ownerPath` is where it was **thrown**, the labels up the owner chain it escaped, when the compiler emitted them), `client` (a `` fragment rejected, the client re-renders the subtree — unless the `` is all of an ``'s content: that `` draws its fallback into the fragment, reports `fallback`, and the hydrating client adopts it, [#4287](https://github.com/solidjs/solid/issues/4287)), `failed` (nothing contained it; the request fails — including a synchronous throw out of `renderToString` or `renderToStream`'s first pass, reported before it reaches the caller), `serialize` (a hydration value would not serialize — reported for a render that passed `onError`, as seroval's own `onError` always was. With the default serializer, synchronous and asynchronous failures follow the same rule **before the first flush** ([#4709](https://github.com/solidjs/solid/issues/4709)) — an awaited `renderToStream`, or a stream whose shell has not gone out — the render **fails** like a rejection there: nothing is sent, `onCompleteAll` does not fire, and the hook hears only `serialize`; **after the first flush** (midstream, where the response cannot be failed cleanly) the key — and any promise or async iterable inside its value that already went out — rejects on the client with an error that says the value could not be serialized and names the key, so the reading computation throws into the nearest ``, whose fallback replaces the server's content until `reset()` or an input change reruns it as a client fetch — uncaught like any rejected key with no `` above — and the render completes ([#4647](https://github.com/solidjs/solid/issues/4647)). A synchronous failure after the first flush still completes the render: the value is omitted if nothing of it was published, or rejected if part of it already went out ([#4227](https://github.com/solidjs/solid/issues/4227)). An error an `` contained is not such a value. When the default serializer cannot encode it (a field it cannot serialize, kept by the dev tier's fidelity, by `markSafeError` or by a hook's mapping), its record and the rejection of the source it came from, `deferStream` or streamed, are sent as a plain `Error` with its message: the fallback stays and the render completes, every record of the same error carries the same replacement, and the hook hears `serialize` once. A rejection no `` contained is a value like any other and fails the render before the first flush. A custom `serializer`'s late failure is its own to settle; the render completes. `renderToString` refuses async values outright, so it has no late case). `kind: "server-function"` — `thrown` (the body threw; `functionId`, and `direct: true` for an in-process call during SSR) or `channel` (a rejection or throw escaping through the result graph, the head already committed). `kind: "request"` is always `failed`: a failure that fails the request outside any render or server function the runtime reports (a middleware throw, a setup step), reported by the framework's request handler through `reportRequestFailure(error, event)`. A render failure, synchronous throws included, is reported as `render`, so a handler that catches one and passes it to `reportRequestFailure` adds nothing. It has no per-request tier, so only the ambient hook hears it. `event` is the request, when the failure happened inside one, and always for `kind: "request"`. +- **Called once per error object per `kind` per request, at first sight** (per render when no request is in scope — never once per process: an error object reused across requests is heard, and mapped, by each), with where the failure was met. A direct server-function call that throws during SSR inside an `` is heard twice, as `server-function` and then as `render`, so `kind: "render"` alone tells you a render failed; the wire value is the first one the hook returned. `kind: "render"` — `fallback` (an `` rendered its fallback; `boundary` is its hydration id and `boundaryPath` its component labels — where the error was **met** — while `ownerPath` is where it was **thrown**, the labels up the owner chain it escaped, when the compiler emitted them), `client` (a `` fragment rejected, the client re-renders the subtree — unless the `` is all of an ``'s content: that `` draws its fallback into the fragment, reports `fallback`, and the hydrating client adopts it, [#4287](https://github.com/solidjs/solid/issues/4287). Before the shell is sent, an `` with other content around the `` does the same in the shell, its fallback in place of all that content, when the fallback is ready without waiting and the `` put an element or a `` placeholder of its own into the page), `failed` (nothing contained it; the request fails — including a synchronous throw out of `renderToString` or `renderToStream`'s first pass, reported before it reaches the caller), `serialize` (a hydration value would not serialize — reported for a render that passed `onError`, as seroval's own `onError` always was. With the default serializer, synchronous and asynchronous failures follow the same rule **before the first flush** ([#4709](https://github.com/solidjs/solid/issues/4709)) — an awaited `renderToStream`, or a stream whose shell has not gone out — the render **fails** like a rejection there: nothing is sent, `onCompleteAll` does not fire, and the hook hears only `serialize`; **after the first flush** (midstream, where the response cannot be failed cleanly) the key — and any promise or async iterable inside its value that already went out — rejects on the client with an error that says the value could not be serialized and names the key, so the reading computation throws into the nearest ``, whose fallback replaces the server's content until `reset()` or an input change reruns it as a client fetch — uncaught like any rejected key with no `` above — and the render completes ([#4647](https://github.com/solidjs/solid/issues/4647)). A synchronous failure after the first flush still completes the render: the value is omitted if nothing of it was published, or rejected if part of it already went out ([#4227](https://github.com/solidjs/solid/issues/4227)). An error an `` contained is not such a value. When the default serializer cannot encode it (a field it cannot serialize, kept by the dev tier's fidelity, by `markSafeError` or by a hook's mapping), its record and the rejection of the source it came from, `deferStream` or streamed, are sent as a plain `Error` with its message: the fallback stays and the render completes, every record of the same error carries the same replacement, and the hook hears `serialize` once. A rejection no `` contained is a value like any other and fails the render before the first flush. A custom `serializer`'s late failure is its own to settle; the render completes. `renderToString` refuses async values outright, so it has no late case). `kind: "server-function"` — `thrown` (the body threw; `functionId`, and `direct: true` for an in-process call during SSR) or `channel` (a rejection or throw escaping through the result graph, the head already committed). `kind: "request"` is always `failed`: a failure that fails the request outside any render or server function the runtime reports (a middleware throw, a setup step), reported by the framework's request handler through `reportRequestFailure(error, event)`. A render failure, synchronous throws included, is reported as `render`, so a handler that catches one and passes it to `reportRequestFailure` adds nothing. It has no per-request tier, so only the ambient hook hears it. `event` is the request, when the failure happened inside one, and always for `kind: "request"`. - **The return is the wire value**: rendered into the fallback, serialized for hydration, sent as the RPC error. `undefined` leaves the default policy in place (generic outside dev, fidelity in dev). A returned value is the author's intent — like a `wrapInvocation` mapping — and is not sanitized again; `markSafeError` is not needed on it. Ignored for `failed`, which has no wire, and for `serialize`, whose only wire — the midstream key rejection ([#4647](https://github.com/solidjs/solid/issues/4647)) — is the fixed message naming the key, never the serializer's error or a mapping of it. One road a mapping does not reach: a rejected async source's serialized rejection is encoded the moment the source rejects, ahead of the boundary, and carries the default policy's value; the hydrating client renders from the boundary's record, which carries the mapping. - **Once means once across roads.** A direct server-function call that throws during SSR is met first by the invocation (`kind: "server-function"`, `direct: true`) and then by the `` that contains it; the boundary reuses the verdict — the same replacement in the fallback and the record — and does not report again. A `` re-pull recurring the same throw is the same object, the same verdict. The observe tier keeps the multi-event picture (an `"invocation"` record _and_ an `SSR_RENDER_ERROR_CONTAINED` finding) for consumers that want it. - **Two tiers, as `wrapInvocation` has.** Ambient: `configureServerErrors({ onError })`, once per process, registered on `globalThis` under a registered symbol so a bundled server build and an instrumented `--import`ed module share it — and the only tier that sees direct in-process calls. Per request, overriding it: `onError` on `renderToStream`/`renderToString`, and on `handleServerFunctionRequest` for the call it dispatches. A throwing hook is reported on the console and treated as silent. With no hook anywhere, a failure that fails the request goes to `console.error` — never silent. A synchronous render throw is the exception: it is rethrown to the caller, whose own handling (or `reportRequestFailure`) decides. diff --git a/packages/solid/src/server/hydration.ts b/packages/solid/src/server/hydration.ts index 3cf4185ac..22590a1af 100644 --- a/packages/solid/src/server/hydration.ts +++ b/packages/solid/src/server/hydration.ts @@ -392,7 +392,8 @@ function ssrLoadingBoundary( // twin draws it, its error serialized at the Errored id so the hydrating // client adopts that markup; otherwise nothing — the blank the client // twin renders fresh over (`hydratedCreateLoadingBoundary`'s rejected - // arm). Inside one + // arm), unless the shell is still held, where an enclosing `` + // draws in place of its own markup (`failFragment`). Inside one // (frames-rulings 3.3, A0 corollary 4 inward — the position shows what the // SERVER rendered for the outcome, never a blank, never a client-invented // state; there is no twin): the nearest server ``'s fallback for @@ -446,6 +447,23 @@ function ssrLoadingBoundary( outcomeRendered = true; return true; } + // Before the shell is handed to the sink, with nothing drawn at this + // position: an enclosing `` whose markup is in the shell + // meets the failure there when its fallback is finished as it + // renders, the fallback in place of that markup and of whatever sits + // between the two boundaries, as on the client (#4287). Settled first, + // as above. Not met: the paths below, where settling again changes + // nothing. + if (!outcome && parentHandler && ctx.shell && ctx.shell.open) { + done!(undefined, err); + // Met only by a boundary that contained it: one that absorbs it + // (its subtree already discarded) leaves it reported as before. + const contained = ctx.shell.contained; + if (parentHandler(err, ESCALATE) === true && ctx.shell.contained !== contained) { + outcomeRendered = true; + return true; + } + } if (report && !outcomeRendered) { reportServerError( err, diff --git a/packages/solid/src/server/shared.ts b/packages/solid/src/server/shared.ts index f5fa6c483..4167ffbf6 100644 --- a/packages/solid/src/server/shared.ts +++ b/packages/solid/src/server/shared.ts @@ -1,5 +1,5 @@ import { getOwner, getNextChildId, getContext, devPeekNextChildId } from "./signals.js"; -import type { Context } from "./signals.js"; +import type { Context, ShellContainer } from "./signals.js"; import type { BoundaryEvent } from "./observe.js"; import type { NavigationRef, Observe } from "@solidjs/signals"; @@ -140,6 +140,11 @@ export type HydrationContext = { * renderToStream. */ flushed?: () => boolean; + /** + * @internal The shell while the renderer still holds it (see + * `ShellContainer`). Set by @solidjs/web's renderToStream. + */ + shell?: ShellContainer; /** * @internal Per-request memo of `resolveAssets(moduleUrl)` results, keyed * by moduleUrl. lazy() consults it so a component re-created across diff --git a/packages/solid/src/server/signals.ts b/packages/solid/src/server/signals.ts index ce84de9c1..4bd90ea22 100644 --- a/packages/solid/src/server/signals.ts +++ b/packages/solid/src/server/signals.ts @@ -3764,10 +3764,12 @@ export type BoundaryOutcome = * `` fallback failing while the server waits for it. Each handler * meets it if its region can still change, else passes it up: a `` * whose fragment is still pending fails it (as a failure in its own pass - * does); an `` whose markup sits raw in such a fragment draws its - * fallback there (`FragmentContainer.region`), or, still pending itself, - * on its next pull. A boundary whose subtree is already discarded absorbs - * it. Answered `undefined` from the root: nothing could meet it. Not part + * does); an `` whose markup sits raw in such a fragment, or in the + * shell the renderer still holds (a fallback finished as it renders only), + * draws its fallback there + * (`FragmentContainer.region`, `ShellContainer.region`), or, still pending + * itself, on its next pull. A boundary whose subtree is already discarded + * absorbs it. Answered `undefined` from the root: nothing could meet it. Not part * of the public API (the server entry does not export it). */ export const ESCALATE: unique symbol = Symbol("escalate") as any; @@ -3784,6 +3786,30 @@ export type FragmentContainer = { open: boolean; region(from: string, to: string | (() => Promise), err: any): void; }; +/** + * The shell as the `` boundaries rendered into it see it, while the + * renderer still holds it (`open`, until it is handed to the sink): an + * `` whose finished markup it `has` takes its finished fallback in + * place of that markup (`region`), as in a pending `` fragment. + * It `has` only markup with a place of its own: carrying a hydration key or + * a `` placeholder, and found once. + * `drop` releases what the subtree under an owner id left pending — its + * fragments, its serialized values, its head registrations — once its + * markup is out of the page (`region` drops the replaced content's) or was + * never put in it (a fallback rendered and not drawn); with `rerun`, only + * the head registrations, for a subtree about to render again at the same + * ids. Never waits: a fallback not finished when it renders is not drawn + * here. + * @internal + */ +export type ShellContainer = { + open: boolean; + /** How many failures the render's `` boundaries have contained. */ + readonly contained: number; + has(from: string): boolean; + region(from: string, to: string, scope: string | undefined): void; + drop(scope: string, rerun?: boolean): void; +}; const containers = /* @__PURE__ */ new WeakMap(); /** @internal A registered ``'s content owner and its fragment. */ export function setFragmentContainer(owner: Owner, container: FragmentContainer | null): void { @@ -4273,14 +4299,11 @@ export function createErrorBoundary( } return resolved; }; - const renderFallback = (err: any) => + const renderFallback = (err: any, read?: () => void) => ctx ? runWithOwner(parent!, () => { return runWithOwner(outputOwner!, () => - fallback( - () => err, - () => {} - ) + fallback(read ? () => (read(), err) : () => err, () => {}) ); }) : fallback( @@ -4378,7 +4401,10 @@ export function createErrorBoundary( // #4287) this boundary answers only when that Loading's placeholder is // all of its content: the fallback then lands where the client twin draws // it, and the error serialized here lets it adopt that markup. Deeper in - // the content it answers nothing — the client renders the failure fresh. + // the content it answers nothing: before the shell is handed to the sink + // the failure is then handed up (`ESCALATE`) and, the fallback finished as + // it renders, drawn in the shell in place of this boundary's markup + // (`drawInShell`); otherwise the client renders the failure fresh. // Asked by a `` (outside a server component), a fallback still // resolving answers with a function instead: called, it waits out the // fallback's holes and answers with the finished markup (or `undefined`, @@ -4429,36 +4455,42 @@ export function createErrorBoundary( // #4316), met as the boundary's own pull would meet it: the fallback in // place of this boundary's markup. Still pending itself, the boundary is // pulled again and shows it then; finished, rendered raw into a fragment - // still pending, the fallback takes its markup's place in that fragment - // (drawn as an outcome is: waited for, its error serialized once it is - // finished, its own failure the next boundary's). Already showing the - // fallback, it absorbs the failure. Otherwise — the markup is out, or its - // fallback failed — the next boundary up meets it. + // still pending, the fallback takes its markup's place there (drawn as an + // outcome is: waited for, its error serialized once it is finished, its + // own failure the next boundary's); in the shell the renderer still holds + // (#4287), see `drawInShell`. Already showing the fallback, it absorbs the + // failure. Otherwise — the markup is out, or its fallback failed — the + // next boundary up meets it. const escalated = (err: any, up: BoundaryErrorHandler | null): BoundaryOutcome => { if (ctx && !fallbackFailed) { if (fallbackSettled) return true; if (pending || pulling) return (handleError(err), true); const from = markup(); - const container = from !== undefined && fragmentContainer(parent); - if (container) { - const to = drawFallback(err, undefined, up); - if (fallbackFailed) return to; - container.region(from!, to as string | (() => Promise), err); - return true; + if (from !== undefined) { + const fragment = fragmentContainer(parent); + if (fragment) { + const to = drawFallback(err, undefined, up) as + | string + | (() => Promise); + if (fallbackFailed) return to; + fragment.region(from, to, err); + return true; + } + const shell = ctx.shell; + // The shell held and no fragment pending above: not drawn here (its + // fallback unfinished, its markup not found — not inserted, or with + // no place of its own), the failure is not an outer boundary's + // either: this one meets it on the client. + if (shell && shell.open && !fragmentContainer(parent, true)) + return shellDrawable && shell.has(from) ? drawInShell(err, up, shell, from) : undefined; } } return up ? up(err, ESCALATE) : undefined; }; - // Renders the fallback for `err` as an outcome (`outcome`: the asking - // position) or in place of this boundary's markup (`undefined`). - const drawFallback = ( - err: any, - outcome: true | string | undefined, - parentHandler: BoundaryErrorHandler | null - ): BoundaryOutcome => { - // A hole of the fallback that throws while it renders reaches the - // fallback owner's handler first: hold it for `escalate` instead of - // letting the parent handler route it from here. + // A hole of the fallback that throws while it renders reaches the + // fallback owner's handler first: hold it for `escalate` instead of + // letting the parent handler route it from here. + const intercept = (parentHandler: BoundaryErrorHandler | null) => { if (parentHandler && !interceptor) { interceptor = true; setContext( @@ -4470,22 +4502,120 @@ export function createErrorBoundary( outputOwner ); } + }; + // Rendered from a resume loop, where the render context the compiled + // template reads has long moved past this boundary's: restore it. + const inCtx = (run: () => any, fail: (e: any) => void) => { + const prevCtx = sharedConfig.context; + sharedConfig.context = ctx; + answering = true; + try { + return run(); + } catch (e) { + if (!(e instanceof NotReadyError)) fail(e); + } finally { + answering = false; + sharedConfig.context = prevCtx; + } + }; + // Whether this boundary may still draw in the held shell: not once its + // fallback rendered unfinished there. + let shellDrawable = true; + // The fallback in place of this boundary's finished markup in the shell + // the renderer still holds (#4287), only when it is finished as it + // renders: the shell never waits for it. Rendered first with the error's + // default wire value, the hook not yet told: it hears `fallback` once the + // fallback is drawn (re-rendered when its mapping changes a value the + // fallback read), and nothing from here otherwise — the failing + // `` then reports `client`, and what the unfinished fallback + // started is dropped (`ShellContainer.drop`), never retried. Its own + // failure is the next boundary's (#4316); met there, so is the content's. + const drawInShell = ( + err: any, + up: BoundaryErrorHandler | null, + shell: ShellContainer, + from: string + ): BoundaryOutcome => { + intercept(up); + const scope = ownerId(outputOwner!); let failed: { e: any } | undefined; - // Rendered from a resume loop, where the render context the compiled - // template reads has long moved past this boundary's: restore it. - const inCtx = (run: () => any) => { - const prevCtx = sharedConfig.context; - sharedConfig.context = ctx; - answering = true; + let read = false; + let result: any; + let wire: any; + let reported = false; + const render = (value: any): string | undefined => { + read = false; + // Its registrations (head tags, assets) are the shell's, not the + // failing fragment's this runs under. + const boundary = ctx!._currentBoundaryId; + ctx!._currentBoundaryId = null; + let resolved: any; try { - return run(); - } catch (e) { - if (!(e instanceof NotReadyError)) failed = { e }; + resolved = inCtx( + () => ctx!.resolve(ctx!.escape((result = renderFallback(value, () => (read = true))))), + e => (failed = { e }) + ); } finally { - answering = false; - sharedConfig.context = prevCtx; + ctx!._currentBoundaryId = boundary; } + if (failed || !resolved || (resolved.h && resolved.h.length)) return; + return Array.isArray(resolved.t) ? resolved.t[0] : resolved.t; + }; + // `rerun`: rendered again at the same ids, where what the first render + // started (a `` of the fallback's, a serialized value) is + // joined, not made again: only its head registrations go. + const undo = (rerun?: boolean) => { + resetOwnerForRerun(outputOwner!); + if (scope !== undefined) shell.drop(scope, rerun); + }; + const report = () => { + reported = true; + reportContained(err); + wire = ssrSanitizeError( + err, + owner, + { kind: "render", handling: "fallback", boundary: boundaryId }, + ctx!.errorPolicy, + ctx!._errorScope + ); + if (ctx!.contained) ctx!.contained(err, wire); }; + const provisional = ssrSanitizeError(err, owner, undefined, undefined, ctx!._errorScope); + let to = render(provisional); + if (to !== undefined) { + report(); + if (read && wire !== provisional) { + undo(true); + to = render(wire); + } + if (to !== undefined) { + shell.region(from, to, boundaryId); + serializeError(wire); + fallbackResult = result; + fallbackSettled = true; + return true; + } + } + undo(); + if (failed) { + fallbackFailed = true; + const met = up ? up(failed.e, ESCALATE) : undefined; + if (met === true && !reported) report(); + return met; + } + shellDrawable = false; + return undefined; + }; + // Renders the fallback for `err` as an outcome (`outcome`: the asking + // position) or in place of this boundary's markup (`undefined`). + const drawFallback = ( + err: any, + outcome: true | string | undefined, + parentHandler: BoundaryErrorHandler | null + ): BoundaryOutcome => { + intercept(parentHandler); + let failed: { e: any } | undefined; + const inCtxHere = (run: () => any) => inCtx(run, e => (failed = { e })); const finish = (resolved: any) => { if (!resolved || (resolved.h && resolved.h.length)) return; if (deferredWire) (serializeError(deferredWire), (deferredWire = undefined)); @@ -4508,7 +4638,7 @@ export function createErrorBoundary( const met = parentHandler(e, ESCALATE); if (outcome === undefined) return met; }; - let resolved: any = inCtx(() => ctx!.resolve(ctx!.escape(handleError(err, true)))); + let resolved: any = inCtxHere(() => ctx!.resolve(ctx!.escape(handleError(err, true)))); if (failed) return escalate(); if (outcome === true || !resolved || !resolved.h || !resolved.h.length) return finish(resolved); disposed ||= new Promise(r => @@ -4522,7 +4652,7 @@ export function createErrorBoundary( if (torn) return; // Under the fallback's owner, as it rendered: a hole failing now // meets the handler a sync throw did. - resolved = inCtx(() => + resolved = inCtxHere(() => runWithOwner(outputOwner!, () => ctx!.ssr(resolved.t, ...resolved.h)) ); if (failed) { diff --git a/packages/web/src/server.ts b/packages/web/src/server.ts index 2fac6a84f..4aea11240 100644 --- a/packages/web/src/server.ts +++ b/packages/web/src/server.ts @@ -936,7 +936,7 @@ function registerPreloadLink(tracking, headRegistry, link, nonce) { function createHeadRegistry() { return { - pending: [], // { boundary, tags: [raw descriptor (+ peeked link rel)] } + pending: [], // { boundary, scope, tags: [raw descriptor (+ peeked link rel)] } committed: [], // { seq, tags: [{ tag, props, identity }] } in commit order seq: 0, uniq: 0, @@ -953,6 +953,10 @@ function createHeadRegistry() { // pre-shell by construction). function registerHeadTags(registry, context, tracking, emitResource, nonce, tags) { const boundary = context._currentBoundaryId || ""; + // The registering owner's id: a subtree dropped from the shell drops its + // registrations by it (`dropSubtree`). + const owner = getOwner(); + const scope = owner ? owner.id : undefined; if (typeof tags === "function") { // Reactive group: membership resolves at the boundary's flush, the same // moment as prop getters — component-level grouping composes its list @@ -963,6 +967,7 @@ function registerHeadTags(registry, context, tracking, emitResource, nonce, tags // that is mid-flush is an ordering hazard, so gating is skipped. registry.pending.push({ boundary, + scope, list: tags, resource: (desc, rel) => emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel) @@ -1026,7 +1031,7 @@ function registerHeadTags(registry, context, tracking, emitResource, nonce, tags ); } } - if (replaceable) registry.pending.push({ boundary, tags: replaceable }); + if (replaceable) registry.pending.push({ boundary, scope, tags: replaceable }); } // Shell-attempt readiness pass for root-owned head registrations (called by @@ -2840,16 +2845,13 @@ export function renderToStream(code, options = {}) { // client re-renders that subtree from scratch, and a consumer watching // request cost wants to know how much was thrown away. A leaf fragment's // failure alone is the render error's own finding, not this one. - const abandonSubtree = (key, error) => { - // A boundary created where no owner id was current (inside an async - // memo's continuation, #4242) registers under an undefined key. It is - // nobody's descendant and has no addressable subtree of its own; reading - // its length would turn one fragment's failure into a whole-request one. - if (key == null) return; + // Releases the fragments and serialized values still pending under `key` + // (its descendants; `self`: `key` too). Returns how many of each. + const releaseSubtree = (key, self) => { let fragments = 0; let serialized = 0; for (const [k, entry] of registry) { - if (k != null && k.length > key.length && k.startsWith(key)) { + if (k != null && (self || k.length > key.length) && k.startsWith(key)) { registry.delete(k); entry.resolve(); fragments++; @@ -2873,6 +2875,15 @@ export function renderToStream(code, options = {}) { // that triggers the fresh render) and the read computes. A frame sink // has no reader for these records. if (unregister.length && !options.sink) pushTask(unregister.join(";")); + return { fragments, serialized }; + }; + const abandonSubtree = (key, error) => { + // A boundary created where no owner id was current (inside an async + // memo's continuation, #4242) registers under an undefined key. It is + // nobody's descendant and has no addressable subtree of its own; reading + // its length would turn one fragment's failure into a whole-request one. + if (key == null) return; + const { fragments, serialized } = releaseSubtree(key, false); if ("_SOLID_OBSERVE_" && (fragments || serialized)) emitFinding( { @@ -2888,6 +2899,18 @@ export function renderToStream(code, options = {}) { null ); }; + // A subtree whose markup the page does not have (`context.shell.drop`): + // nothing streams for it, and its head registrations — under a fragment + // of it, or made by its owners outside any — never commit, as a client + // render that never shows it registers none (#4287). + const dropSubtree = (scope, rerun) => { + if (!scope) return; + if (!rerun) releaseSubtree(scope, true); + const under = key => typeof key === "string" && key.startsWith(scope); + headRegistry.pending = headRegistry.pending.filter( + reg => !under(reg.boundary) && !under(reg.scope) + ); + }; const writeTasks = () => { if (tasks.length && !completed && firstFlushed) { buffer.write(`${tasks}`); @@ -2931,10 +2954,38 @@ export function renderToStream(code, options = {}) { // over a shell suspension keeps the boundary's placeholder in its own // retry state, out of `html`. Spliced in when a root-hole re-pull lands it. let parkedInlines = null; - function inlineFragment(key, value) { + // `splices`: how the fragment's settled children went into `value`. + function inlineFragment(key, value, splices) { if (rootHoles && !html.includes(`