@uniflowed/router 0.0.0-alpha.4 → 0.0.0-alpha.40

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.
Files changed (42) hide show
  1. package/action.js +301 -0
  2. package/client.js +295 -8
  3. package/handler.js +101 -17
  4. package/index.js +71 -4
  5. package/internal/action-endpoint.js +434 -0
  6. package/internal/action-wire.js +608 -0
  7. package/internal/base-path.js +175 -0
  8. package/internal/boundaries.js +481 -0
  9. package/internal/boundary-data.js +88 -0
  10. package/internal/compose.js +490 -0
  11. package/internal/devtools.js +131 -0
  12. package/internal/diagnostics.js +169 -0
  13. package/internal/error-view.js +193 -0
  14. package/internal/flight-browser.js +228 -0
  15. package/internal/flight-chunks.js +205 -0
  16. package/internal/flight-ssr.js +78 -0
  17. package/internal/flight.js +158 -0
  18. package/internal/head.js +219 -0
  19. package/internal/hydration.js +1085 -0
  20. package/internal/inspector.js +626 -0
  21. package/internal/navigation-cache.js +144 -0
  22. package/internal/payload-rows.js +270 -0
  23. package/internal/payload.js +685 -0
  24. package/internal/prepare-document.js +49 -0
  25. package/internal/react-version.js +77 -0
  26. package/internal/request.js +43 -0
  27. package/internal/resolve.js +1615 -0
  28. package/internal/resolved-summary.js +199 -0
  29. package/internal/routing.js +474 -0
  30. package/internal/runtime.js +1511 -543
  31. package/internal/server-route.js +58 -0
  32. package/internal/shell.js +115 -0
  33. package/internal/stream.js +1084 -0
  34. package/middleware.js +350 -0
  35. package/native.js +408 -0
  36. package/package.json +36 -7
  37. package/routing.js +51 -0
  38. package/rsc-client.js +120 -0
  39. package/rsc-ssr.js +440 -0
  40. package/rsc.js +334 -0
  41. package/server-components.js +159 -0
  42. package/server.js +448 -75
package/server.js CHANGED
@@ -3,13 +3,35 @@
3
3
  // Rendering one URL to an HTML document.
4
4
  //
5
5
  // `virtual:uf/server` calls `createRenderer` with the app root and the route
6
- // table, and `uf dev` renders every document request through the result while
7
- // `uf build` renders every static route through it once. Both produce the
6
+ // table, and `uf dev` streams every document request through `render` while
7
+ // `uf build` writes every static route through `prerender`. Both produce the
8
8
  // same markup from the same code, which is the point.
9
+ //
10
+ // # Two entry points, because there are two questions
11
+ //
12
+ // `render` streams and `prerender` waits, and which one a host wants is not a
13
+ // detail of how it was called — it is what the host is *for*. A server has a
14
+ // browser on the other end and a reason to send the layouts and the fallbacks
15
+ // now; a build writes a file that something may later serve to a crawler, and a
16
+ // file whose content is a `<template>` waiting for a script to move it is a
17
+ // file that is blank to everything but a browser.
18
+ //
19
+ // They were one function with `renderToString` behind it, which answered the
20
+ // first question by giving up on it: nothing streamed, so nothing could
21
+ // usefully suspend, so `$loading.js` had nothing to be. Making the split
22
+ // explicit is the point of ubugeeei-prod/uf#254 rather than a side effect —
23
+ // `internal/stream.js` holds the mechanics and says which React renderer serves
24
+ // which.
9
25
 
10
- import { DATA_ID, ROOT_ID } from "./internal/document.js";
26
+ import { noteRoute } from "@uniflowed/server/host";
11
27
  import * as React from "react";
12
- import { renderToString } from "react-dom/server";
28
+
29
+ import {
30
+ type DocumentBody,
31
+ type WritableLike,
32
+ prerenderDocument,
33
+ renderDocument,
34
+ } from "./internal/stream.js";
13
35
 
14
36
  import {
15
37
  type AppProps,
@@ -17,9 +39,15 @@ import {
17
39
  type RouteTable,
18
40
  RedirectError,
19
41
  installRoutes,
42
+ resolveFailure,
20
43
  resolveMatch,
21
44
  } from "./internal/runtime.js";
22
45
 
46
+ import { type StreamDiagnostic, streamReporter } from "./internal/inspector.js";
47
+ import { currentNonce } from "@uniflowed/server/host";
48
+
49
+ import { redirectDocument, redirectResult, shellFor } from "./internal/shell.js";
50
+
23
51
  /** Asset URLs to reference from the document. */
24
52
  export type RenderAssets = {|
25
53
  readonly scripts: $ReadOnlyArray<string>,
@@ -27,113 +55,458 @@ export type RenderAssets = {|
27
55
  readonly preloads: $ReadOnlyArray<string>,
28
56
  |};
29
57
 
30
- /** A rendered document. */
58
+ /**
59
+ * A document that has begun.
60
+ *
61
+ * `status` and `headers` are known once the shell is ready, which is the moment
62
+ * this resolves and is why a streaming renderer can still answer with a status
63
+ * line. The body arrives afterwards, through exactly one of `pipe`, `stream`
64
+ * and `text` — they are three views of one pass over the same chunks, not three
65
+ * copies of the document.
66
+ */
31
67
  export type RenderResult = {|
68
+ readonly status: number,
69
+ readonly headers?: { readonly [string]: string },
70
+ /** Write the document into a Node response. */
71
+ readonly pipe: (destination: WritableLike) => Promise<void>,
72
+ /** The document as a web stream, for `new Response(…)`. */
73
+ readonly stream: () => ReadableStream,
74
+ /** The whole document, once it has finished streaming. */
75
+ readonly text: () => Promise<string>,
76
+ /**
77
+ * The exception this render fell back to its error boundary for.
78
+ *
79
+ * The document is still a document — the boundary rendered — and this is how
80
+ * the caller learns that it is an error page rather than the page it asked
81
+ * for. `uf build` fails the route it names; `uf dev` reports it in the
82
+ * terminal. Without it, containment would mean a build that quietly wrote a
83
+ * directory of error pages and exited 0.
84
+ *
85
+ * `forbidden()` and `unauthorized()` do not set it: those are answers an
86
+ * application chose, and a build that prerendered one has not failed.
87
+ *
88
+ * Only the failures known before the first byte: a loader that threw, or a
89
+ * shell that did. An exception inside a `<Suspense>` boundary happens after
90
+ * this has been read, so it is reported through `render`'s `onError` instead
91
+ * — a streaming renderer cannot put a late failure in a value the caller
92
+ * already has.
93
+ */
94
+ readonly error?: mixed,
95
+ |};
96
+
97
+ /** A document that is finished: every boundary resolved, nothing left to wait for. */
98
+ export type PrerenderResult = {|
32
99
  readonly status: number,
33
100
  readonly html: string,
34
101
  readonly headers?: { readonly [string]: string },
102
+ /** The exception this render fell back to its error boundary for; see [`RenderResult`]. */
103
+ readonly error?: mixed,
104
+ /**
105
+ * The Flight payload the document was rendered from, for a document React
106
+ * Server Components rendered.
107
+ *
108
+ * `uf build` writes it beside the document as the route's payload file, so a
109
+ * browser that navigates to a prerendered route fetches a file rather than
110
+ * asking a server — which is what makes a static host able to serve client
111
+ * navigation at all. Absent for a document rendered from its modules.
112
+ */
113
+ readonly payload?: Uint8Array,
35
114
  |};
36
115
 
37
116
  /**
38
- * Build a `render(url, assets)` for one app.
117
+ * A route's payload, as a browser navigating to it is answered.
118
+ *
119
+ * `stream` is `null` for a redirect, whose `location` is already the target's
120
+ * payload URL when the target is on this origin: `fetch` follows it and lands
121
+ * on a payload.
39
122
  */
123
+ export type FlightResponse = {|
124
+ readonly status: number,
125
+ readonly headers: { readonly [string]: string },
126
+ readonly stream: ReadableStream<Uint8Array> | null,
127
+ /** The exception the route resolved to its error boundary for; see [`RenderResult`]. */
128
+ readonly error?: mixed,
129
+ |};
130
+
131
+ /** What a host may tell the renderer about one request. */
132
+ export type RenderOptions = {|
133
+ /**
134
+ * Every exception React recovered from, including the ones it answered by
135
+ * streaming a boundary's fallback after the response had begun.
136
+ *
137
+ * A callback rather than a field on the result, because that is the shape of
138
+ * the truth: by the time one of these happens the caller is already writing
139
+ * bytes. `uf dev` reports them in the terminal; a production host logs them.
140
+ */
141
+ readonly onError?: (error: mixed) => void,
142
+ /**
143
+ * Rewrite the document opening — the head and, when present, the body start
144
+ * tag — before it goes out.
145
+ *
146
+ * For `uf dev` and nothing else. Vite's `transformIndexHtml` injects
147
+ * `/@vite/client` and the refresh preamble and rewrites asset URLs, and it
148
+ * is a *whole document* hook, so the development server used to collect the
149
+ * page and transform it at the end. That made the one place a developer
150
+ * would notice streaming the one place it did not happen: a slow page showed
151
+ * nothing until it was finished, and `$loading.js` looked broken.
152
+ * See ubugeeei-prod/uf#374.
153
+ *
154
+ * A production host passes nothing here and streams as it always did.
155
+ *
156
+ * # What a plugin that injects into the body gets
157
+ *
158
+ * `transformIndexHtml` is a whole-document hook and this hands it only the
159
+ * parseable opening of the document. Measured against Vite 8.2.2, injecting
160
+ * all four positions into a whole document and into the streamed opening:
161
+ *
162
+ * | `injectTo` | whole document | streamed |
163
+ * | -------------- | ------------------- | -------- |
164
+ * | `head-prepend` | after `<head>` | same |
165
+ * | `head` | before `</head>` | same |
166
+ * | `body-prepend` | after `<body>` | same |
167
+ * | `body` | before `</body>` | after `<body>` |
168
+ *
169
+ * Nothing is dropped — every tag still reaches the document — but a `body`
170
+ * tag lands at the top of the body rather than after the content, because
171
+ * the content is deliberately not passed to the hook. That keeps Vite's
172
+ * parser away from chunk boundaries that may sit inside an attribute.
173
+ *
174
+ * uf's own injections are `head` and `head-prepend`, and Vite's client is
175
+ * head-injected, so this is about a third-party plugin.
176
+ * `packages/vite/dev-head-transform.test.js` pins the table above, so the day
177
+ * it changes is a failing test rather than a surprise.
178
+ */
179
+ readonly transformHead?: (html: string) => Promise<string>,
180
+ /**
181
+ * Told, in words, when a document streamed differently than it did last time.
182
+ *
183
+ * For `uf dev` and nothing else, like `transformHead` above. It answers the
184
+ * half of ubugeeei-prod/uf#520 that is about the wire — what arrived, in what
185
+ * order, and which part of the tree each chunk built — for the stream uf has
186
+ * today, which is a document whose Suspense boundaries resolve independently.
187
+ * `internal/inspector.js` is what it is and what it deliberately is not.
188
+ *
189
+ * A host that passes nothing here records nothing: no recorder is
190
+ * constructed, and the chunks a production stream yields are untouched.
191
+ *
192
+ * It is handed a message and its detail lines rather than the record they
193
+ * came from, because the caller is `@uniflowed/vite` — plain JavaScript, run
194
+ * by Vite before any Flow transform exists, which is why `DEVTOOLS_HOOK` and
195
+ * `DIAGNOSTIC_ENDPOINT` are spelled twice rather than imported. The
196
+ * vocabulary of the report belongs on this side of that line.
197
+ */
198
+ readonly onStream?: (diagnostic: StreamDiagnostic) => void,
199
+ |};
200
+
201
+ /** The two ids the server writes and the client reads. */
40
202
  export { DATA_ID, ROOT_ID } from "./internal/document.js";
41
203
 
204
+ /**
205
+ * How a host begins the request everything below runs inside.
206
+ *
207
+ * Re-exported rather than left to the host to import, and the reason is the
208
+ * one thing about `@uniflowed/server` that is easy to get wrong: the request
209
+ * store is shared by every copy of one *release* of that package, and no more.
210
+ * A host that resolved `@uniflowed/server/host` for itself — from its own
211
+ * `node_modules`, or from outside the bundle a build produced — may hold a
212
+ * different release, and would begin a request in a store the application
213
+ * never reads, so every `cookies()` in it would still be outside one, silently.
214
+ * Handing it out from here makes the copy the host begins with the copy this
215
+ * module dispatches and renders with, because it is the same import.
216
+ *
217
+ * `run` wraps everything that decides the response; `settle` is called once
218
+ * the response has been *written*, which is a different line in every host.
219
+ * `createMiddlewareRunner` and `createDispatcher` refuse to run outside it.
220
+ * See ubugeeei-prod/uf#389.
221
+ */
222
+ export type { RequestLifecycle } from "@uniflowed/server/host";
223
+ export { beginRequest } from "@uniflowed/server/host";
224
+
42
225
  export type { Handler, HandlerContext, HandlerModule, HandlerRecord } from "./handler.js";
43
226
  export { createDispatcher } from "./handler.js";
44
227
 
228
+ export type {
229
+ Middleware,
230
+ MiddlewareContext,
231
+ MiddlewareModule,
232
+ MiddlewareRecord,
233
+ } from "./middleware.js";
234
+ export { createMiddlewareRunner } from "./middleware.js";
235
+
236
+ /**
237
+ * `app.router.basePath` and `trailingSlash`, for `virtual:uf/server` to install
238
+ * before the first render, and `basePath()` for a middleware or a route handler
239
+ * that builds an address itself. See `./internal/base-path.js`.
240
+ */
241
+ export type { RoutingSettings, TrailingSlash } from "./internal/base-path.js";
242
+ export { basePath, installRouting } from "./internal/base-path.js";
243
+
244
+ /**
245
+ * The endpoint a `"use server"` export is dialled at.
246
+ *
247
+ * Here rather than beside `@uniflowed/router/action`, which is the browser's
248
+ * half of the same feature and must stay reachable from a client component:
249
+ * this one refuses outside a request, so it imports `internal/request.js` and
250
+ * through it `node:async_hooks`. The two halves share `internal/action-wire.js`
251
+ * and nothing else, which is what keeps one grammar rather than two.
252
+ *
253
+ * `virtual:uf/server` calls it with the table `virtual:uf/actions` built from
254
+ * the RSC manifest, and every host runs it between the middleware and the
255
+ * route handlers. See `internal/action-endpoint.js` for what the endpoint
256
+ * refuses and why.
257
+ */
258
+ export type { ActionModule, ActionRecord } from "./internal/action-endpoint.js";
259
+ export { createActionDispatcher } from "./internal/action-endpoint.js";
260
+
261
+ /**
262
+ * What a URL turned out to be: a route to render, or a redirect to answer with.
263
+ *
264
+ * Tagged, and returned rather than thrown, because both entry points need the
265
+ * same answer and a redirect is the one thing `resolveMatch` lets out. Without
266
+ * the tag this would be a union of two exact objects and reading either field
267
+ * would be a type error on the branch that does not have it.
268
+ */
269
+ type Resolution =
270
+ | {| readonly kind: "route", readonly route: ResolvedRoute |}
271
+ | {| readonly kind: "redirect", readonly error: RedirectError |};
272
+
273
+ /** The two ways one app answers for a URL. */
274
+ export type Renderer = {|
275
+ readonly render: (
276
+ url: string,
277
+ assets: RenderAssets,
278
+ options?: RenderOptions,
279
+ ) => Promise<RenderResult>,
280
+ readonly prerender: (
281
+ url: string,
282
+ assets: RenderAssets,
283
+ options?: RenderOptions,
284
+ ) => Promise<PrerenderResult>,
285
+ /**
286
+ * A route's payload, for a browser that is navigating rather than loading a
287
+ * document. Only a renderer for React Server Components has one.
288
+ */
289
+ readonly flight?: (
290
+ url: string,
291
+ options?: {| readonly onError?: (error: mixed) => void |},
292
+ ) => Promise<FlightResponse>,
293
+ |};
294
+
45
295
  export function createRenderer(options: {|
46
296
  readonly App: React.ComponentType<AppProps>,
47
297
  readonly routes: RouteTable["routes"],
48
298
  readonly notFound: RouteTable["notFound"],
49
- |}): (url: string, assets: RenderAssets) => Promise<RenderResult> {
50
- const table: RouteTable = { routes: options.routes, notFound: options.notFound };
299
+ readonly errors: RouteTable["errors"],
300
+ |}): Renderer {
301
+ const table: RouteTable = {
302
+ routes: options.routes,
303
+ notFound: options.notFound,
304
+ errors: options.errors,
305
+ };
51
306
  installRoutes(table);
52
307
  const { App } = options;
53
308
 
54
- return async function render(url: string, assets: RenderAssets): Promise<RenderResult> {
55
- let resolved: ResolvedRoute;
309
+ /**
310
+ * The route to render, or the redirect to answer with instead.
311
+ *
312
+ * Shared by both entry points, because *what* a URL resolves to has nothing
313
+ * to do with how the answer is delivered — with one exception, which is
314
+ * `defer` and is the exception that proves it. Whether the router may hand
315
+ * the page a loader that has not answered yet *is* a question about delivery:
316
+ * only a renderer with a `<Suspense>` fallback to send first has anywhere to
317
+ * put the wait. `render` says yes and `prerender` says no; see
318
+ * `ResolveOptions.defer` and ubugeeei-prod/uf#373.
319
+ *
320
+ * Returning the redirect rather than throwing it keeps the two callers from
321
+ * each having to remember that a redirect is the one thing `resolveMatch`
322
+ * lets out.
323
+ *
324
+ * `onMatch` is what makes the request's log line say `/orders/:id` rather
325
+ * than `/orders/8813`. It is handed to `resolveMatch` rather than read off
326
+ * the route this returns, because a loader runs *inside* that call and a
327
+ * loader has things to log: recording the route afterwards would leave every
328
+ * line the loader wrote claiming to belong to no route at all. `noteRoute`
329
+ * does nothing outside a request, which is what lets `prerender` — a build,
330
+ * with no request anywhere — call the same function.
331
+ */
332
+ async function resolve(url: string, defer: boolean): Promise<Resolution> {
56
333
  try {
57
- resolved = await resolveMatch(table, url);
334
+ return {
335
+ kind: "route",
336
+ route: await resolveMatch(table, url, { defer, onMatch: noteRoute }),
337
+ };
58
338
  } catch (error) {
59
339
  if (error instanceof RedirectError) {
60
- return redirectDocument(error);
340
+ return { kind: "redirect", error };
61
341
  }
62
342
  throw error;
63
343
  }
344
+ }
64
345
 
65
- const markup = renderToString(<App url={url} initial={resolved} />);
66
- const html = assemble(markup, resolved, assets);
67
- return { status: resolved.status, html };
68
- };
69
- }
346
+ async function render(
347
+ url: string,
348
+ assets: RenderAssets,
349
+ settings?: RenderOptions,
350
+ ): Promise<RenderResult> {
351
+ const resolution = await resolve(url, true);
352
+ if (resolution.kind === "redirect") {
353
+ return redirectDocument(resolution.error);
354
+ }
355
+ let resolved: ResolvedRoute = resolution.route;
356
+ const report = settings?.onError ?? (() => {});
357
+ // Built once and shared by both renders below, so a page that threw its
358
+ // shell away and rendered its error boundary instead reports the stream the
359
+ // browser was actually sent rather than the one that was abandoned.
360
+ const send = settings?.onStream;
361
+ const onStream = send == null ? undefined : streamReporter(url, send);
362
+ // Read rather than minted: a project that has not asked for a nonce gets
363
+ // `null` and the document it has always had. Read once for both renders
364
+ // below, so the error document a failed shell falls back to carries the
365
+ // same nonce as the policy already on the response.
366
+ const nonce = currentNonce();
70
367
 
71
- function redirectDocument(error: RedirectError): RenderResult {
72
- const target = escapeAttribute(error.to);
73
- return {
74
- status: error.permanent ? 308 : 307,
75
- headers: { Location: error.to },
76
- html: `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="refresh" content="0; url=${target}"><title>Redirecting</title></head><body><a href="${target}">Redirecting…</a></body></html>\n`,
77
- };
78
- }
368
+ // React reports an exception to `onError` *and*, if it was in the shell, to
369
+ // `onShellError` — so forwarding both would tell the host about one failure
370
+ // twice, once through `onError` and once as `result.error` after this
371
+ // re-renders. Errors are held until the shell is known to have survived;
372
+ // if it did not, they are the failure the caller is about to be handed, and
373
+ // the render they came from is being thrown away with them.
374
+ let streaming = false;
375
+ let held: Array<mixed> = [];
376
+ const onError = (error: mixed) => {
377
+ if (streaming) {
378
+ report(error);
379
+ return;
380
+ }
381
+ held.push(error);
382
+ };
79
383
 
80
- /**
81
- * Turn the app's markup into a complete document.
82
- *
83
- * An app whose root layout renders `<html>` owns the whole document, and the
84
- * client hydrates `document`; the scripts and stylesheets are inserted before
85
- * `</head>`. An app that renders only content is wrapped in a minimal shell
86
- * around `<div id="uf-root">`, which is what the client hydrates instead.
87
- */
88
- function assemble(markup: string, resolved: ResolvedRoute, assets: RenderAssets): string {
89
- const head = headTags(assets) + dataScript(resolved.data);
90
- if (/^\s*<html[\s>]/i.test(markup)) {
91
- const document = markup.includes("</head>")
92
- ? markup.replace("</head>", `${head}</head>`)
93
- : markup.replace(/<html([^>]*)>/i, `<html$1><head>${head}</head>`);
94
- return `<!doctype html>\n${document}\n`;
95
- }
96
- const title =
97
- resolved.metadata.title != null ? `<title>${escapeText(resolved.metadata.title)}</title>` : "";
98
- return `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${title}${head}</head><body><div id="${ROOT_ID}">${markup}</div></body></html>\n`;
99
- }
384
+ let body: DocumentBody;
385
+ try {
386
+ body = await renderDocument(<App url={url} initial={resolved} />, {
387
+ shell: shellFor(assets, nonce),
388
+ onError,
389
+ transformHead: settings?.transformHead,
390
+ onStream,
391
+ nonce,
392
+ });
393
+ streaming = true;
394
+ // Recovered before the shell was ready: a `<Suspense>` boundary whose
395
+ // content threw while the shell was still rendering. The response is
396
+ // fine and the host still has to hear about it.
397
+ for (const error of held) {
398
+ report(error);
399
+ }
400
+ held = [];
401
+ } catch (error) {
402
+ // The server's half of the error boundary. React runs a class boundary
403
+ // inside a `<Suspense>` and not outside one, so a throw in the shell —
404
+ // the layouts, or a page with no boundary above it — still reaches here
405
+ // rather than `RouteView`'s. Nothing has been written yet, which is what
406
+ // makes answering with a different document possible at all: `onShellError`
407
+ // fires before the first byte, and once it has not, this is unreachable.
408
+ // See ubugeeei-prod/uf#257.
409
+ if (error instanceof RedirectError) {
410
+ return redirectDocument(error);
411
+ }
412
+ held = [];
413
+ resolved = await resolveFailure(table, url, error);
414
+ // Deliberately not caught again: this render is the boundary's own
415
+ // component, and a boundary that throws has nothing left to answer with.
416
+ // It reaches `uf dev`'s overlay and fails `uf build`'s route, which is
417
+ // where somebody can fix it.
418
+ streaming = true;
419
+ body = await renderDocument(<App url={url} initial={resolved} />, {
420
+ shell: shellFor(assets, nonce),
421
+ onError,
422
+ transformHead: settings?.transformHead,
423
+ onStream,
424
+ nonce,
425
+ });
426
+ }
100
427
 
101
- function headTags(assets: RenderAssets): string {
102
- let tags = "";
103
- for (const href of assets.styles) {
104
- tags += `<link rel="stylesheet" href="${escapeAttribute(href)}">`;
428
+ return {
429
+ status: resolved.status,
430
+ pipe: body.pipe,
431
+ stream: body.stream,
432
+ text: body.text,
433
+ error: renderFailure(resolved),
434
+ };
105
435
  }
106
- for (const href of assets.preloads) {
107
- tags += `<link rel="modulepreload" href="${escapeAttribute(href)}">`;
436
+
437
+ async function prerender(
438
+ url: string,
439
+ assets: RenderAssets,
440
+ settings?: RenderOptions,
441
+ ): Promise<PrerenderResult> {
442
+ const resolution = await resolve(url, false);
443
+ if (resolution.kind === "redirect") {
444
+ return redirectResult(redirectDocument(resolution.error));
445
+ }
446
+ let resolved: ResolvedRoute = resolution.route;
447
+ const report = settings?.onError ?? (() => {});
448
+
449
+ let html: string;
450
+ try {
451
+ html = await prerenderDocument(<App url={url} initial={resolved} />, {
452
+ shell: shellFor(assets),
453
+ onError: report,
454
+ });
455
+ } catch (error) {
456
+ if (error instanceof RedirectError) {
457
+ return redirectResult(redirectDocument(error));
458
+ }
459
+ resolved = await resolveFailure(table, url, error);
460
+ html = await prerenderDocument(<App url={url} initial={resolved} />, {
461
+ shell: shellFor(assets),
462
+ onError: report,
463
+ });
464
+ }
465
+
466
+ return { status: resolved.status, html, error: renderFailure(resolved) };
108
467
  }
109
- for (const src of assets.scripts) {
110
- tags += `<script type="module" src="${escapeAttribute(src)}"></script>`;
468
+
469
+ return { render, prerender };
470
+ }
471
+
472
+ /** The exception a resolved route fell back to its error boundary for. */
473
+ function renderFailure(resolved: ResolvedRoute): mixed {
474
+ if (resolved.error == null) {
475
+ return undefined;
111
476
  }
112
- return tags;
477
+ return match (resolved.error) {
478
+ {kind: "thrown", error: const error} => error,
479
+ {kind: "unauthorized"} => undefined,
480
+ {kind: "forbidden"} => undefined,
481
+ };
113
482
  }
114
483
 
115
484
  /**
116
- * The loader data, embedded for hydration.
485
+ * The document a single-page build writes, and the only one it writes.
486
+ *
487
+ * `app.rendering.modes: ["csr"]` renders no route at build time: the client
488
+ * router resolves and renders every one of them in the browser, so what the
489
+ * build has to leave behind is the *chrome* — the stylesheets, the module
490
+ * script, and the empty root the client renders into. That is exactly
491
+ * [`shellFor`]'s three strings with nothing between them, which is why this is
492
+ * three concatenations rather than a fourth shape of document to keep in step
493
+ * with the other three.
494
+ *
495
+ * No React runs. There is nothing to render: no URL has been asked for, and
496
+ * whatever this document is served for is decided by the host rather than by
497
+ * this build.
498
+ *
499
+ * # What it costs, said here because it is not visible from the file
117
500
  *
118
- * `<` is escaped inside the JSON so a string holding `</script>` cannot end
119
- * the element early, and the script's type keeps the browser from executing
120
- * it.
501
+ * The document has no `<title>`, no `<meta name="description">` and no content.
502
+ * A crawler that runs no JavaScript sees an empty page for **every** URL, and a
503
+ * reader sees nothing until the bundle has loaded and the route has resolved.
504
+ * That is what a single-page application is, and it is why `modes: ["csr"]` is
505
+ * a declaration a project makes rather than something a build falls back to.
506
+ * A project that wants a document per route has `ssg`, and one that wants a
507
+ * document per request has `ssr`.
121
508
  */
122
- function dataScript(data: mixed): string {
123
- if (data === undefined) {
124
- return "";
125
- }
126
- const json = JSON.stringify(data)
127
- .replace(/</g, "\\u003c")
128
- .replace(/\u2028/g, "\\u2028")
129
- .replace(/\u2029/g, "\\u2029");
130
- return `<script id="${DATA_ID}" type="application/json">${json}</script>`;
131
- }
132
-
133
- function escapeAttribute(value: string): string {
134
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
135
- }
136
-
137
- function escapeText(value: string): string {
138
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
509
+ export function shellDocument(assets: RenderAssets): string {
510
+ const shell = shellFor(assets);
511
+ return `${shell.open}${shell.body}${shell.close}`;
139
512
  }