@warlock.js/web 5.1.0 → 5.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +182 -0
- package/README.md +126 -12
- package/esm/build/contribution.d.mts +10 -13
- package/esm/build/contribution.mjs +45 -57
- package/esm/build/contribution.mjs.map +1 -1
- package/esm/build/discover-pages.mjs +104 -44
- package/esm/build/discover-pages.mjs.map +1 -1
- package/esm/build/generate-client-registry.mjs +46 -12
- package/esm/build/generate-client-registry.mjs.map +1 -1
- package/esm/build/generate-pages-barrel.mjs +54 -12
- package/esm/build/generate-pages-barrel.mjs.map +1 -1
- package/esm/build/page-default-export.mjs +48 -0
- package/esm/build/page-default-export.mjs.map +1 -0
- package/esm/build/page-routes-manifest.mjs +21 -0
- package/esm/build/page-routes-manifest.mjs.map +1 -0
- package/esm/build/public-files.mjs +45 -0
- package/esm/build/public-files.mjs.map +1 -0
- package/esm/build/read-route-exports.mjs.map +1 -1
- package/esm/client/build-hydrated-tree.mjs +39 -8
- package/esm/client/build-hydrated-tree.mjs.map +1 -1
- package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
- package/esm/client/navigation/prefetch.mjs.map +1 -1
- package/esm/client/runtime/index.d.mts +2 -1
- package/esm/client/runtime/index.mjs +2 -1
- package/esm/client/runtime/manifest.mjs +2 -1
- package/esm/client/runtime/manifest.mjs.map +1 -1
- package/esm/client/runtime/matcher.d.mts +12 -0
- package/esm/client/runtime/matcher.mjs +12 -0
- package/esm/client/runtime/matcher.mjs.map +1 -1
- package/esm/client/runtime/types.d.mts +14 -1
- package/esm/components/document-context.d.mts +39 -1
- package/esm/components/document-context.mjs.map +1 -1
- package/esm/components/link.mjs.map +1 -1
- package/esm/components/scripts.mjs +3 -1
- package/esm/components/scripts.mjs.map +1 -1
- package/esm/context.d.mts +5 -101
- package/esm/hydration-payload.d.mts +1 -1
- package/esm/hydration-payload.mjs +36 -7
- package/esm/hydration-payload.mjs.map +1 -1
- package/esm/index.d.mts +3 -2
- package/esm/loaders.d.mts +6 -35
- package/esm/props.d.mts +15 -7
- package/esm/route.d.mts +1 -16
- package/esm/routing/filesystem-route.mjs +45 -0
- package/esm/routing/filesystem-route.mjs.map +1 -0
- package/esm/routing/layout-policy.mjs.map +1 -1
- package/esm/routing/query-string.mjs.map +1 -1
- package/esm/routing/route-table.mjs.map +1 -1
- package/esm/runtime/register-modules.d.mts +19 -0
- package/esm/runtime/register-modules.mjs +22 -0
- package/esm/runtime/register-modules.mjs.map +1 -0
- package/esm/server/build-hydration-payload.mjs +1 -0
- package/esm/server/build-hydration-payload.mjs.map +1 -1
- package/esm/server/create-page-module-loader.mjs +1 -0
- package/esm/server/create-page-module-loader.mjs.map +1 -1
- package/esm/server/create-page-route-handler.d.mts +30 -5
- package/esm/server/create-page-route-handler.mjs +127 -42
- package/esm/server/create-page-route-handler.mjs.map +1 -1
- package/esm/server/dev-server.mjs +1 -12
- package/esm/server/dev-server.mjs.map +1 -1
- package/esm/server/error-page.d.mts +14 -0
- package/esm/server/error-page.mjs +39 -0
- package/esm/server/error-page.mjs.map +1 -0
- package/esm/server/execute-page-request.d.mts +6 -3
- package/esm/server/execute-page-request.mjs +78 -79
- package/esm/server/execute-page-request.mjs.map +1 -1
- package/esm/server/execute-page-request.types.d.mts +32 -91
- package/esm/server/hydration-client-url.mjs +1 -1
- package/esm/server/index.d.mts +5 -5
- package/esm/server/index.mjs +3 -4
- package/esm/server/install-page-routes-from-manifest.d.mts +16 -6
- package/esm/server/install-page-routes-from-manifest.mjs +70 -9
- package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
- package/esm/server/install-page-routes.d.mts +31 -14
- package/esm/server/install-page-routes.mjs +90 -38
- package/esm/server/install-page-routes.mjs.map +1 -1
- package/esm/server/install-production-page-routes.mjs +2 -35
- package/esm/server/install-production-page-routes.mjs.map +1 -1
- package/esm/server/match-page-route.mjs +1 -1
- package/esm/server/match-page-route.mjs.map +1 -1
- package/esm/server/not-found-page.mjs +1 -1
- package/esm/server/not-found-page.mjs.map +1 -1
- package/esm/server/page-context.d.mts +2 -8
- package/esm/server/page-context.mjs +2 -15
- package/esm/server/page-context.mjs.map +1 -1
- package/esm/server/page-file-change.mjs +77 -0
- package/esm/server/page-file-change.mjs.map +1 -0
- package/esm/server/page-manifest.d.mts +24 -9
- package/esm/server/page-manifest.mjs.map +1 -1
- package/esm/server/page-render-bundle.mjs +38 -0
- package/esm/server/page-render-bundle.mjs.map +1 -0
- package/esm/server/page-route-reload.mjs +54 -0
- package/esm/server/page-route-reload.mjs.map +1 -0
- package/esm/server/register-production-public-files.mjs +40 -0
- package/esm/server/register-production-public-files.mjs.map +1 -0
- package/esm/server/render-page.d.mts +10 -13
- package/esm/server/render-page.mjs +153 -27
- package/esm/server/render-page.mjs.map +1 -1
- package/esm/server/resolve-page-metadata.mjs +1 -1
- package/esm/server/resolve-page-metadata.mjs.map +1 -1
- package/esm/server/settle-page-response.d.mts +58 -1
- package/esm/server/settle-page-response.mjs +110 -45
- package/esm/server/settle-page-response.mjs.map +1 -1
- package/esm/server/stylesheet-urls.d.mts +40 -29
- package/esm/server/stylesheet-urls.mjs +136 -51
- package/esm/server/stylesheet-urls.mjs.map +1 -1
- package/esm/server/unregistered-pages.mjs +42 -0
- package/esm/server/unregistered-pages.mjs.map +1 -0
- package/esm/server/web-connector-factory.d.mts +1 -2
- package/esm/server/web-connector-factory.mjs +6 -5
- package/esm/server/web-connector-factory.mjs.map +1 -1
- package/esm/server/web-connector.mjs +137 -17
- package/esm/server/web-connector.mjs.map +1 -1
- package/esm/shared.d.mts +17 -2
- package/esm/shared.mjs +2 -6
- package/esm/shared.mjs.map +1 -1
- package/esm/vite/build-client.mjs +1 -1
- package/esm/vite/build-client.mjs.map +1 -1
- package/esm/vite/gate-a-resolve.mjs +66 -12
- package/esm/vite/gate-a-resolve.mjs.map +1 -1
- package/esm/vite/gate-b-secrets.mjs +34 -16
- package/esm/vite/gate-b-secrets.mjs.map +1 -1
- package/esm/vite/gate-c-verify.mjs +5 -5
- package/esm/vite/gate-c-verify.mjs.map +1 -1
- package/esm/vite/hydration-entries.mjs +1 -1
- package/esm/vite/hydration-entries.mjs.map +1 -1
- package/esm/vite/index.d.mts +8 -5
- package/esm/vite/index.mjs +123 -10
- package/esm/vite/index.mjs.map +1 -1
- package/esm/vite/page-registry-plugin.d.mts +21 -2
- package/esm/vite/page-registry-plugin.mjs +47 -13
- package/esm/vite/page-registry-plugin.mjs.map +1 -1
- package/esm/vite/projection.d.mts +1 -1
- package/esm/vite/projection.mjs +37 -14
- package/esm/vite/projection.mjs.map +1 -1
- package/llms-full.txt +220 -56
- package/llms.txt +5 -3
- package/package.json +3 -3
- package/skills/add-web-to-an-app/SKILL.md +3 -3
- package/skills/create-a-page/SKILL.md +117 -10
- package/skills/load-page-data/SKILL.md +92 -12
- package/skills/navigate-on-the-client/SKILL.md +1 -1
- package/skills/serve-styles/SKILL.md +13 -12
- package/skills/use-layouts/SKILL.md +14 -8
- package/skills/write-the-root/SKILL.md +3 -1
- package/esm/server/buffered-response.d.mts +0 -58
- package/esm/server/buffered-response.mjs +0 -115
- package/esm/server/buffered-response.mjs.map +0 -1
|
@@ -1,11 +1,26 @@
|
|
|
1
1
|
import { DocumentContext, PAYLOAD_SCRIPT_ID, escapePayload } from "../components/document-context.mjs";
|
|
2
|
+
import { markNonHydrating } from "./page-render-bundle.mjs";
|
|
3
|
+
import { registerModules } from "../runtime/register-modules.mjs";
|
|
2
4
|
import DefaultApp from "../components/default-app.mjs";
|
|
3
5
|
import { buildHydrationPayload } from "./build-hydration-payload.mjs";
|
|
6
|
+
import { ERROR_PAGE_METADATA } from "./resolve-page-metadata.mjs";
|
|
7
|
+
import { hydrationErrorPageProps, resolveErrorPageMetadata } from "./error-page.mjs";
|
|
4
8
|
import { buildErrorRecord, designateBoundary } from "./settle-page-response.mjs";
|
|
5
9
|
import { executePageRequest } from "./execute-page-request.mjs";
|
|
6
10
|
import { createElement } from "react";
|
|
11
|
+
import { Response } from "@warlock.js/core";
|
|
7
12
|
|
|
8
13
|
//#region ../web/src/server/render-page.ts
|
|
14
|
+
/** Reads the stage 7 commit into the lowercased header map `RenderedPage` carries. */
|
|
15
|
+
function committedHeaders(bundle) {
|
|
16
|
+
const headers = {};
|
|
17
|
+
for (const header of bundle.commit?.headers ?? []) headers[header.key.toLowerCase()] = header.value;
|
|
18
|
+
return headers;
|
|
19
|
+
}
|
|
20
|
+
/** Reads the stage 7 commit into the cookie list `RenderedPage` carries. */
|
|
21
|
+
function committedCookies(bundle) {
|
|
22
|
+
return bundle.commit?.cookies ?? [];
|
|
23
|
+
}
|
|
9
24
|
let pageRoutesRegistry;
|
|
10
25
|
/**
|
|
11
26
|
* Boot-time wiring so `renderPage(name, options)` can resolve a route NAME
|
|
@@ -46,6 +61,11 @@ function buildUrl(entry, params, query) {
|
|
|
46
61
|
function FrameworkRootBoundary() {
|
|
47
62
|
return createElement("main", { role: "alert" }, "Something went wrong.");
|
|
48
63
|
}
|
|
64
|
+
function errorPageElement(module, props) {
|
|
65
|
+
const ErrorPage = module.default;
|
|
66
|
+
if (!ErrorPage) throw new Error("The application error.page.tsx module has no default export.");
|
|
67
|
+
return createElement(ErrorPage, props);
|
|
68
|
+
}
|
|
49
69
|
const DATA_KEYS = {
|
|
50
70
|
app: "appData",
|
|
51
71
|
layout: "layoutData",
|
|
@@ -63,7 +83,7 @@ const DATA_KEYS = {
|
|
|
63
83
|
* with no DOM.
|
|
64
84
|
*/
|
|
65
85
|
function buildPageElement(triple, bundle) {
|
|
66
|
-
return wrapRootward(triple, bundle, "page", buildLeaf(triple.page, bundle
|
|
86
|
+
return wrapRootward(triple, bundle, "page", buildLeaf(triple.page, bundle));
|
|
67
87
|
}
|
|
68
88
|
/**
|
|
69
89
|
* The error path renders the DESIGNATED boundary in place of the level it
|
|
@@ -81,12 +101,13 @@ function buildBoundaryElement(triple, bundle, record) {
|
|
|
81
101
|
const wrapped = wrapRootward(triple, bundle, boundary.boundaryLevel, element);
|
|
82
102
|
return boundary.boundaryLevel === "app" ? createElement(DefaultApp, { children: wrapped }) : wrapped;
|
|
83
103
|
}
|
|
84
|
-
function buildLeaf(module, bundle
|
|
104
|
+
function buildLeaf(module, bundle) {
|
|
85
105
|
const Component = module.default;
|
|
86
106
|
if (!Component) return null;
|
|
87
107
|
return createElement(Component, {
|
|
88
|
-
data: bundle
|
|
89
|
-
shared: bundle.shared
|
|
108
|
+
data: bundle.pageData,
|
|
109
|
+
shared: bundle.shared,
|
|
110
|
+
params: bundle.route.params
|
|
90
111
|
});
|
|
91
112
|
}
|
|
92
113
|
function wrapRootward(triple, bundle, from, leaf) {
|
|
@@ -131,20 +152,12 @@ function capturingCreateHttp(registry, as) {
|
|
|
131
152
|
createHttp(match) {
|
|
132
153
|
state.match = match;
|
|
133
154
|
state.captured = registry.createHttp(match);
|
|
134
|
-
if (as
|
|
155
|
+
if (as != null) state.captured.request.user = as;
|
|
135
156
|
return state.captured;
|
|
136
157
|
}
|
|
137
158
|
};
|
|
138
159
|
}
|
|
139
|
-
/**
|
|
140
|
-
* Structural read of the two core `Request` fields the slots need. Neither
|
|
141
|
-
* `nonce` nor `locale` is declared on `PipelineRequest`/`WebRequest` (the
|
|
142
|
-
* loader-facing facade only declares `validated`/`input`/`user`,
|
|
143
|
-
* context.ts:30-68) — a narrow typed intersection at the one call site that
|
|
144
|
-
* needs it, the same pattern `execute-page-request.ts` uses for its own
|
|
145
|
-
* `(response as PipelineResponse & { statusCode?: number })` read
|
|
146
|
-
* (execute-page-request.ts:517).
|
|
147
|
-
*/
|
|
160
|
+
/** Reads document slots directly from core's Request. */
|
|
148
161
|
function documentSlotsFrom(captured) {
|
|
149
162
|
const request = captured?.request;
|
|
150
163
|
return {
|
|
@@ -152,13 +165,12 @@ function documentSlotsFrom(captured) {
|
|
|
152
165
|
lang: request?.locale
|
|
153
166
|
};
|
|
154
167
|
}
|
|
155
|
-
async function finishRender(triple, bundle, documentSlots) {
|
|
156
|
-
const headers =
|
|
157
|
-
|
|
158
|
-
const cookies = bundle.commit?.cookies ?? [];
|
|
168
|
+
async function finishRender(triple, bundle, documentSlots, response, loadErrorPage) {
|
|
169
|
+
const headers = committedHeaders(bundle);
|
|
170
|
+
const cookies = committedCookies(bundle);
|
|
159
171
|
if (bundle.shortCircuit) return {
|
|
160
172
|
html: "",
|
|
161
|
-
status: bundle.shortCircuit.stage === "validation" ? bundle.shortCircuit.status : bundle.shortCircuit.
|
|
173
|
+
status: bundle.shortCircuit.stage === "validation" ? bundle.shortCircuit.status : bundle.shortCircuit.statusCode ?? 200,
|
|
162
174
|
headers,
|
|
163
175
|
cookies,
|
|
164
176
|
data: bundle.pageData,
|
|
@@ -166,7 +178,7 @@ async function finishRender(triple, bundle, documentSlots) {
|
|
|
166
178
|
};
|
|
167
179
|
if (headers["cache-control"] === void 0) headers["cache-control"] = "private";
|
|
168
180
|
const { renderToString } = await import("react-dom/server");
|
|
169
|
-
|
|
181
|
+
let documentValue = {
|
|
170
182
|
metadata: bundle.metadata,
|
|
171
183
|
payload: buildHydrationPayload(bundle),
|
|
172
184
|
nonce: documentSlots.nonce,
|
|
@@ -177,20 +189,58 @@ async function finishRender(triple, bundle, documentSlots) {
|
|
|
177
189
|
children: element
|
|
178
190
|
}));
|
|
179
191
|
let currentError = bundle.error;
|
|
180
|
-
let renderTimeThrow = false;
|
|
181
192
|
let body;
|
|
193
|
+
const renderFrameworkRoot = () => renderWithContext(createElement(DefaultApp, { children: createElement(FrameworkRootBoundary, {}) }));
|
|
194
|
+
const renderFrameworkAfterErrorPageFailure = () => {
|
|
195
|
+
bundle.errorPage = void 0;
|
|
196
|
+
bundle.metadata = ERROR_PAGE_METADATA;
|
|
197
|
+
documentValue = {
|
|
198
|
+
...documentValue,
|
|
199
|
+
metadata: bundle.metadata,
|
|
200
|
+
payload: buildHydrationPayload(bundle)
|
|
201
|
+
};
|
|
202
|
+
return renderFrameworkRoot();
|
|
203
|
+
};
|
|
204
|
+
const renderErrorPage = async (thrown, serializableError = thrown) => {
|
|
205
|
+
if (!loadErrorPage) return void 0;
|
|
206
|
+
const props = {
|
|
207
|
+
error: thrown,
|
|
208
|
+
status: 500
|
|
209
|
+
};
|
|
210
|
+
const module = await loadErrorPage();
|
|
211
|
+
registerModules([module]);
|
|
212
|
+
bundle.errorPage = hydrationErrorPageProps(props, serializableError);
|
|
213
|
+
bundle.metadata = resolveErrorPageMetadata(module, props);
|
|
214
|
+
documentValue = {
|
|
215
|
+
...documentValue,
|
|
216
|
+
metadata: bundle.metadata,
|
|
217
|
+
payload: buildHydrationPayload(bundle)
|
|
218
|
+
};
|
|
219
|
+
return renderWithContext(wrapRootward(triple, bundle, "page", errorPageElement(module, props)));
|
|
220
|
+
};
|
|
182
221
|
for (;;) try {
|
|
222
|
+
if (currentError?.boundary.boundaryLevel === "app" && !triple.app.ErrorBoundary) {
|
|
223
|
+
try {
|
|
224
|
+
body = await renderErrorPage(currentError.originalError ?? currentError.error, currentError.error) ?? renderFrameworkRoot();
|
|
225
|
+
} catch {
|
|
226
|
+
body = renderFrameworkAfterErrorPageFailure();
|
|
227
|
+
}
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
183
230
|
body = renderWithContext(currentError ? buildBoundaryElement(triple, bundle, currentError) : buildPageElement(triple, bundle));
|
|
184
231
|
break;
|
|
185
232
|
} catch (thrown) {
|
|
186
|
-
renderTimeThrow = true;
|
|
187
233
|
if (currentError?.boundary.boundaryLevel === "app") {
|
|
188
|
-
|
|
234
|
+
try {
|
|
235
|
+
body = await renderErrorPage(thrown) ?? renderFrameworkRoot();
|
|
236
|
+
} catch {
|
|
237
|
+
body = renderFrameworkAfterErrorPageFailure();
|
|
238
|
+
}
|
|
189
239
|
break;
|
|
190
240
|
}
|
|
191
241
|
currentError = buildErrorRecord(thrown, designateBoundary(currentError?.boundary.boundaryLevel === "layout" ? "app" : currentError ? "layout" : "page", triple));
|
|
192
242
|
}
|
|
193
|
-
const status =
|
|
243
|
+
const status = currentError ? 500 : bundle.commit?.statusCode ?? 200;
|
|
194
244
|
return {
|
|
195
245
|
html: emitDocument(body),
|
|
196
246
|
status,
|
|
@@ -200,6 +250,82 @@ async function finishRender(triple, bundle, documentSlots) {
|
|
|
200
250
|
bundle
|
|
201
251
|
};
|
|
202
252
|
}
|
|
253
|
+
/**
|
|
254
|
+
* Render failures that happen before the page pipeline has a triple (notably a
|
|
255
|
+
* module-load or registration throw). This deliberately owns one terminal
|
|
256
|
+
* attempt: an error-page failure falls straight to FrameworkRootBoundary.
|
|
257
|
+
*
|
|
258
|
+
* There is no triple yet, so there is no trustworthy server composition for
|
|
259
|
+
* the browser to hydrate against — every response this function produces is
|
|
260
|
+
* marked `markNonHydrating` (page-render-bundle.ts), on both the bundle and
|
|
261
|
+
* the document payload, whether or not it managed to render the app's own
|
|
262
|
+
* `error.page.tsx`. A normal app error page reached through `finishRender`
|
|
263
|
+
* renders inside a real triple and stays hydratable; this path never does.
|
|
264
|
+
*/
|
|
265
|
+
async function renderPageFailure(options) {
|
|
266
|
+
const { request, response, name, path, thrown, loadErrorPage } = options;
|
|
267
|
+
const bundle = markNonHydrating({ route: {
|
|
268
|
+
name,
|
|
269
|
+
path,
|
|
270
|
+
params: {},
|
|
271
|
+
query: {}
|
|
272
|
+
} });
|
|
273
|
+
const headers = { "cache-control": "private" };
|
|
274
|
+
const { renderToString } = await import("react-dom/server");
|
|
275
|
+
const slots = documentSlotsFrom({
|
|
276
|
+
request,
|
|
277
|
+
response
|
|
278
|
+
});
|
|
279
|
+
const frameworkPayload = markNonHydrating(buildHydrationPayload(bundle));
|
|
280
|
+
let value = {
|
|
281
|
+
metadata: void 0,
|
|
282
|
+
payload: frameworkPayload,
|
|
283
|
+
nonce: slots.nonce,
|
|
284
|
+
lang: slots.lang
|
|
285
|
+
};
|
|
286
|
+
const renderWithContext = (element) => renderToString(createElement(DocumentContext.Provider, {
|
|
287
|
+
value,
|
|
288
|
+
children: element
|
|
289
|
+
}));
|
|
290
|
+
let body;
|
|
291
|
+
try {
|
|
292
|
+
if (!loadErrorPage) throw new Error("No application error page is configured.");
|
|
293
|
+
const props = {
|
|
294
|
+
error: thrown,
|
|
295
|
+
status: 500
|
|
296
|
+
};
|
|
297
|
+
const module = await loadErrorPage();
|
|
298
|
+
registerModules([module]);
|
|
299
|
+
const errorPage = hydrationErrorPageProps(props);
|
|
300
|
+
bundle.errorPage = errorPage;
|
|
301
|
+
value = {
|
|
302
|
+
...value,
|
|
303
|
+
metadata: resolveErrorPageMetadata(module, props),
|
|
304
|
+
payload: markNonHydrating({
|
|
305
|
+
...frameworkPayload,
|
|
306
|
+
errorPage
|
|
307
|
+
})
|
|
308
|
+
};
|
|
309
|
+
body = renderWithContext(createElement(DefaultApp, { children: errorPageElement(module, props) }));
|
|
310
|
+
} catch {
|
|
311
|
+
bundle.errorPage = void 0;
|
|
312
|
+
bundle.metadata = ERROR_PAGE_METADATA;
|
|
313
|
+
value = {
|
|
314
|
+
...value,
|
|
315
|
+
metadata: bundle.metadata,
|
|
316
|
+
payload: markNonHydrating(buildHydrationPayload(bundle))
|
|
317
|
+
};
|
|
318
|
+
body = renderWithContext(createElement(DefaultApp, { children: createElement(FrameworkRootBoundary, {}) }));
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
html: emitDocument(body),
|
|
322
|
+
status: 500,
|
|
323
|
+
headers,
|
|
324
|
+
cookies: [],
|
|
325
|
+
data: void 0,
|
|
326
|
+
bundle
|
|
327
|
+
};
|
|
328
|
+
}
|
|
203
329
|
async function renderPage(routeName, options = {}) {
|
|
204
330
|
const registry = requireRegistry(options);
|
|
205
331
|
const entry = registry.routes.find((candidate) => candidate.name === routeName);
|
|
@@ -213,7 +339,7 @@ async function renderPage(routeName, options = {}) {
|
|
|
213
339
|
url,
|
|
214
340
|
routes: registry.routes,
|
|
215
341
|
createHttp,
|
|
216
|
-
finish: (bundle) => finishRender(entry.triple, bundle, documentSlotsFrom(state.captured))
|
|
342
|
+
finish: (bundle) => finishRender(entry.triple, bundle, documentSlotsFrom(state.captured), state.captured.response, options.loadErrorPage)
|
|
217
343
|
});
|
|
218
344
|
if (!rendered) throw new Error(`renderPage("${routeName}"): the built URL "${url}" did not match stage 1 (web/src/server/render-page.ts). The name resolved but the matcher disagreed — that is a manifest bug, not a caller bug.`);
|
|
219
345
|
return rendered;
|
|
@@ -235,7 +361,7 @@ async function renderPageRequest(url, options = {}) {
|
|
|
235
361
|
url,
|
|
236
362
|
routes: registry.routes,
|
|
237
363
|
createHttp,
|
|
238
|
-
finish: (bundle) => finishRender(state.match.entry.triple, bundle, documentSlotsFrom(state.captured))
|
|
364
|
+
finish: (bundle) => finishRender(state.match.entry.triple, bundle, documentSlotsFrom(state.captured), state.captured.response, options.loadErrorPage)
|
|
239
365
|
});
|
|
240
366
|
if (!rendered) return {
|
|
241
367
|
html: "",
|
|
@@ -249,5 +375,5 @@ async function renderPageRequest(url, options = {}) {
|
|
|
249
375
|
}
|
|
250
376
|
|
|
251
377
|
//#endregion
|
|
252
|
-
export { connectPageRoutes, renderPage, renderPageRequest };
|
|
378
|
+
export { connectPageRoutes, renderPage, renderPageFailure, renderPageRequest };
|
|
253
379
|
//# sourceMappingURL=render-page.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-page.mjs","names":[],"sources":["../../../../../../../web/src/server/render-page.ts"],"sourcesContent":["import { createElement, type ComponentType, type ReactNode } from \"react\";\nimport DefaultApp from \"../components/default-app\";\nimport {\n DocumentContext,\n escapePayload,\n PAYLOAD_SCRIPT_ID,\n type DocumentContextValue,\n} from \"../components/document-context\";\nimport type { SharedContext } from \"../index\";\nimport { buildHydrationPayload } from \"./build-hydration-payload\";\nimport type { BufferedCookie } from \"./buffered-response\";\nimport {\n buildErrorRecord,\n designateBoundary,\n executePageRequest,\n type ExecutePageRequestOptions,\n type PageDataBundle,\n type PageErrorRecord,\n type PageLevelName,\n type PageRouteEntry,\n type PageRouteMatch,\n type PageTripleModule,\n type PipelineRequest,\n type PipelineResponse,\n} from \"./execute-page-request\";\n\nexport { escapePayload, PAYLOAD_SCRIPT_ID };\n\n/**\n * Pipeline stages 9–10: RENDER the page tree from the\n * data bundle stages 1–8 produced, then return finalized { html, status,\n * headers, cookies }. Stage 10 happens at the CALL SITE in two halves —\n * 10a the caller applies status + headers (the single live-response write,\n * after render, before anything flushes), 10b it flushes\n * the document. Nothing in this module writes the live response. It never\n * re-runs any earlier stage — `renderPage` calls `executePageRequest` and\n * everything here consumes its bundle as-is.\n *\n * `renderPage` is deliberately double-duty (dx-differentiators.md §3): it is\n * the production orchestrator AND the test helper. Because a loader IS a\n * controller, `renderPage(\"products.details\", { params: { id: \"42\" } })`\n * returns `{ html, status, headers, data }` in one call — asserting a page's\n * data and its response headers is a unit test, no browser, no server boot.\n */\n\n// ---------------------------------------------------------------------------\n// The routes seam (same pattern as connectPageContext: boot wiring, once)\n// ---------------------------------------------------------------------------\n\nexport type PageRoutesRegistry = {\n routes: readonly PageRouteEntry[];\n /** Same contract as ExecutePageRequestOptions[\"createHttp\"]. */\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n};\n\nlet pageRoutesRegistry: PageRoutesRegistry | undefined;\n\n/**\n * Boot-time wiring so `renderPage(name, options)` can resolve a route NAME\n * without each call site carrying the manifest. Returns the previous registry\n * so tests can restore it. A per-call `routes`/`createHttp` override wins.\n */\nexport function connectPageRoutes(\n registry: PageRoutesRegistry | undefined,\n): PageRoutesRegistry | undefined {\n const previous = pageRoutesRegistry;\n pageRoutesRegistry = registry;\n return previous;\n}\n\n// ---------------------------------------------------------------------------\n// renderPage surface\n// ---------------------------------------------------------------------------\n\nexport type RenderPageOptions = {\n params?: Record<string, string>;\n query?: Record<string, string>;\n /**\n * Impersonation for tests: assigned to `request.user` right after the\n * request pair is constructed — `user` is a plain public property on core's\n * Request (core/src/http/request.ts:92) and this is exactly the write auth\n * middleware would have performed.\n */\n as?: unknown;\n /** Per-call overrides of the connected registry (tests, mostly). */\n routes?: readonly PageRouteEntry[];\n createHttp?: ExecutePageRequestOptions[\"createHttp\"];\n};\n\n/**\n * `renderPageRequest` takes the URL itself, so `params`/`query` (the\n * name-based sugar buildUrl consumes) have no meaning here — everything else\n * is the same seam.\n */\nexport type RenderPageRequestOptions = Omit<RenderPageOptions, \"params\" | \"query\">;\n\nexport type RenderedPage = {\n /** The full document (\"\" when the pipeline short-circuited before render). */\n html: string;\n status: number;\n /** Committed response headers, lowercased key → value. */\n headers: Record<string, string>;\n /**\n * Committed cookies in commit order, attribute-faithful: each entry carries\n * the loader's raw value (pre-serialization) AND its options\n * (`httpOnly`/`secure`/`sameSite`/`path`/`expires`/…). Never flattened to a\n * name→value map — a map cannot express the attributes, and a Set-Cookie\n * built without them is a security defect, not a convenience.\n */\n cookies: BufferedCookie[];\n /**\n * The PAGE loader's data — `data.product.name` reads as the dx story\n * writes it. `unknown`: the pipeline never checks a loader's return shape.\n */\n data: unknown;\n /**\n * The full stages-1–8 bundle, for assertions beyond the page's own data.\n * Undefined ONLY on `renderPageRequest`'s no-match path: no route matched,\n * so no pipeline ran and there is no bundle — the 404 answer stands alone.\n * `renderPage` always carries one (its no-match throws instead).\n */\n bundle: PageDataBundle | undefined;\n};\n\nfunction requireRegistry(\n options: Pick<RenderPageOptions, \"routes\" | \"createHttp\">,\n): PageRoutesRegistry {\n const routes = options.routes ?? pageRoutesRegistry?.routes;\n const createHttp = options.createHttp ?? pageRoutesRegistry?.createHttp;\n\n if (!routes || !createHttp) {\n throw new Error(\n \"renderPage()/renderPageRequest() has no route registry connected \" +\n \"(web/src/server/render-page.ts). Both resolve against the page \" +\n \"manifest, which the server bootstrap owns. Fix: \" +\n \"call connectPageRoutes({ routes, createHttp }) at boot (tests: in \" +\n \"beforeAll), or pass { routes, createHttp } to this call.\",\n );\n }\n\n return { routes, createHttp };\n}\n\nfunction buildUrl(\n entry: PageRouteEntry,\n params: Record<string, string>,\n query: Record<string, string>,\n): string {\n const path = entry.path\n .split(\"/\")\n .map(segment => {\n if (!segment.startsWith(\":\")) return segment;\n\n const name = segment.slice(1);\n const value = params[name];\n\n if (value === undefined) {\n throw new Error(\n `renderPage(\"${entry.name}\"): route path \"${entry.path}\" needs ` +\n `param \"${name}\" and the call did not provide it ` +\n \"(web/src/server/render-page.ts). Fix: pass it in \" +\n `\\`params: { ${name}: … }\\`.`,\n );\n }\n\n return encodeURIComponent(value);\n })\n .join(\"/\");\n\n const queryString = new URLSearchParams(query).toString();\n\n return queryString ? `${path}?${queryString}` : path;\n}\n\n// ---------------------------------------------------------------------------\n// Stage 9 — RENDER\n// ---------------------------------------------------------------------------\n\n/**\n * The framework-owned terminal boundary (P1 §4: designation falls back to\n * `app` even when no level exports one — \"the framework owns a root\n * boundary\"). Deliberately generic: the error itself is server knowledge and\n * never serialized into the document.\n */\nfunction FrameworkRootBoundary(): ReactNode {\n return createElement(\"main\", { role: \"alert\" }, \"Something went wrong.\");\n}\n\ntype LevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n children?: ReactNode;\n};\n\nconst DATA_KEYS: Record<PageLevelName, \"appData\" | \"layoutData\" | \"pageData\"> = {\n app: \"appData\",\n layout: \"layoutData\",\n page: \"pageData\",\n};\n\n/**\n * Compose the tree root→leaf: `<App><Layout><Page/></Layout></App>`, each\n * level receiving ITS OWN loader data and the same sealed `shared` — the\n * exact props the M1 contract declares (web/src/props.ts) and never\n * request/response (the component also renders on a machine where neither\n * exists, props.ts:19-22).\n *\n * A level with no default export contributes no DOM and passes children\n * through — that is `layout.tsx` omitting its default export to be a guard\n * with no DOM.\n */\nfunction buildPageElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n): ReactNode {\n return wrapRootward(triple, bundle, \"page\", buildLeaf(triple.page, bundle, \"page\"));\n}\n\n/**\n * The error path renders the DESIGNATED boundary in place of the level it\n * covers, still wrapped by every level rootward of it — a page-level throw\n * keeps its App and Layout chrome, whose data survived the settle rules\n * (P1 §4: fulfilled sibling data stays in the bundle).\n *\n * `record` is explicit rather than read from `bundle.error` — a render-time\n * throw (`finishRender`'s stage 9 escalation loop) designates a NEW boundary on the fly that the stage 1-8 bundle never saw.\n */\nfunction buildBoundaryElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n record: PageErrorRecord,\n): ReactNode {\n const { boundary, error } = record;\n const Boundary = triple[boundary.boundaryLevel].ErrorBoundary as\n | ((props: { error: unknown }) => ReactNode)\n | undefined;\n\n const element = Boundary\n ? createElement(Boundary, { error })\n : createElement(FrameworkRootBoundary, {});\n\n const wrapped = wrapRootward(triple, bundle, boundary.boundaryLevel, element);\n\n // \"App\" has no level rootward of it, so `wrapRootward` returns `wrapped`\n // unwrapped when the boundary covers the app level itself — but the\n // pipeline always emits a complete document, so the\n // framework default supplies the shell here even though the app's own\n // (broken) root is what's being bypassed.\n return boundary.boundaryLevel === \"app\"\n ? createElement(DefaultApp, { children: wrapped })\n : wrapped;\n}\n\nfunction buildLeaf(\n module: PageTripleModule,\n bundle: PageDataBundle,\n level: PageLevelName,\n): ReactNode {\n const Component = module.default as ((props: LevelProps) => ReactNode) | undefined;\n\n if (!Component) return null;\n\n return createElement(Component as ComponentType<LevelProps>, {\n data: bundle[DATA_KEYS[level]],\n shared: bundle.shared,\n });\n}\n\nfunction wrapRootward(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n from: PageLevelName,\n leaf: ReactNode,\n): ReactNode {\n const wrappers: PageLevelName[] = from === \"page\" ? [\"layout\", \"app\"] : from === \"layout\" ? [\"app\"] : [];\n\n let element = leaf;\n\n for (const level of wrappers) {\n const Component = triple[level].default as ((props: LevelProps) => ReactNode) | undefined;\n\n if (!Component) {\n // \"App\" is the root: no App export means no custom document, but the\n // pipeline always emits a complete one — the\n // framework default App supplies it. Layout has no such fallback: an\n // omitted layout default export stays a no-DOM passthrough,\n // unchanged from before.\n if (level === \"app\") {\n element = createElement(DefaultApp, { children: element });\n }\n\n continue;\n }\n\n element = createElement(Component as ComponentType<LevelProps>, {\n data: bundle[DATA_KEYS[level]],\n shared: bundle.shared,\n children: element,\n });\n }\n\n return element;\n}\n\n// ---------------------------------------------------------------------------\n// Document assembly — stage 10 (10a apply + 10b flush) lives at the call site\n// ---------------------------------------------------------------------------\n\n/**\n * The root (App or the framework default) now ALWAYS renders a complete\n * `<html>…</html>` document itself — `<Head/>`/\n * `<Scripts/>` read the metadata/payload from `DocumentContext` (provided\n * around the element in `finishRender`, below) and emit real elements.\n * There is nothing left for this stage to assemble by string surgery; it\n * only prepends the doctype `renderToString` never includes.\n */\nfunction emitDocument(body: string): string {\n return \"<!DOCTYPE html>\" + body;\n}\n\n// ---------------------------------------------------------------------------\n// The shared tail (stages 9–10) — both orchestrators end here\n// ---------------------------------------------------------------------------\n\n/**\n * The real request/response pair `capturingCreateHttp` captured for this\n * call. `finishRender` itself no longer takes this (D1: the short-circuit\n * status now lives on `bundle.shortCircuit`/`bundle.commit`) — it is used at\n * the two orchestrator call sites for the `as` impersonation write\n * (`state.captured.request.user = as`, below) and to read the document\n * slots (`documentSlotsFrom`, below).\n */\ntype CapturedHttp = {\n request: PipelineRequest;\n response: PipelineResponse;\n};\n\n/**\n * Wrap the caller's createHttp to capture the real pair (for the document\n * slots, `documentSlotsFrom` below), the matched entry (the only place a\n * URL-based caller learns which triple to render), and to apply `as` —\n * `user` is a plain public property on core's Request\n * (core/src/http/request.ts:92), exactly the write auth middleware performs.\n */\nfunction capturingCreateHttp(\n registry: PageRoutesRegistry,\n as: unknown,\n): {\n state: { captured?: CapturedHttp; match?: PageRouteMatch };\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n} {\n const state: { captured?: CapturedHttp; match?: PageRouteMatch } = {};\n\n return {\n state,\n createHttp(match) {\n state.match = match;\n state.captured = registry.createHttp(match);\n\n if (as !== undefined) state.captured.request.user = as;\n\n return state.captured;\n },\n };\n}\n\n/**\n * The two request-derived document slots (`nonce`/`lang` on\n * `DocumentContextValue`), extracted at the orchestrator call sites\n * because `finishRender` no longer carries `captured` (D1). `dir` is not\n * here: core's Request has no dir-like field (checked\n * core/src/http/request.ts — only `nonce` at :177 and `locale` at :343\n * exist) — an app supplies `dir` via its own convention.\n */\ntype DocumentSlots = {\n nonce?: string;\n lang?: string;\n};\n\n/**\n * Structural read of the two core `Request` fields the slots need. Neither\n * `nonce` nor `locale` is declared on `PipelineRequest`/`WebRequest` (the\n * loader-facing facade only declares `validated`/`input`/`user`,\n * context.ts:30-68) — a narrow typed intersection at the one call site that\n * needs it, the same pattern `execute-page-request.ts` uses for its own\n * `(response as PipelineResponse & { statusCode?: number })` read\n * (execute-page-request.ts:517).\n */\nfunction documentSlotsFrom(captured: CapturedHttp | undefined): DocumentSlots {\n const request = captured?.request as (PipelineRequest & { nonce?: string; locale?: string }) | undefined;\n\n return { nonce: request?.nonce, lang: request?.locale };\n}\n\nasync function finishRender(\n triple: PageRouteEntry[\"triple\"],\n bundle: PageDataBundle,\n documentSlots: DocumentSlots,\n): Promise<RenderedPage> {\n const headers: Record<string, string> = {};\n\n for (const header of bundle.commit?.headers ?? []) {\n headers[header.key.toLowerCase()] = header.value;\n }\n\n // The commit already deduplicated per name and ordered root→leaf\n // (execute-page-request.ts settle/commit) — pass it through untransformed so\n // every attribute survives to the caller's Set-Cookie.\n const cookies: BufferedCookie[] = bundle.commit?.cookies ?? [];\n\n // Short-circuit paths emit no document: the status IS the answer\n // (redirect/notFound/guard/422 — P1 §4), nothing renders to describe.\n if (bundle.shortCircuit) {\n const status =\n bundle.shortCircuit.stage === \"validation\"\n ? bundle.shortCircuit.status\n : bundle.shortCircuit.stage === \"loaders\"\n ? bundle.shortCircuit.statusCode\n // D1: the middleware variant now carries its own statusCode,\n // captured at stage 3 where the pipeline legitimately touches the\n // live response (execute-page-request.ts:514-518) — no live read here.\n : (bundle.shortCircuit.statusCode ?? 200);\n\n return { html: \"\", status, headers, cookies, data: bundle.pageData, bundle };\n }\n\n // The framework's closed-by-default answer (README rule 8): every document\n // is `Cache-Control: private` unless a loader's committed headers already\n // answered for the key. Map-only — `finishRender` never writes the live\n // response; the caller applies the returned headers.\n if (headers[\"cache-control\"] === undefined) {\n headers[\"cache-control\"] = \"private\";\n }\n\n // ── stage 9 · RENDER ─────────────────────────────────────────────────────\n // Lazy import: react-dom is a peer used only on this path, so merely\n // loading the server barrel never requires it.\n const { renderToString } = await import(\"react-dom/server\");\n\n // JSON.stringify omits object properties whose value is undefined. Loader\n // `<Head/>`/`<Scripts/>` read this context — metadata and the payload are\n // both already final by this point (stages 1-8 are done), so there is\n // nothing left for the root to await.\n //\n // The payload comes from `buildHydrationPayload` rather than being assembled\n // here, so that this document and the `_loader` route hand the browser the\n // SAME object. See that module for why the two must not drift.\n const documentValue: DocumentContextValue = {\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n nonce: documentSlots.nonce,\n lang: documentSlots.lang,\n };\n\n const renderWithContext = (element: ReactNode): string =>\n renderToString(createElement(DocumentContext.Provider, { value: documentValue, children: element }));\n\n // A boundary that throws while rendering escalates to\n // the next enclosing boundary rootward; if none survives, the framework's\n // last-resort terminal renders. `currentError` starts as whatever stage\n // 1-8 already designated (`bundle.error`, undefined for a normal page\n // render) and is replaced by each escalation — `bundle.error` itself is\n // never mutated, staying a truthful stage 1-8 record.\n let currentError = bundle.error;\n let renderTimeThrow = false;\n let body: string;\n\n for (;;) {\n try {\n const element = currentError\n ? buildBoundaryElement(triple, bundle, currentError)\n : buildPageElement(triple, bundle);\n\n body = renderWithContext(element);\n break;\n } catch (thrown) {\n renderTimeThrow = true;\n\n if (currentError?.boundary.boundaryLevel === \"app\") {\n // The floor: the app-level boundary's own render just threw, so\n // there is nothing rootward of `app` to escalate to (§2's \"none\n // survives\"). Render the framework's trivial boundary directly —\n // bypassing the app's ErrorBoundary/App component, since that is\n // what just failed — wrapped in DefaultApp so the response is still\n // a complete `<html>` document (default-app.tsx:22-46) rather than\n // a bare `<main>` fragment.\n body = renderWithContext(createElement(DefaultApp, { children: createElement(FrameworkRootBoundary, {}) }));\n break;\n }\n\n // Escalate from the level rootward of whatever just threw — searching\n // from the SAME level would re-select the boundary that just failed.\n // A throw not yet attributable to a level (a normal page render, no\n // prior designation) starts the search at `page`.\n const throwingLevel: PageLevelName =\n currentError?.boundary.boundaryLevel === \"layout\" ? \"app\" : currentError ? \"layout\" : \"page\";\n\n currentError = buildErrorRecord(thrown, designateBoundary(throwingLevel, triple));\n }\n }\n\n // Status is chosen after render — the last thing that can change the\n // outcome — and RETURNED, never applied: `finishRender` writes the live\n // response zero times (and now zero live response READS either — D1 deleted the last one). The caller applies\n // status + headers at one site and flushes immediately after (stage\n // 10a/10b). A render-time throw follows the same status rule as a\n // pre-render one: a NESTED boundary catch\n // (page/layout) keeps the committed status; the app boundary or the\n // framework terminal forces 500. Without a render-time throw, the\n // pre-render designation already carries this rule — P1's commit forces\n // 500 only when it designated `app` (execute-page-request.ts:625-637).\n const status = renderTimeThrow\n ? currentError!.boundary.boundaryLevel === \"app\"\n ? 500\n : (bundle.commit?.statusCode ?? 200)\n : bundle.error\n ? (bundle.commit?.statusCode ?? 500)\n : (bundle.commit?.statusCode ?? 200);\n\n const html = emitDocument(body);\n\n return { html, status, headers, cookies, data: bundle.pageData, bundle };\n}\n\n// ---------------------------------------------------------------------------\n// The orchestrators\n// ---------------------------------------------------------------------------\n\nexport async function renderPage(\n routeName: string,\n options: RenderPageOptions = {},\n): Promise<RenderedPage> {\n const registry = requireRegistry(options);\n const entry = registry.routes.find(candidate => candidate.name === routeName);\n\n if (!entry) {\n const known = registry.routes.map(candidate => `\"${candidate.name}\"`).join(\", \");\n\n throw new Error(\n `renderPage(\"${routeName}\"): no route with that name ` +\n `(web/src/server/render-page.ts). Known route names: ${known}. ` +\n \"Fix: use a name from the manifest, or connect the manifest that \" +\n \"declares this one.\",\n );\n }\n\n const url = buildUrl(entry, options.params ?? {}, options.query ?? {});\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: bundle => finishRender(entry.triple, bundle, documentSlotsFrom(state.captured)),\n });\n\n if (!rendered) {\n throw new Error(\n `renderPage(\"${routeName}\"): the built URL \"${url}\" did not match ` +\n \"stage 1 (web/src/server/render-page.ts). The name resolved but the \" +\n \"matcher disagreed — that is a manifest bug, not a caller bug.\",\n );\n }\n\n return rendered;\n}\n\n/**\n * The URL-based sibling of `renderPage` — the production render surface: a\n * real HTTP server has a URL, not a route name. The url goes STRAIGHT to\n * executePageRequest's stage-1 matcher (no buildUrl), then the same shared\n * tail renders and emits.\n *\n * No-match here is NOT the manifest bug renderPage throws on: an arbitrary\n * URL matching no route is a legitimate 404, and a server must ANSWER it —\n * `{ html: \"\", status: 404 }` with an undefined `bundle` (see RenderedPage).\n */\nexport async function renderPageRequest(\n url: string,\n options: RenderPageRequestOptions = {},\n): Promise<RenderedPage> {\n const registry = requireRegistry(options);\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: bundle => finishRender(state.match!.entry.triple, bundle, documentSlotsFrom(state.captured)),\n });\n\n if (!rendered) {\n return { html: \"\", status: 404, headers: {}, cookies: [], data: undefined, bundle: undefined };\n }\n\n // executePageRequest only produces a bundle after createHttp ran for the\n // match, so the captured entry is present whenever the bundle is.\n return rendered;\n}\n"],"mappings":";;;;;;;;AAuDA,IAAI;;;;;;AAOJ,SAAgB,kBACd,UACgC;CAChC,MAAM,WAAW;CACjB,qBAAqB;CACrB,OAAO;AACT;AAwDA,SAAS,gBACP,SACoB;CACpB,MAAM,SAAS,QAAQ,UAAU,oBAAoB;CACrD,MAAM,aAAa,QAAQ,cAAc,oBAAoB;CAE7D,IAAI,CAAC,UAAU,CAAC,YACd,MAAM,IAAI,MACR,4SAKF;CAGF,OAAO;EAAE;EAAQ;CAAW;AAC9B;AAEA,SAAS,SACP,OACA,QACA,OACQ;CACR,MAAM,OAAO,MAAM,KAChB,MAAM,GAAG,CAAC,CACV,KAAI,YAAW;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ACR,eAAe,UAAU,kFACgC,MAAM,qFAGjE;CACF;CAEA,MAAM,MAAM,SAAS,OAAO,QAAQ,UAAU,CAAC,GAAG,QAAQ,SAAS,CAAC,CAAC;CACrE,MAAM,EAAE,OAAO,eAAe,oBAAoB,UAAU,QAAQ,EAAE;CAEtE,MAAM,WAAW,MAAM,mBAAmB;EACxC;EACA,QAAQ,SAAS;EACjB;EACA,SAAQ,WAAU,aAAa,MAAM,QAAQ,QAAQ,kBAAkB,MAAM,QAAQ,CAAC;CACxF,CAAC;CAED,IAAI,CAAC,UACH,MAAM,IAAI,MACR,eAAe,UAAU,qBAAqB,IAAI,iJAGpD;CAGF,OAAO;AACT;;;;;;;;;;;AAYA,eAAsB,kBACpB,KACA,UAAoC,CAAC,GACd;CACvB,MAAM,WAAW,gBAAgB,OAAO;CACxC,MAAM,EAAE,OAAO,eAAe,oBAAoB,UAAU,QAAQ,EAAE;CAEtE,MAAM,WAAW,MAAM,mBAAmB;EACxC;EACA,QAAQ,SAAS;EACjB;EACA,SAAQ,WAAU,aAAa,MAAM,MAAO,MAAM,QAAQ,QAAQ,kBAAkB,MAAM,QAAQ,CAAC;CACrG,CAAC;CAED,IAAI,CAAC,UACH,OAAO;EAAE,MAAM;EAAI,QAAQ;EAAK,SAAS,CAAC;EAAG,SAAS,CAAC;EAAG,MAAM;EAAW,QAAQ;CAAU;CAK/F,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"render-page.mjs","names":[],"sources":["../../../../../../../web/src/server/render-page.ts"],"sourcesContent":["import { createElement, type ComponentType, type ReactNode } from \"react\";\nimport { Response, type Request } from \"@warlock.js/core\";\nimport DefaultApp from \"../components/default-app\";\nimport {\n DocumentContext,\n escapePayload,\n PAYLOAD_SCRIPT_ID,\n type DocumentContextValue,\n} from \"../components/document-context\";\nimport type { SharedContext } from \"../index\";\nimport { buildHydrationPayload } from \"./build-hydration-payload\";\nimport {\n hydrationErrorPageProps,\n resolveErrorPageMetadata,\n type ErrorPageModule,\n type ErrorPageModuleLoader,\n} from \"./error-page\";\nimport { ERROR_PAGE_METADATA } from \"./resolve-page-metadata\";\nimport {\n registerModules,\n type RegisterableModuleNamespace,\n} from \"../runtime/register-modules\";\nimport { markNonHydrating } from \"./page-render-bundle\";\nimport type { ServerErrorPageProps } from \"../props\";\nimport {\n buildErrorRecord,\n designateBoundary,\n executePageRequest,\n type BufferedCookie,\n type ExecutePageRequestOptions,\n type PageDataBundle,\n type PageErrorRecord,\n type PageLevelName,\n type PageResponseCommit,\n type PageRouteEntry,\n type PageRouteMatch,\n type PageTripleModule,\n} from \"./execute-page-request\";\n\nexport { escapePayload, PAYLOAD_SCRIPT_ID };\nexport type { BufferedCookie };\n\n/** Widens `PageDataBundle` with the stage 7 commit record — see `execute-page-request.ts`. */\ntype Bundle = PageDataBundle & { commit?: PageResponseCommit };\n\n/** Reads the stage 7 commit into the lowercased header map `RenderedPage` carries. */\nfunction committedHeaders(bundle: PageDataBundle): Record<string, string> {\n const headers: Record<string, string> = {};\n\n for (const header of (bundle as Bundle).commit?.headers ?? []) {\n headers[header.key.toLowerCase()] = header.value;\n }\n\n return headers;\n}\n\n/** Reads the stage 7 commit into the cookie list `RenderedPage` carries. */\nfunction committedCookies(bundle: PageDataBundle): BufferedCookie[] {\n return (bundle as Bundle).commit?.cookies ?? [];\n}\n\n/**\n * Pipeline stages 9–10: RENDER the page tree from the\n * data bundle stages 1–8 produced, then return finalized { html, status,\n * headers }. Stage 10 happens at the CALL SITE in two halves —\n * 10a the caller applies status + headers (the single live-response write,\n * after render, before anything flushes), 10b it flushes\n * the document. Nothing in this module writes the live response. It never\n * re-runs any earlier stage — `renderPage` calls `executePageRequest` and\n * everything here consumes its bundle as-is.\n *\n * `renderPage` is deliberately double-duty (dx-differentiators.md §3): it is\n * the production orchestrator AND the test helper. Because a loader IS a\n * controller, `renderPage(\"products.details\", { params: { id: \"42\" } })`\n * returns `{ html, status, headers, data }` in one call — asserting a page's\n * data and its response headers is a unit test, no browser, no server boot.\n */\n\n// ---------------------------------------------------------------------------\n// The routes seam (same pattern as connectPageContext: boot wiring, once)\n// ---------------------------------------------------------------------------\n\nexport type PageRoutesRegistry = {\n routes: readonly PageRouteEntry[];\n /** Same contract as ExecutePageRequestOptions[\"createHttp\"]. */\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n};\n\nlet pageRoutesRegistry: PageRoutesRegistry | undefined;\n\n/**\n * Boot-time wiring so `renderPage(name, options)` can resolve a route NAME\n * without each call site carrying the manifest. Returns the previous registry\n * so tests can restore it. A per-call `routes`/`createHttp` override wins.\n */\nexport function connectPageRoutes(\n registry: PageRoutesRegistry | undefined,\n): PageRoutesRegistry | undefined {\n const previous = pageRoutesRegistry;\n pageRoutesRegistry = registry;\n return previous;\n}\n\n// ---------------------------------------------------------------------------\n// renderPage surface\n// ---------------------------------------------------------------------------\n\nexport type RenderPageOptions = {\n params?: Record<string, string>;\n query?: Record<string, string>;\n /**\n * Impersonation for tests: assigned to `request.user` right after the\n * request pair is constructed — `user` is a plain public property on core's\n * Request (core/src/http/request.ts:92) and this is exactly the write auth\n * middleware would have performed.\n */\n as?: unknown;\n /** Per-call overrides of the connected registry (tests, mostly). */\n routes?: readonly PageRouteEntry[];\n createHttp?: ExecutePageRequestOptions[\"createHttp\"];\n /** Loaded only after the ordinary boundary chain has been exhausted. */\n loadErrorPage?: ErrorPageModuleLoader;\n};\n\n/**\n * `renderPageRequest` takes the URL itself, so `params`/`query` (the\n * name-based sugar buildUrl consumes) have no meaning here — everything else\n * is the same seam.\n */\nexport type RenderPageRequestOptions = Omit<\n RenderPageOptions,\n \"params\" | \"query\"\n>;\n\nexport type RenderedPage = {\n /** The full document (\"\" when the pipeline short-circuited before render). */\n html: string;\n status: number;\n /** Committed response headers, lowercased key → value. */\n headers: Record<string, string>;\n /** Committed response cookies, in commit order — stage 7's `bundle.commit.cookies`. */\n cookies: BufferedCookie[];\n /**\n * The PAGE loader's data — `data.product.name` reads as the dx story\n * writes it. `unknown`: the pipeline never checks a loader's return shape.\n */\n data: unknown;\n /**\n * The full stages-1–8 bundle, for assertions beyond the page's own data.\n * Undefined ONLY on `renderPageRequest`'s no-match path: no route matched,\n * so no pipeline ran and there is no bundle — the 404 answer stands alone.\n * `renderPage` always carries one (its no-match throws instead).\n */\n bundle: PageDataBundle | undefined;\n};\n\nexport type RenderPageFailureOptions = {\n name: string;\n path: string;\n request: Request;\n response: Response;\n thrown: unknown;\n loadErrorPage?: ErrorPageModuleLoader;\n};\n\nfunction requireRegistry(\n options: Pick<RenderPageOptions, \"routes\" | \"createHttp\">,\n): PageRoutesRegistry {\n const routes = options.routes ?? pageRoutesRegistry?.routes;\n const createHttp = options.createHttp ?? pageRoutesRegistry?.createHttp;\n\n if (!routes || !createHttp) {\n throw new Error(\n \"renderPage()/renderPageRequest() has no route registry connected \" +\n \"(web/src/server/render-page.ts). Both resolve against the page \" +\n \"manifest, which the server bootstrap owns. Fix: \" +\n \"call connectPageRoutes({ routes, createHttp }) at boot (tests: in \" +\n \"beforeAll), or pass { routes, createHttp } to this call.\",\n );\n }\n\n return { routes, createHttp };\n}\n\nfunction buildUrl(\n entry: PageRouteEntry,\n params: Record<string, string>,\n query: Record<string, string>,\n): string {\n const path = entry.path\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n\n const name = segment.slice(1);\n const value = params[name];\n\n if (value === undefined) {\n throw new Error(\n `renderPage(\"${entry.name}\"): route path \"${entry.path}\" needs ` +\n `param \"${name}\" and the call did not provide it ` +\n \"(web/src/server/render-page.ts). Fix: pass it in \" +\n `\\`params: { ${name}: … }\\`.`,\n );\n }\n\n return encodeURIComponent(value);\n })\n .join(\"/\");\n\n const queryString = new URLSearchParams(query).toString();\n\n return queryString ? `${path}?${queryString}` : path;\n}\n\n// ---------------------------------------------------------------------------\n// Stage 9 — RENDER\n// ---------------------------------------------------------------------------\n\n/**\n * The framework-owned terminal boundary (P1 §4: designation falls back to\n * `app` even when no level exports one — \"the framework owns a root\n * boundary\"). Deliberately generic: the error itself is server knowledge and\n * never serialized into the document.\n */\nfunction FrameworkRootBoundary(): ReactNode {\n return createElement(\"main\", { role: \"alert\" }, \"Something went wrong.\");\n}\n\nfunction errorPageElement(\n module: ErrorPageModule,\n props: ServerErrorPageProps,\n): ReactNode {\n const ErrorPage = module.default as\n ((input: ServerErrorPageProps) => ReactNode) | undefined;\n if (!ErrorPage) {\n throw new Error(\n \"The application error.page.tsx module has no default export.\",\n );\n }\n return createElement(ErrorPage, props);\n}\n\ntype LevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n children?: ReactNode;\n};\n\n/** The ordinary page leaf alone receives the route match's params. */\ntype PageLevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n params: Readonly<Record<string, string>>;\n};\n\nconst DATA_KEYS: Record<PageLevelName, \"appData\" | \"layoutData\" | \"pageData\"> =\n {\n app: \"appData\",\n layout: \"layoutData\",\n page: \"pageData\",\n };\n\n/**\n * Compose the tree root→leaf: `<App><Layout><Page/></Layout></App>`, each\n * level receiving ITS OWN loader data and the same sealed `shared` — the\n * exact props the M1 contract declares (web/src/props.ts) and never\n * request/response (the component also renders on a machine where neither\n * exists, props.ts:19-22).\n *\n * A level with no default export contributes no DOM and passes children\n * through — that is `layout.tsx` omitting its default export to be a guard\n * with no DOM.\n */\nfunction buildPageElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n): ReactNode {\n return wrapRootward(triple, bundle, \"page\", buildLeaf(triple.page, bundle));\n}\n\n/**\n * The error path renders the DESIGNATED boundary in place of the level it\n * covers, still wrapped by every level rootward of it — a page-level throw\n * keeps its App and Layout chrome, whose data survived the settle rules\n * (P1 §4: fulfilled sibling data stays in the bundle).\n *\n * `record` is explicit rather than read from `bundle.error` — a render-time\n * throw (`finishRender`'s stage 9 escalation loop) designates a NEW boundary on the fly that the stage 1-8 bundle never saw.\n */\nfunction buildBoundaryElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n record: PageErrorRecord,\n): ReactNode {\n const { boundary, error } = record;\n const Boundary = triple[boundary.boundaryLevel].ErrorBoundary as\n ((props: { error: unknown }) => ReactNode) | undefined;\n\n const element = Boundary\n ? createElement(Boundary, { error })\n : createElement(FrameworkRootBoundary, {});\n\n const wrapped = wrapRootward(triple, bundle, boundary.boundaryLevel, element);\n\n // \"App\" has no level rootward of it, so `wrapRootward` returns `wrapped`\n // unwrapped when the boundary covers the app level itself — but the\n // pipeline always emits a complete document, so the\n // framework default supplies the shell here even though the app's own\n // (broken) root is what's being bypassed.\n return boundary.boundaryLevel === \"app\"\n ? createElement(DefaultApp, { children: wrapped })\n : wrapped;\n}\n\nfunction buildLeaf(\n module: PageTripleModule,\n bundle: PageDataBundle,\n): ReactNode {\n const Component = module.default as\n ((props: PageLevelProps) => ReactNode) | undefined;\n\n if (!Component) return null;\n\n return createElement(Component as ComponentType<PageLevelProps>, {\n data: bundle.pageData,\n shared: bundle.shared,\n params: bundle.route.params,\n });\n}\n\nfunction wrapRootward(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n from: PageLevelName,\n leaf: ReactNode,\n): ReactNode {\n const wrappers: PageLevelName[] =\n from === \"page\" ? [\"layout\", \"app\"] : from === \"layout\" ? [\"app\"] : [];\n\n let element = leaf;\n\n for (const level of wrappers) {\n const Component = triple[level].default as\n ((props: LevelProps) => ReactNode) | undefined;\n\n if (!Component) {\n // \"App\" is the root: no App export means no custom document, but the\n // pipeline always emits a complete one — the\n // framework default App supplies it. Layout has no such fallback: an\n // omitted layout default export stays a no-DOM passthrough,\n // unchanged from before.\n if (level === \"app\") {\n element = createElement(DefaultApp, { children: element });\n }\n\n continue;\n }\n\n element = createElement(Component as ComponentType<LevelProps>, {\n data: bundle[DATA_KEYS[level]],\n shared: bundle.shared,\n children: element,\n });\n }\n\n return element;\n}\n\n// ---------------------------------------------------------------------------\n// Document assembly — stage 10 (10a apply + 10b flush) lives at the call site\n// ---------------------------------------------------------------------------\n\n/**\n * The root (App or the framework default) now ALWAYS renders a complete\n * `<html>…</html>` document itself — `<Head/>`/\n * `<Scripts/>` read the metadata/payload from `DocumentContext` (provided\n * around the element in `finishRender`, below) and emit real elements.\n * There is nothing left for this stage to assemble by string surgery; it\n * only prepends the doctype `renderToString` never includes.\n */\nfunction emitDocument(body: string): string {\n return \"<!DOCTYPE html>\" + body;\n}\n\n// ---------------------------------------------------------------------------\n// The shared tail (stages 9–10) — both orchestrators end here\n// ---------------------------------------------------------------------------\n\n/**\n * The real request/response pair `capturingCreateHttp` captured for this\n * call. It is used at\n * the two orchestrator call sites for the `as` impersonation write\n * (`state.captured.request.user = as`, below) and to read the document\n * slots (`documentSlotsFrom`, below).\n */\ntype CapturedHttp = {\n request: Request;\n response: Response;\n};\n\n/**\n * Wrap the caller's createHttp to capture the real pair (for the document\n * slots, `documentSlotsFrom` below), the matched entry (the only place a\n * URL-based caller learns which triple to render), and to apply `as` —\n * `user` is a plain public property on core's Request\n * (core/src/http/request.ts:92), exactly the write auth middleware performs.\n */\nfunction capturingCreateHttp(\n registry: PageRoutesRegistry,\n as: unknown,\n): {\n state: { captured?: CapturedHttp; match?: PageRouteMatch };\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n} {\n const state: { captured?: CapturedHttp; match?: PageRouteMatch } = {};\n\n return {\n state,\n createHttp(match) {\n state.match = match;\n state.captured = registry.createHttp(match);\n\n // `!= null` (not just `!== undefined`): `Request.user` is `RequestUser\n // | undefined` (core/src/http/request.ts:93) — it has no `null` member,\n // so an explicit `as: null` is treated the same as \"no impersonation\"\n // rather than written through.\n if (as != null) state.captured.request.user = as;\n\n return state.captured;\n },\n };\n}\n\n/**\n * The two request-derived document slots (`nonce`/`lang` on\n * `DocumentContextValue`), extracted at the orchestrator call sites\n * because `finishRender` no longer carries `captured` (D1). `dir` is not\n * here: core's Request has no dir-like field (checked\n * core/src/http/request.ts — only `nonce` at :177 and `locale` at :343\n * exist) — an app supplies `dir` via its own convention.\n */\ntype DocumentSlots = {\n nonce?: string;\n lang?: string;\n};\n\n/** Reads document slots directly from core's Request. */\nfunction documentSlotsFrom(captured: CapturedHttp | undefined): DocumentSlots {\n const request = captured?.request;\n\n return { nonce: request?.nonce, lang: request?.locale };\n}\n\nasync function finishRender(\n triple: PageRouteEntry[\"triple\"],\n bundle: PageDataBundle,\n documentSlots: DocumentSlots,\n response: Response,\n loadErrorPage: ErrorPageModuleLoader | undefined,\n): Promise<RenderedPage> {\n // Read from the stage 7 commit, never live off `response` — this function\n // writes (and now reads) the live response zero times. A bundle with no\n // commit (no loader ran at all) simply has no headers/cookies to report.\n const headers = committedHeaders(bundle);\n const cookies = committedCookies(bundle);\n\n // Middleware and validation short-circuits emit no document. Loader-returned\n // Response instances never reach this function.\n if (bundle.shortCircuit) {\n const status =\n bundle.shortCircuit.stage === \"validation\"\n ? bundle.shortCircuit.status\n : (bundle.shortCircuit.statusCode ?? 200);\n return {\n html: \"\",\n status,\n headers,\n cookies,\n data: bundle.pageData,\n bundle,\n };\n }\n\n // The framework's closed-by-default answer (README rule 8): every document\n // is `Cache-Control: private` unless a loader's committed headers already\n // answered for the key. Map-only — the caller applies the returned headers.\n if (headers[\"cache-control\"] === undefined) {\n headers[\"cache-control\"] = \"private\";\n }\n\n // ── stage 9 · RENDER ─────────────────────────────────────────────────────\n // Lazy import: react-dom is a peer used only on this path, so merely\n // loading the server barrel never requires it.\n const { renderToString } = await import(\"react-dom/server\");\n\n // JSON.stringify omits object properties whose value is undefined. Loader\n // `<Head/>`/`<Scripts/>` read this context — metadata and the payload are\n // both already final by this point (stages 1-8 are done), so there is\n // nothing left for the root to await.\n //\n // The payload comes from `buildHydrationPayload` rather than being assembled\n // here, so that this document and the `_loader` route hand the browser the\n // SAME object. See that module for why the two must not drift.\n let documentValue: DocumentContextValue = {\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n nonce: documentSlots.nonce,\n lang: documentSlots.lang,\n };\n\n const renderWithContext = (element: ReactNode): string =>\n renderToString(\n createElement(DocumentContext.Provider, {\n value: documentValue,\n children: element,\n }),\n );\n\n // A boundary that throws while rendering escalates to\n // the next enclosing boundary rootward; if none survives, the framework's\n // last-resort terminal renders. `currentError` starts as whatever stage\n // 1-8 already designated (`bundle.error`, undefined for a normal page\n // render) and is replaced by each escalation — `bundle.error` itself is\n // never mutated, staying a truthful stage 1-8 record.\n let currentError = bundle.error;\n let renderTimeThrow = false;\n let body: string;\n\n const renderFrameworkRoot = (): string =>\n renderWithContext(\n createElement(DefaultApp, {\n children: createElement(FrameworkRootBoundary, {}),\n }),\n );\n const renderFrameworkAfterErrorPageFailure = (): string => {\n bundle.errorPage = undefined;\n bundle.metadata = ERROR_PAGE_METADATA;\n documentValue = {\n ...documentValue,\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n };\n return renderFrameworkRoot();\n };\n\n const renderErrorPage = async (\n thrown: unknown,\n serializableError: unknown = thrown,\n ): Promise<string | undefined> => {\n if (!loadErrorPage) return undefined;\n\n const props: ServerErrorPageProps = { error: thrown, status: 500 };\n const module = await loadErrorPage();\n registerModules([module as RegisterableModuleNamespace]);\n const errorPage = hydrationErrorPageProps(props, serializableError);\n bundle.errorPage = errorPage;\n bundle.metadata = resolveErrorPageMetadata(module, props);\n documentValue = {\n ...documentValue,\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n };\n return renderWithContext(\n wrapRootward(triple, bundle, \"page\", errorPageElement(module, props)),\n );\n };\n\n for (;;) {\n try {\n // The application error page is the framework terminal, never a rival\n // to an authored boundary. It is reached only after no app boundary\n // exists (or after that boundary has itself thrown below).\n if (\n currentError?.boundary.boundaryLevel === \"app\" &&\n !triple.app.ErrorBoundary\n ) {\n try {\n body =\n (await renderErrorPage(\n currentError.originalError ?? currentError.error,\n currentError.error,\n )) ?? renderFrameworkRoot();\n } catch {\n body = renderFrameworkAfterErrorPageFailure();\n }\n renderTimeThrow = true;\n break;\n }\n\n const element = currentError\n ? buildBoundaryElement(triple, bundle, currentError)\n : buildPageElement(triple, bundle);\n\n body = renderWithContext(element);\n break;\n } catch (thrown) {\n renderTimeThrow = true;\n\n if (currentError?.boundary.boundaryLevel === \"app\") {\n // The floor: the app-level boundary's own render just threw, so\n // there is nothing rootward of `app` to escalate to (§2's \"none\n // survives\"). Render the framework's trivial boundary directly —\n // bypassing the app's ErrorBoundary/App component, since that is\n // what just failed — wrapped in DefaultApp so the response is still\n // a complete `<html>` document (default-app.tsx:22-46) rather than\n // a bare `<main>` fragment.\n try {\n body = (await renderErrorPage(thrown)) ?? renderFrameworkRoot();\n } catch {\n body = renderFrameworkAfterErrorPageFailure();\n }\n break;\n }\n\n // Escalate from the level rootward of whatever just threw — searching\n // from the SAME level would re-select the boundary that just failed.\n // A throw not yet attributable to a level (a normal page render, no\n // prior designation) starts the search at `page`.\n const throwingLevel: PageLevelName =\n currentError?.boundary.boundaryLevel === \"layout\"\n ? \"app\"\n : currentError\n ? \"layout\"\n : \"page\";\n\n currentError = buildErrorRecord(\n thrown,\n designateBoundary(throwingLevel, triple),\n );\n }\n }\n\n // Status is chosen after render — the last thing that can change the\n // outcome — and RETURNED, never applied: `finishRender` writes the live\n // response zero times. The caller applies status + headers at one site and\n // flushes immediately after (stage 10a/10b). \"The framework owns the status\n // whenever a boundary renders\" (design/request-lifecycle.md stage 7): ANY\n // boundary — nested or app-level, discovered pre-render or escalated during\n // render — forces 500. The boundary's LEVEL only decides which component\n // renders, never the status; the committed status from stage 7\n // (`bundle.commit.statusCode`) stands only for a page with no error at all\n // — read off the commit, never off the live `response`, same as `headers`\n // above. No committed status (no loader called `setStatusCode`) is the\n // ordinary 200.\n const status = currentError\n ? 500\n : ((bundle as Bundle).commit?.statusCode ?? 200);\n\n const html = emitDocument(body);\n\n return { html, status, headers, cookies, data: bundle.pageData, bundle };\n}\n\n/**\n * Render failures that happen before the page pipeline has a triple (notably a\n * module-load or registration throw). This deliberately owns one terminal\n * attempt: an error-page failure falls straight to FrameworkRootBoundary.\n *\n * There is no triple yet, so there is no trustworthy server composition for\n * the browser to hydrate against — every response this function produces is\n * marked `markNonHydrating` (page-render-bundle.ts), on both the bundle and\n * the document payload, whether or not it managed to render the app's own\n * `error.page.tsx`. A normal app error page reached through `finishRender`\n * renders inside a real triple and stays hydratable; this path never does.\n */\nexport async function renderPageFailure(\n options: RenderPageFailureOptions,\n): Promise<RenderedPage> {\n const { request, response, name, path, thrown, loadErrorPage } = options;\n const bundle: PageDataBundle = markNonHydrating({\n route: { name, path, params: {}, query: {} },\n });\n // No pipeline ran (there is no triple), so there is no commit to read —\n // never a live `response.getHeaders()` read either; see `finishRender`.\n const headers: Record<string, string> = { \"cache-control\": \"private\" };\n\n const { renderToString } = await import(\"react-dom/server\");\n const slots = documentSlotsFrom({ request, response });\n const frameworkPayload = markNonHydrating(buildHydrationPayload(bundle));\n let value: DocumentContextValue = {\n metadata: undefined,\n payload: frameworkPayload,\n nonce: slots.nonce,\n lang: slots.lang,\n };\n const renderWithContext = (element: ReactNode): string =>\n renderToString(\n createElement(DocumentContext.Provider, { value, children: element }),\n );\n let body: string;\n\n try {\n if (!loadErrorPage)\n throw new Error(\"No application error page is configured.\");\n const props: ServerErrorPageProps = { error: thrown, status: 500 };\n const module = await loadErrorPage();\n registerModules([module as RegisterableModuleNamespace]);\n const errorPage = hydrationErrorPageProps(props);\n bundle.errorPage = errorPage;\n value = {\n ...value,\n metadata: resolveErrorPageMetadata(module, props),\n payload: markNonHydrating({ ...frameworkPayload, errorPage }),\n };\n body = renderWithContext(\n createElement(DefaultApp, { children: errorPageElement(module, props) }),\n );\n } catch {\n bundle.errorPage = undefined;\n bundle.metadata = ERROR_PAGE_METADATA;\n value = {\n ...value,\n metadata: bundle.metadata,\n payload: markNonHydrating(buildHydrationPayload(bundle)),\n };\n body = renderWithContext(\n createElement(DefaultApp, {\n children: createElement(FrameworkRootBoundary, {}),\n }),\n );\n }\n\n return {\n html: emitDocument(body),\n status: 500,\n headers,\n cookies: [],\n data: undefined,\n bundle,\n };\n}\n\n// ---------------------------------------------------------------------------\n// The orchestrators\n// ---------------------------------------------------------------------------\n\nexport async function renderPage(\n routeName: string,\n options: RenderPageOptions = {},\n): Promise<RenderedPage | Response> {\n const registry = requireRegistry(options);\n const entry = registry.routes.find(\n (candidate) => candidate.name === routeName,\n );\n\n if (!entry) {\n const known = registry.routes\n .map((candidate) => `\"${candidate.name}\"`)\n .join(\", \");\n\n throw new Error(\n `renderPage(\"${routeName}\"): no route with that name ` +\n `(web/src/server/render-page.ts). Known route names: ${known}. ` +\n \"Fix: use a name from the manifest, or connect the manifest that \" +\n \"declares this one.\",\n );\n }\n\n const url = buildUrl(entry, options.params ?? {}, options.query ?? {});\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: (bundle) =>\n finishRender(\n entry.triple,\n bundle,\n documentSlotsFrom(state.captured),\n state.captured!.response,\n options.loadErrorPage,\n ),\n });\n\n if (!rendered) {\n throw new Error(\n `renderPage(\"${routeName}\"): the built URL \"${url}\" did not match ` +\n \"stage 1 (web/src/server/render-page.ts). The name resolved but the \" +\n \"matcher disagreed — that is a manifest bug, not a caller bug.\",\n );\n }\n\n return rendered;\n}\n\n/**\n * The URL-based sibling of `renderPage` — the production render surface: a\n * real HTTP server has a URL, not a route name. The url goes STRAIGHT to\n * executePageRequest's stage-1 matcher (no buildUrl), then the same shared\n * tail renders and emits.\n *\n * No-match here is NOT the manifest bug renderPage throws on: an arbitrary\n * URL matching no route is a legitimate 404, and a server must ANSWER it —\n * `{ html: \"\", status: 404 }` with an undefined `bundle` (see RenderedPage).\n */\nexport async function renderPageRequest(\n url: string,\n options: RenderPageRequestOptions = {},\n): Promise<RenderedPage | Response> {\n const registry = requireRegistry(options);\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: (bundle) =>\n finishRender(\n state.match!.entry.triple,\n bundle,\n documentSlotsFrom(state.captured),\n state.captured!.response,\n options.loadErrorPage,\n ),\n });\n\n if (!rendered) {\n return {\n html: \"\",\n status: 404,\n headers: {},\n cookies: [],\n data: undefined,\n bundle: undefined,\n };\n }\n\n // executePageRequest only produces a bundle after createHttp ran for the\n // match, so the captured entry is present whenever the bundle is.\n return rendered;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAS,iBAAiB,QAAgD;CACxE,MAAM,UAAkC,CAAC;CAEzC,KAAK,MAAM,UAAW,OAAkB,QAAQ,WAAW,CAAC,GAC1D,QAAQ,OAAO,IAAI,YAAY,KAAK,OAAO;CAG7C,OAAO;AACT;;AAGA,SAAS,iBAAiB,QAA0C;CAClE,OAAQ,OAAkB,QAAQ,WAAW,CAAC;AAChD;AA6BA,IAAI;;;;;;AAOJ,SAAgB,kBACd,UACgC;CAChC,MAAM,WAAW;CACjB,qBAAqB;CACrB,OAAO;AACT;AAgEA,SAAS,gBACP,SACoB;CACpB,MAAM,SAAS,QAAQ,UAAU,oBAAoB;CACrD,MAAM,aAAa,QAAQ,cAAc,oBAAoB;CAE7D,IAAI,CAAC,UAAU,CAAC,YACd,MAAM,IAAI,MACR,4SAKF;CAGF,OAAO;EAAE;EAAQ;CAAW;AAC9B;AAEA,SAAS,SACP,OACA,QACA,OACQ;CACR,MAAM,OAAO,MAAM,KAChB,MAAM,GAAG,EACT,KAAK,YAAY;EAChB,IAAI,CAAC,QAAQ,WAAW,GAAG,GAAG,OAAO;EAErC,MAAM,OAAO,QAAQ,MAAM,CAAC;EAC5B,MAAM,QAAQ,OAAO;EAErB,IAAI,UAAU,QACZ,MAAM,IAAI,MACR,eAAe,MAAM,KAAK,kBAAkB,MAAM,KAAK,iBAC3C,KAAK,iGAEA,KAAK,SACxB;EAGF,OAAO,mBAAmB,KAAK;CACjC,CAAC,EACA,KAAK,GAAG;CAEX,MAAM,cAAc,IAAI,gBAAgB,KAAK,EAAE,SAAS;CAExD,OAAO,cAAc,GAAG,KAAK,GAAG,g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AS,CAAC;EACV,SAAS,CAAC;EACV,MAAM;EACN,QAAQ;CACV;CAKF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-page-metadata.mjs","names":[],"sources":["../../../../../../../web/src/server/resolve-page-metadata.ts"],"sourcesContent":["/**\r\n * Stage 8 of the page pipeline — METADATA.\r\n *\r\n * Its own file because the behaviour that matters here is about ERRORS, and\r\n * reaching an error path through the full ten-stage pipeline means standing up\r\n * a real Request/Response pair to observe a `try`/`catch`. See\r\n * `resolve-page-metadata.spec.ts`.\r\n *\r\n * ## Why a page's `metadata` never runs after a failed loader\r\n *\r\n * It used to. `design/request-lifecycle.md` said \"exactly one of data/error\r\n * set\", and stage 8 duly called `metadata({ data: undefined, error })` when a\r\n * loader rejected — while `PageMetadata` declared `data` as always present.\r\n * **The type lied**, so the natural way to write a metadata function was also\r\n * the broken way:\r\n *\r\n * ```ts\r\n * export const metadata: PageMetadata<typeof loader> = ({ data }) => ({\r\n * title: \"Home\",\r\n * description: `${data.products.length} products in stock`,\r\n * });\r\n * ```\r\n *\r\n * All three function-form metadata exports in the reference app were written\r\n * exactly like that, and all three turned a loader's real error — a\r\n * `MissingDataSourceError`, say — into `TypeError: Cannot read properties of\r\n * undefined`, reported against a different file in a different subsystem. The\r\n * cost was never the crash; it was that every future debugging session on a\r\n * failed loader would start by investigating the wrong thing.\r\n *\r\n * The alternative was to widen `data` to `| undefined` and make every author\r\n * handle a path almost none of them care about — and without a discriminant,\r\n * TypeScript cannot narrow `data` from `if (error)` anyway, so authors would\r\n * have reached for `data!` and re-created the lie with extra syntax.\r\n *\r\n * So: a page describes a page it actually has. When there is no data there is\r\n * no page-authored description, and the framework supplies\r\n * {@link ERROR_PAGE_METADATA} instead.\r\n *\r\n * ## Partial failure\r\n *\r\n * Stage 7 runs app, layout and page loaders
|
|
1
|
+
{"version":3,"file":"resolve-page-metadata.mjs","names":[],"sources":["../../../../../../../web/src/server/resolve-page-metadata.ts"],"sourcesContent":["/**\r\n * Stage 8 of the page pipeline — METADATA.\r\n *\r\n * Its own file because the behaviour that matters here is about ERRORS, and\r\n * reaching an error path through the full ten-stage pipeline means standing up\r\n * a real Request/Response pair to observe a `try`/`catch`. See\r\n * `resolve-page-metadata.spec.ts`.\r\n *\r\n * ## Why a page's `metadata` never runs after a failed loader\r\n *\r\n * It used to. `design/request-lifecycle.md` said \"exactly one of data/error\r\n * set\", and stage 8 duly called `metadata({ data: undefined, error })` when a\r\n * loader rejected — while `PageMetadata` declared `data` as always present.\r\n * **The type lied**, so the natural way to write a metadata function was also\r\n * the broken way:\r\n *\r\n * ```ts\r\n * export const metadata: PageMetadata<typeof loader> = ({ data }) => ({\r\n * title: \"Home\",\r\n * description: `${data.products.length} products in stock`,\r\n * });\r\n * ```\r\n *\r\n * All three function-form metadata exports in the reference app were written\r\n * exactly like that, and all three turned a loader's real error — a\r\n * `MissingDataSourceError`, say — into `TypeError: Cannot read properties of\r\n * undefined`, reported against a different file in a different subsystem. The\r\n * cost was never the crash; it was that every future debugging session on a\r\n * failed loader would start by investigating the wrong thing.\r\n *\r\n * The alternative was to widen `data` to `| undefined` and make every author\r\n * handle a path almost none of them care about — and without a discriminant,\r\n * TypeScript cannot narrow `data` from `if (error)` anyway, so authors would\r\n * have reached for `data!` and re-created the lie with extra syntax.\r\n *\r\n * So: a page describes a page it actually has. When there is no data there is\r\n * no page-authored description, and the framework supplies\r\n * {@link ERROR_PAGE_METADATA} instead.\r\n *\r\n * ## Partial failure\r\n *\r\n * Stage 7 runs app, layout and page loaders root-to-leaf, so an ancestor\n * rejection prevents the page loader from starting. `failed` is still the\n * relevant guard here: any recorded error means a boundary renders instead of\n * the page, and metadata describes what is on screen. Describing a page the\n * visitor never received is the same defect in a quieter form.\n *\r\n * If per-page error metadata is ever wanted, it is a separate `errorMetadata`\r\n * export — a distinct signature for a distinct situation, not an arm of this\r\n * one. Nothing has asked for it.\r\n */\r\n\r\nimport type { SharedContext } from \"../index\";\r\nimport type { MetadataOutput, PageMetadata } from \"../metadata\";\r\nimport type { PipelineLoader } from \"./execute-page-request\";\r\n\r\n/**\r\n * What `<head>` gets when the page did not render.\r\n *\r\n * `robots` is the load-bearing member, not `title`. An error render is a\r\n * transient server state that happens to be reachable at a real URL; letting a\r\n * crawler index it puts \"Something went wrong\" in a search result for a page\r\n * that works. `title` is a fallback a boundary is free to improve on.\r\n */\r\nexport const ERROR_PAGE_METADATA: MetadataOutput = Object.freeze({\n title: \"Something went wrong\",\r\n robots: \"noindex\",\r\n});\r\n\r\nexport type ResolvePageMetadataInput = {\r\n /** The page module's `metadata` export — absent, object, or function. */\r\n metadata: PageMetadata<PipelineLoader> | undefined;\r\n /** `bundle.pageData`. Read only when `failed` is false. */\r\n data: unknown;\r\n /** The value an earlier stage already recorded. Diagnostics only. */\r\n error: unknown;\r\n /** Whether an earlier stage recorded an error at all. */\r\n failed: boolean;\r\n shared: Readonly<SharedContext>;\r\n};\r\n\r\nexport type ResolvedPageMetadata = {\r\n metadata: MetadataOutput | undefined;\r\n /**\r\n * Set only when the page's own metadata function threw on the SUCCESS path.\r\n * Returned rather than rethrown so the caller can record it the same way a\r\n * loader throw is recorded — the boundary renders and the framework keeps\r\n * ownership of the status, instead of an exception escaping stage 8.\r\n *\r\n * Never set on the error path: nothing runs there that could throw, and an\r\n * error arriving at stage 8 has already won.\r\n */\r\n thrown?: unknown;\r\n};\r\n\r\n/** The function arm of `PageMetadata`, for the one call this module makes. */\r\ntype PageMetadataFunction = Extract<PageMetadata<PipelineLoader>, (...args: never) => unknown>;\r\n\r\nexport function resolvePageMetadata(input: ResolvePageMetadataInput): ResolvedPageMetadata {\r\n if (input.failed) {\r\n return { metadata: ERROR_PAGE_METADATA };\r\n }\r\n\r\n const { metadata } = input;\r\n\r\n if (typeof metadata !== \"function\") {\r\n return { metadata };\r\n }\r\n\r\n try {\r\n return {\r\n metadata: (metadata as PageMetadataFunction)({\r\n data: input.data as Parameters<PageMetadataFunction>[0][\"data\"],\r\n shared: input.shared,\r\n }),\r\n };\r\n } catch (thrown) {\r\n return { metadata: undefined, thrown };\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;AAgEA,MAAa,sBAAsC,OAAO,OAAO;CAC/D,OAAO;CACP,QAAQ;AACV,CAAC;AA+BD,SAAgB,oBAAoB,OAAuD;CACzF,IAAI,MAAM,QACR,OAAO,EAAE,UAAU,oBAAoB;CAGzC,MAAM,EAAE,aAAa;CAErB,IAAI,OAAO,aAAa,YACtB,OAAO,EAAE,SAAS;CAGpB,IAAI;EACF,OAAO,EACL,UAAW,SAAkC;GAC3C,MAAM,MAAM;GACZ,QAAQ,MAAM;EAChB,CAAC,EACH;CACF,SAAS,QAAQ;EACf,OAAO;GAAE,UAAU;GAAW;EAAO;CACvC;AACF"}
|
|
@@ -1 +1,58 @@
|
|
|
1
|
-
|
|
1
|
+
import { PageLevelName } from "./execute-page-request.types.mjs";
|
|
2
|
+
import { Response } from "@warlock.js/core";
|
|
3
|
+
|
|
4
|
+
//#region ../web/src/server/settle-page-response.d.ts
|
|
5
|
+
/** A single committed response header, in application order. */
|
|
6
|
+
type BufferedHeader = {
|
|
7
|
+
key: string;
|
|
8
|
+
value: string;
|
|
9
|
+
};
|
|
10
|
+
/** A single committed response cookie — the shape `applyBufferedCookie` replays. */
|
|
11
|
+
type BufferedCookie = {
|
|
12
|
+
name: string;
|
|
13
|
+
value: unknown;
|
|
14
|
+
options?: Record<string, unknown>;
|
|
15
|
+
};
|
|
16
|
+
/** The two loader short-circuit kinds a buffered response can signal. */
|
|
17
|
+
type LoaderShortCircuitKind = "redirect" | "notFound";
|
|
18
|
+
declare const LOADER_SHORT_CIRCUIT: unique symbol;
|
|
19
|
+
/**
|
|
20
|
+
* What `response.redirect()` / `response.permanentRedirect()` / `response.notFound()`
|
|
21
|
+
* return from inside a loader — a branded value the stage 7 settle scan
|
|
22
|
+
* recognises by symbol, never by shape (so an app returning an
|
|
23
|
+
* accidentally-similar plain object can't be mistaken for one).
|
|
24
|
+
*/
|
|
25
|
+
type LoaderShortCircuitSignal = {
|
|
26
|
+
readonly [LOADER_SHORT_CIRCUIT]: true;
|
|
27
|
+
kind: LoaderShortCircuitKind;
|
|
28
|
+
statusCode: number;
|
|
29
|
+
url?: string;
|
|
30
|
+
body?: unknown;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* The response surface a LOADER sees — never the live core `Response`.
|
|
34
|
+
* `header()`/`cookie()` queue into the level's own buffer; nothing here
|
|
35
|
+
* touches the real reply. `redirect()`/`permanentRedirect()`/`notFound()`
|
|
36
|
+
* queue the buffer's own status (+ `Location`, for the two redirects) AND
|
|
37
|
+
* return the branded signal stage 7 detects — the loader is expected to
|
|
38
|
+
* `return response.redirect(...)`.
|
|
39
|
+
*/
|
|
40
|
+
type BufferedResponse = {
|
|
41
|
+
header(key: string, value: unknown): BufferedResponse;
|
|
42
|
+
headers(bag: Record<string, unknown>): BufferedResponse;
|
|
43
|
+
cookie(name: string, value: unknown, options?: Record<string, unknown>): BufferedResponse;
|
|
44
|
+
setStatusCode(statusCode: number): BufferedResponse;
|
|
45
|
+
redirect(url: string, statusCode?: number): LoaderShortCircuitSignal;
|
|
46
|
+
permanentRedirect(url: string): LoaderShortCircuitSignal;
|
|
47
|
+
notFound(body?: unknown): LoaderShortCircuitSignal;
|
|
48
|
+
};
|
|
49
|
+
/** Stage 7's folded, applied result — what `bundle.commit` carries. */
|
|
50
|
+
type PageResponseCommit = {
|
|
51
|
+
committedLevels: PageLevelName[];
|
|
52
|
+
headers: BufferedHeader[];
|
|
53
|
+
cookies: BufferedCookie[];
|
|
54
|
+
statusCode?: number;
|
|
55
|
+
};
|
|
56
|
+
//#endregion
|
|
57
|
+
export { BufferedCookie, BufferedHeader, BufferedResponse, LoaderShortCircuitKind, PageResponseCommit };
|
|
58
|
+
//# sourceMappingURL=settle-page-response.d.mts.map
|