| 1 | + | // Streamlined render entry for client-root projects. |
| 2 | + | // |
| 3 | + | // When the project's root is a "use client" module (i.e. the resolved root |
| 4 | + | // export is a registerClientReference proxy), we can skip the RSC flight |
| 5 | + | // pipeline entirely — there's no server tree to flatten, just a single |
| 6 | + | // client component reference. The SSR worker resolves the module from its |
| 7 | + | // id, builds a React.createElement(RootComponent, props) tree, and renders |
| 8 | + | // HTML directly. |
| 9 | + | // |
| 10 | + | // The render(Component, props, options) signature mirrors render-rsc.jsx |
| 11 | + | // so lib/dev/ssr-handler.mjs can swap the entryModule transparently. |
| 12 | + | |
| 13 | + | import { clientReferenceMap } from "@lazarv/react-server/dist/server/client-reference-map"; |
| 14 | + | |
| 15 | + | import { |
| 16 | + | context$, |
| 17 | + | ContextStorage, |
| 18 | + | getContext, |
| 19 | + | } from "@lazarv/react-server/server/context.mjs"; |
| 20 | + | import { init$ as revalidate$ } from "@lazarv/react-server/server/revalidate.mjs"; |
| 21 | + | import { |
| 22 | + | CLIENT_MODULES_CONTEXT, |
| 23 | + | CONFIG_CONTEXT, |
| 24 | + | CONFIG_ROOT, |
| 25 | + | HTTP_CONTEXT, |
| 26 | + | HTTP_HEADERS, |
| 27 | + | HTTP_RESPONSE, |
| 28 | + | HTTP_STATUS, |
| 29 | + | IMPORT_MAP, |
| 30 | + | LOGGER_CONTEXT, |
| 31 | + | MAIN_MODULE, |
| 32 | + | POSTPONE_STATE, |
| 33 | + | PRELUDE_HTML, |
| 34 | + | REDIRECT_CONTEXT, |
| 35 | + | RENDER_CONTEXT, |
| 36 | + | RENDER_STREAM, |
| 37 | + | REQUEST_CACHE_SHARED, |
| 38 | + | SCROLL_RESTORATION_MODULE, |
| 39 | + | STYLES_CONTEXT, |
| 40 | + | } from "@lazarv/react-server/server/symbols.mjs"; |
| 41 | + | |
| 42 | + | const REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"); |
| 43 | + | |
| 44 | + | /** |
| 45 | + | * Render a client-root React app, skipping the RSC flight pipeline. |
| 46 | + | * |
| 47 | + | * `Component` must be a registerClientReference proxy (the export of a |
| 48 | + | * "use client" module). Detection happens upstream in ssr-handler.mjs; |
| 49 | + | * this entry is only loaded when that condition holds. |
| 50 | + | * |
| 51 | + | * @param {object} Component - The client reference proxy |
| 52 | + | * @param {object} props - Props to pass to the client root |
| 53 | + | * @param {object} options - Reserved (middlewareError propagation) |
| 54 | + | * @returns {Promise<Response>} |
| 55 | + | */ |
| 56 | + | // Root components never receive props — the client-root path is identity- |
| 57 | + | // only ("here is the component, render it"). The signature still accepts |
| 58 | + | // `props` so it can be plugged into the same dispatch (lib/dev/ssr-handler.mjs |
| 59 | + | // passes `{}` either way), but the value is ignored end-to-end. |
| 60 | + | export async function render(Component, _props = {}, options = {}) { |
| 61 | + | const logger = getContext(LOGGER_CONTEXT); |
| 62 | + | const renderStream = getContext(RENDER_STREAM); |
| 63 | + | const config = getContext(CONFIG_CONTEXT)?.[CONFIG_ROOT] ?? {}; |
| 64 | + | const context = getContext(HTTP_CONTEXT); |
| 65 | + | const renderContext = getContext(RENDER_CONTEXT); |
| 66 | + | const importMap = getContext(IMPORT_MAP); |
| 67 | + | |
| 68 | + | // Hard guard: this entry should only be reached for client references. |
| 69 | + | // If something upstream went wrong (config drift, plugin pipeline issue), |
| 70 | + | // fail loudly rather than silently producing broken HTML. |
| 71 | + | if (Component?.$$typeof !== REACT_CLIENT_REFERENCE) { |
| 72 | + | throw new Error( |
| 73 | + | "render-ssr.jsx requires a client reference root; received " + |
| 74 | + | "non-client component. This is a runtime invariant violation — " + |
| 75 | + | "client-root detection in ssr-handler.mjs should have routed " + |
| 76 | + | "this request through render-rsc.jsx instead." |
| 77 | + | ); |
| 78 | + | } |
| 79 | + | if (options?.middlewareError) { |
| 80 | + | throw options.middlewareError; |
| 81 | + | } |
| 82 | + | |
| 83 | + | revalidate$(); |
| 84 | + | |
| 85 | + | const [moduleId, exportNameRaw] = String(Component.$$id).split("#"); |
| 86 | + | const exportName = exportNameRaw || "default"; |
| 87 | + | |
| 88 | + | // Worker payload uses the workspace-path id — server/render-dom.mjs's |
| 89 | + | // serverRequireModule(id) prepends "client://" and resolves through |
| 90 | + | // ssrLoadModule, which is the SSR environment's module runner. The SSR |
| 91 | + | // environment leaves "use client" modules untransformed, so this gives |
| 92 | + | // us the real component function. Root components never receive props, |
| 93 | + | // so the worker spec is just (id, name). |
| 94 | + | const workerSpec = { id: moduleId, name: exportName }; |
| 95 | + | |
| 96 | + | // Browser-facing id comes from the same client-reference-map the RSC |
| 97 | + | // path uses to encode flight references — single source of truth for |
| 98 | + | // the "$$id → browser URL" mapping (handles dev no-manifest, prod |
| 99 | + | // manifest, package specifiers, and base-href / origin transforms). |
| 100 | + | const refMap = clientReferenceMap(); |
| 101 | + | const refDef = refMap[Component.$$id]; |
| 102 | + | const browserId = normalizeBrowserUrl(refDef?.id || moduleId); |
| 103 | + | |
| 104 | + | // The browser-facing spec is the bare `${id}#${name}` string entry.client.jsx |
| 105 | + | // splits and dynamic-imports. No props envelope — the contract is "here is |
| 106 | + | // the component, render it". The worker emits it verbatim into a JS string |
| 107 | + | // literal, with the `</script>` escape applied at the emit site. |
| 108 | + | const browserSpec = `${browserId}#${exportName}`; |
| 109 | + | |
| 110 | + | // ── .rsc.x-component requests ─────────────────────────────────────────── |
| 111 | + | // Navigation prefetch / Refresh / Link triggered .rsc.x-component fetches |
| 112 | + | // expect a flight payload. Synthesize the minimal two-row flight that an |
| 113 | + | // RSC render of a single client reference would produce, so the wire |
| 114 | + | // format stays stable for client-side consumers. Props are always empty. |
| 115 | + | if (renderContext?.flags?.isRSC && !renderContext?.flags?.isRemote) { |
| 116 | + | const flight = |
| 117 | + | `1:I[${JSON.stringify(refDef?.id || moduleId)},[],${JSON.stringify(exportName)}]\n` + |
| 118 | + | `0:["$","$L1",null,{}]\n`; |
| 119 | + | const headers = new Headers({ |
| 120 | + | "content-type": "text/x-component; charset=utf-8", |
| 121 | + | "cache-control": |
| 122 | + | context.request.headers.get("cache-control") === "no-cache" |
| 123 | + | ? "no-cache" |
| 124 | + | : "must-revalidate", |
| 125 | + | }); |
| 126 | + | const response = new Response(flight, { status: 200, headers }); |
| 127 | + | context$(HTTP_RESPONSE, response); |
| 128 | + | return response; |
| 129 | + | } |
| 130 | + | |
| 131 | + | // Only HTML / remote-HTML requests reach the SSR worker path. |
| 132 | + | if (!(renderContext?.flags?.isHTML || renderContext?.flags?.isRemote)) { |
| 133 | + | return new Response(null, { status: 404, statusText: "Not Found" }); |
| 134 | + | } |
| 135 | + | |
| 136 | + | // ── HTML request: render via SSR worker with clientRoot payload ───────── |
| 137 | + | |
| 138 | + | const styles = getContext(STYLES_CONTEXT) ?? []; |
| 139 | + | const clientModules = getContext(CLIENT_MODULES_CONTEXT) ?? []; |
| 140 | + | // Ensure the root module itself is preloaded so the bootstrap doesn't |
| 141 | + | // pay an extra RTT after entry.client.jsx executes. |
| 142 | + | if (!clientModules.includes(browserId)) { |
| 143 | + | clientModules.unshift(browserId); |
| 144 | + | } |
| 145 | + | context$(CLIENT_MODULES_CONTEXT, clientModules); |
| 146 | + | |
| 147 | + | let configModulePreload = config.modulePreload ?? true; |
| 148 | + | if (typeof configModulePreload === "function") { |
| 149 | + | configModulePreload = await configModulePreload(); |
| 150 | + | } |
| 151 | + | |
| 152 | + | const isDev = import.meta.env?.DEV ?? false; |
| 153 | + | |
| 154 | + | const lastModified = new Date().toUTCString(); |
| 155 | + | const prevHeaders = getContext(HTTP_HEADERS); |
| 156 | + | context$( |
| 157 | + | HTTP_HEADERS, |
| 158 | + | new Headers({ |
| 159 | + | "content-type": "text/html; charset=utf-8", |
| 160 | + | "cache-control": |
| 161 | + | context.request.headers.get("cache-control") === "no-cache" |
| 162 | + | ? "no-cache" |
| 163 | + | : "must-revalidate", |
| 164 | + | "last-modified": lastModified, |
| 165 | + | ...(prevHeaders ? Object.fromEntries(prevHeaders.entries()) : {}), |
| 166 | + | }) |
| 167 | + | ); |
| 168 | + | |
| 169 | + | let resolveResponse; |
| 170 | + | const responsePromise = new Promise((r) => (resolveResponse = r)); |
| 171 | + | context$(HTTP_RESPONSE, responsePromise); |
| 172 | + | |
| 173 | + | // Indirection so the start callback never closes directly over the |
| 174 | + | // `const stream = await renderStream(...)` TDZ binding. In inline-channel |
| 175 | + | // (edge) mode `worker.postMessage` is synchronous, so the start handler |
| 176 | + | // can be queued as a microtask BEFORE the await continuation drains and |
| 177 | + | // assigns `stream`. Awaiting `streamReady` inside start defers the read |
| 178 | + | // until we explicitly resolve it after the assignment — independent of |
| 179 | + | // microtask ordering. |
| 180 | + | let resolveStreamReady; |
| 181 | + | const streamReady = new Promise((r) => { |
| 182 | + | resolveStreamReady = r; |
| 183 | + | }); |
| 184 | + | |
| 185 | + | return new Promise(async (resolve, reject) => { |
| 186 | + | try { |
| 187 | + | const contextStore = ContextStorage.getStore(); |
| 188 | + | const { onPostponed, prerender } = context; |
| 189 | + | const prelude = getContext(PRELUDE_HTML); |
| 190 | + | const postponed = getContext(POSTPONE_STATE); |
| 191 | + | const scrollRestorationModule = getContext(SCROLL_RESTORATION_MODULE); |
| 192 | + | |
| 193 | + | const stream = await renderStream({ |
| 194 | + | // Discriminator: tells the worker to skip the flight decode path |
| 195 | + | // and build the React tree from this spec directly. See |
| 196 | + | // server/render-dom.mjs createRenderer for the consume side. |
| 197 | + | clientRoot: workerSpec, |
| 198 | + | // Browser-facing spec entry.client.jsx splits + dynamic-imports. |
| 199 | + | // Bare `${id}#${name}` string. The worker is the single owner of |
| 200 | + | // serialization (escapes `</script>` and emits the JS literal). |