@uniflowed/router 0.0.0-alpha.35 → 0.0.0-alpha.37

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/rsc-ssr.js ADDED
@@ -0,0 +1,432 @@
1
+ // @flow
2
+ //
3
+ // `@uniflowed/router/rsc/ssr`: a document, rendered from the payload React
4
+ // Server Components wrote.
5
+ //
6
+ // `virtual:uf/server` imports this entry when routes render as Server
7
+ // Components, which is the default, and `createRenderer` from
8
+ // `@uniflowed/router/server` when they render from their modules
9
+ // (`app.rsc: false`). It is an entry of its own rather than one more export of
10
+ // `./server.js` because it reads the payload with React's Flight client,
11
+ // `react-server-dom-parcel`. That package is an optional peer and needs React
12
+ // 19.3, while the rest of the router runs on the React 19.2.3 that Expo SDK 57
13
+ // and React Native 0.87 ship (ubugeeei-prod/uf#992). A bundler resolves every
14
+ // import in the graph it is given, whether or not anything calls it, so a
15
+ // server bundle that renders no Server Component leaves the package out only if
16
+ // nothing it imports names it. `crates/uf_lib/tests/package_surface.rs` holds
17
+ // the router to that.
18
+ //
19
+ // On an older React the renderer refuses to start, naming the version it found
20
+ // and the one it needs; see `./internal/react-version.js`.
21
+
22
+ import * as React from "react";
23
+
24
+ import { addressOf } from "./internal/base-path.js";
25
+ import {
26
+ type ClientModuleLoader,
27
+ installServerModules,
28
+ readPayload,
29
+ } from "./internal/flight-ssr.js";
30
+ import { FLIGHT_CONTENT_TYPE, flightUrl } from "./internal/flight.js";
31
+ import { type StreamRecord, streamReporter } from "./internal/inspector.js";
32
+ import { requireServerComponentsReact } from "./internal/react-version.js";
33
+ import { RedirectError } from "./internal/routing.js";
34
+ import type { AppProps } from "./internal/runtime.js";
35
+ import { redirectDocument, redirectResult, shellFor } from "./internal/shell.js";
36
+ import { type DocumentBody, prerenderDocument, renderDocument } from "./internal/stream.js";
37
+ import type { FlightRenderer } from "./rsc.js";
38
+ import type {
39
+ FlightResponse,
40
+ PrerenderResult,
41
+ RenderAssets,
42
+ RenderOptions,
43
+ RenderResult,
44
+ Renderer,
45
+ } from "./server.js";
46
+
47
+ /** What `virtual:uf/server` hands the renderer for React Server Components. */
48
+ export type DocumentRendererOptions = {|
49
+ readonly App: React.ComponentType<AppProps>,
50
+ /** The Flight renderer, from the module graph resolved under `react-server`. */
51
+ readonly renderFlight: FlightRenderer,
52
+ /** The server copy of the client module at a browser chunk URL. */
53
+ readonly loadClientModule: ClientModuleLoader,
54
+ |};
55
+
56
+ /**
57
+ * The renderer for an application rendered by React Server Components.
58
+ *
59
+ * [`createRenderer`] renders a route's modules into HTML. This one renders no
60
+ * route module at all: the Flight renderer (`./rsc.js`), in the module graph
61
+ * resolved under `react-server`, renders the route into a payload, and this
62
+ * reads that payload with React's own Flight client and renders what comes
63
+ * out. The same bytes are written into the document as they arrive, so the
64
+ * browser hydrates the tree the server rendered rather than rendering the
65
+ * route's modules a second time — which is what keeps a Server Component's
66
+ * module out of the browser. See ubugeeei-prod/uf#519.
67
+ *
68
+ * The contract with a host is [`Renderer`]'s, unchanged: `render` resolves
69
+ * when the shell is ready with a status and a body, `prerender` resolves with a
70
+ * finished document, and `error` is the exception a route fell back to its
71
+ * error boundary for. It adds `flight`, which answers a browser that is
72
+ * navigating, and `prerender` adds the payload a static host serves for one.
73
+ *
74
+ * # When the shell throws
75
+ *
76
+ * The HTML renderer only ever sees React's serialisation of what a Server
77
+ * Component threw — in a build, a sentence and a digest — and resolving the
78
+ * error boundary needs the exception itself: `forbidden()` is a 403 and a
79
+ * `RedirectError` is a redirect. So the first exception the Flight renderer
80
+ * reports is kept, as thrown, and it is what the error route is resolved for.
81
+ * An exception only the HTML renderer saw — a client component that threw
82
+ * while it rendered on the server — is resolved for as it is.
83
+ */
84
+ export function createDocumentRenderer(options: DocumentRendererOptions): Renderer {
85
+ requireServerComponentsReact("@uniflowed/router/rsc/ssr");
86
+ const { App, renderFlight } = options;
87
+ installServerModules(options.loadClientModule);
88
+
89
+ /**
90
+ * The document for one payload: React's Flight client reads one copy of the
91
+ * stream while the other copy is written into the document.
92
+ */
93
+ async function documentOf(
94
+ stream: ReadableStream<Uint8Array>,
95
+ url: string,
96
+ assets: RenderAssets,
97
+ settings: {|
98
+ readonly onError: (error: mixed) => void,
99
+ readonly transformHead?: (html: string) => Promise<string>,
100
+ readonly onStream?: (record: StreamRecord) => void,
101
+ |},
102
+ ): Promise<DocumentBody> {
103
+ const [forHtml, forBrowser] = stream.tee();
104
+ try {
105
+ return await renderDocument(<App url={url} flight={readPayload(forHtml)} />, {
106
+ shell: shellFor(assets),
107
+ onError: settings.onError,
108
+ transformHead: settings.transformHead,
109
+ onStream: settings.onStream,
110
+ payload: forBrowser,
111
+ });
112
+ } catch (error) {
113
+ void forBrowser.cancel();
114
+ throw error;
115
+ }
116
+ }
117
+
118
+ async function render(
119
+ url: string,
120
+ assets: RenderAssets,
121
+ settings?: RenderOptions,
122
+ ): Promise<RenderResult> {
123
+ const report = settings?.onError ?? (() => {});
124
+ const send = settings?.onStream;
125
+ const onStream = send == null ? undefined : streamReporter(url, send);
126
+ const transformHead = settings?.transformHead;
127
+ const ledger = createErrorLedger();
128
+
129
+ // Held until the shell is known to have survived, for the reason
130
+ // [`createRenderer`] holds them — and dropped rather than reported once the
131
+ // render they came from has been given up for the error boundary. That
132
+ // render goes on reporting while it stops, and nothing it says then is
133
+ // about the response.
134
+ let streaming = false;
135
+ let abandoned = false;
136
+ let held: Array<mixed> = [];
137
+ const onError = (error: mixed) => {
138
+ if (abandoned) {
139
+ return;
140
+ }
141
+ if (streaming) {
142
+ report(error);
143
+ return;
144
+ }
145
+ held.push(error);
146
+ };
147
+
148
+ const stop = new AbortController();
149
+ const rendered = await renderFlight(url, {
150
+ onError: (error: mixed) => {
151
+ onError(error);
152
+ return ledger.record(error);
153
+ },
154
+ signal: stop.signal,
155
+ });
156
+ if (rendered.kind === "redirect") {
157
+ return redirectDocument(new RedirectError(rendered.location, rendered.status === 308));
158
+ }
159
+ let status = rendered.status;
160
+ let failure = rendered.failure;
161
+ let body: DocumentBody;
162
+ try {
163
+ body = await documentOf(rendered.stream, url, assets, {
164
+ onError: (error: mixed) => {
165
+ if (!ledger.isCopy(error)) {
166
+ onError(error);
167
+ }
168
+ },
169
+ transformHead,
170
+ onStream,
171
+ });
172
+ streaming = true;
173
+ for (const error of held) {
174
+ report(error);
175
+ }
176
+ held = [];
177
+ } catch (error) {
178
+ abandoned = true;
179
+ held = [];
180
+ stop.abort();
181
+ const cause = ledger.originalOf(error);
182
+ if (cause instanceof RedirectError) {
183
+ return redirectDocument(cause);
184
+ }
185
+ // Deliberately not caught again: this render is the boundary's own, and a
186
+ // boundary that throws has nothing left to answer with. It reaches
187
+ // `uf dev`'s overlay and fails `uf build`'s route, which is where somebody
188
+ // can fix it.
189
+ const recovered = await renderFlight(url, {
190
+ failure: { error: cause },
191
+ onError: (late: mixed) => {
192
+ report(late);
193
+ return ledger.record(late);
194
+ },
195
+ });
196
+ if (recovered.kind === "redirect") {
197
+ return redirectDocument(new RedirectError(recovered.location, recovered.status === 308));
198
+ }
199
+ status = recovered.status;
200
+ failure = recovered.failure;
201
+ try {
202
+ body = await documentOf(recovered.stream, url, assets, {
203
+ onError: (late: mixed) => {
204
+ if (!ledger.isCopy(late)) {
205
+ report(late);
206
+ }
207
+ },
208
+ transformHead,
209
+ onStream,
210
+ });
211
+ } catch (thrown) {
212
+ // The boundary's own render threw; see `prerender` for why what leaves
213
+ // is the exception as thrown rather than React's copy of it.
214
+ throw ledger.originalOf(thrown);
215
+ }
216
+ }
217
+
218
+ return { status, pipe: body.pipe, stream: body.stream, text: body.text, error: failure };
219
+ }
220
+
221
+ async function prerender(
222
+ url: string,
223
+ assets: RenderAssets,
224
+ settings?: RenderOptions,
225
+ ): Promise<PrerenderResult> {
226
+ const report = settings?.onError ?? (() => {});
227
+ const ledger = createErrorLedger();
228
+ // The Flight renderer's copy of an exception is the one reported, because it
229
+ // is the exception as thrown; the HTML renderer's copy of the same one is
230
+ // recognised by its digest and dropped. See [`createErrorLedger`].
231
+ const onServerError = (error: mixed): string => {
232
+ report(error);
233
+ return ledger.record(error);
234
+ };
235
+ const onHtmlError = (error: mixed) => {
236
+ if (!ledger.isCopy(error)) {
237
+ report(error);
238
+ }
239
+ };
240
+
241
+ // `defer: false`, for the reason [`createRenderer`]'s prerender passes it:
242
+ // a file has no fallback to show first.
243
+ const rendered = await renderFlight(url, { defer: false, onError: onServerError });
244
+ if (rendered.kind === "redirect") {
245
+ return redirectResult(
246
+ redirectDocument(new RedirectError(rendered.location, rendered.status === 308)),
247
+ );
248
+ }
249
+ let status = rendered.status;
250
+ let failure = rendered.failure;
251
+ let payload: Uint8Array;
252
+ let html: string;
253
+ try {
254
+ // Inside the `try`, with the document: a payload the Flight renderer
255
+ // could not finish — a function handed to a client component, say —
256
+ // fails the stream itself, and that is this route's failure like any
257
+ // other.
258
+ payload = await bytesOf(rendered.stream);
259
+ html = await staticDocumentOf(payload, url, assets, onHtmlError);
260
+ } catch (error) {
261
+ const cause = ledger.originalOf(error);
262
+ if (cause instanceof RedirectError) {
263
+ return redirectResult(redirectDocument(cause));
264
+ }
265
+ const recovered = await renderFlight(url, {
266
+ defer: false,
267
+ failure: { error: cause },
268
+ onError: onServerError,
269
+ });
270
+ if (recovered.kind === "redirect") {
271
+ return redirectResult(
272
+ redirectDocument(new RedirectError(recovered.location, recovered.status === 308)),
273
+ );
274
+ }
275
+ status = recovered.status;
276
+ failure = recovered.failure;
277
+ try {
278
+ payload = await bytesOf(recovered.stream);
279
+ html = await staticDocumentOf(payload, url, assets, onHtmlError);
280
+ } catch (thrown) {
281
+ // The boundary's own render threw, and nothing is left to answer with.
282
+ // What leaves is the exception as thrown rather than the copy React's
283
+ // client rebuilt from its row, whose message in a build says only that
284
+ // the real one was omitted — which is all `uf build` would then print.
285
+ throw ledger.originalOf(thrown);
286
+ }
287
+ }
288
+ return { status, html, error: failure, payload };
289
+ }
290
+
291
+ /** A finished document for a finished payload, with the payload written into it. */
292
+ function staticDocumentOf(
293
+ payload: Uint8Array,
294
+ url: string,
295
+ assets: RenderAssets,
296
+ onError: (error: mixed) => void,
297
+ ): Promise<string> {
298
+ return prerenderDocument(<App url={url} flight={readPayload(streamOf(payload))} />, {
299
+ shell: shellFor(assets),
300
+ onError,
301
+ payload: streamOf(payload),
302
+ });
303
+ }
304
+
305
+ async function flight(
306
+ url: string,
307
+ settings?: {| readonly onError?: (error: mixed) => void |},
308
+ ): Promise<FlightResponse> {
309
+ const rendered = await renderFlight(url, { onError: settings?.onError });
310
+ if (rendered.kind === "redirect") {
311
+ const { location } = rendered;
312
+ // A redirect on this origin points at its target's payload, so the
313
+ // browser's `fetch` follows it and lands on one. A redirect elsewhere is
314
+ // left as written: what the browser finds there is not a payload, and it
315
+ // loads the URL as a document instead.
316
+ const onThisOrigin = location.startsWith("/") && !location.startsWith("//");
317
+ return {
318
+ status: rendered.status,
319
+ headers: { location: onThisOrigin ? flightUrl(addressOf(location)) : location },
320
+ stream: null,
321
+ };
322
+ }
323
+ return {
324
+ status: rendered.status,
325
+ headers: { "content-type": FLIGHT_CONTENT_TYPE },
326
+ stream: rendered.stream,
327
+ error: rendered.failure,
328
+ };
329
+ }
330
+
331
+ return { render, prerender, flight };
332
+ }
333
+
334
+ /**
335
+ * Pairs each exception the Flight renderer reports with the copy of it the HTML
336
+ * renderer sees.
337
+ *
338
+ * A Server Component that throws is seen twice. The Flight renderer catches the
339
+ * exception as it was thrown and writes an error row where that part of the
340
+ * tree would have been; React's Flight client reads the row and throws an error
341
+ * rebuilt from it, which is what the HTML renderer sees at the same spot — and
342
+ * in a build, that error's message is a sentence saying the real one was
343
+ * omitted. Reporting both tells a host about one failure twice, once uselessly.
344
+ * Resolving the error boundary for the rebuilt one is worse: `forbidden()`
345
+ * would become a 500 and `redirect()` an error page, because neither survives
346
+ * being rebuilt as a plain `Error`.
347
+ *
348
+ * The row carries a digest, and that is React's field for exactly this: what
349
+ * the Flight renderer's `onError` returns is written into the row and set on the
350
+ * rebuilt error as `digest`. So every exception is recorded here under a digest
351
+ * of its own, and an error the HTML renderer reports with a recorded digest is a
352
+ * copy — dropped from the report, and exchanged for the original when the
353
+ * boundary is resolved.
354
+ *
355
+ * The digest reaches the browser inside the payload, and says nothing: it counts
356
+ * the exceptions one render has recorded.
357
+ */
358
+ function createErrorLedger(): ErrorLedger {
359
+ const originals: Map<string, mixed> = new Map();
360
+ const recorded = (error: mixed): string | null => {
361
+ const digest = digestOf(error);
362
+ return digest != null && originals.has(digest) ? digest : null;
363
+ };
364
+ return {
365
+ record(error: mixed): string {
366
+ const digest = `uf:${originals.size + 1}`;
367
+ originals.set(digest, error);
368
+ return digest;
369
+ },
370
+ isCopy(error: mixed): boolean {
371
+ return recorded(error) != null;
372
+ },
373
+ originalOf(error: mixed): mixed {
374
+ const digest = recorded(error);
375
+ return digest == null ? error : originals.get(digest);
376
+ },
377
+ };
378
+ }
379
+
380
+ /** See [`createErrorLedger`]. */
381
+ type ErrorLedger = {|
382
+ /** Keep an exception the Flight renderer reported, and return its digest. */
383
+ readonly record: (error: mixed) => string,
384
+ /** Whether an error the HTML renderer reported is the copy of a kept one. */
385
+ readonly isCopy: (error: mixed) => boolean,
386
+ /** The exception as thrown, for a copy; any other error, as it is. */
387
+ readonly originalOf: (error: mixed) => mixed,
388
+ |};
389
+
390
+ /** The digest React set on an error, when it set one. */
391
+ function digestOf(error: mixed): string | null {
392
+ if (error == null || typeof error !== "object") {
393
+ return null;
394
+ }
395
+ const tagged: { +digest?: mixed, ... } = (error: $FlowFixMe);
396
+ return typeof tagged.digest === "string" ? tagged.digest : null;
397
+ }
398
+
399
+ /** Every byte of a stream, as one array. */
400
+ async function bytesOf(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
401
+ const reader = stream.getReader();
402
+ const chunks: Array<Uint8Array> = [];
403
+ let total = 0;
404
+ while (true) {
405
+ const step = await reader.read();
406
+ if (step.done === true) {
407
+ break;
408
+ }
409
+ const chunk = step.value;
410
+ if (chunk != null) {
411
+ chunks.push(chunk);
412
+ total += chunk.byteLength;
413
+ }
414
+ }
415
+ const bytes = new Uint8Array(total);
416
+ let at = 0;
417
+ for (const chunk of chunks) {
418
+ bytes.set(chunk, at);
419
+ at += chunk.byteLength;
420
+ }
421
+ return bytes;
422
+ }
423
+
424
+ /** A stream of one array, read as many times as a caller constructs one. */
425
+ function streamOf(bytes: Uint8Array): ReadableStream<Uint8Array> {
426
+ return new ReadableStream({
427
+ start(controller) {
428
+ controller.enqueue(bytes);
429
+ controller.close();
430
+ },
431
+ });
432
+ }
package/rsc.js CHANGED
@@ -57,6 +57,7 @@ import { routeBoundaries } from "./internal/boundary-data.js";
57
57
  import { composeRoute, pageComponent } from "./internal/compose.js";
58
58
  import { ErrorRoutePage } from "./internal/error-view.js";
59
59
  import { type FlightRoot, routeState } from "./internal/flight.js";
60
+ import { requireServerComponentsReact } from "./internal/react-version.js";
60
61
  import type { ErrorModule, PageModule, ResolvedRoute, ResolvedSlot } from "./internal/resolve.js";
61
62
  import { resolveFailure, resolveMatch } from "./internal/resolve.js";
62
63
  import type { RouteParams, RouteTable, SearchParams } from "./internal/routing.js";
@@ -64,6 +65,8 @@ import { RedirectError, nearestBoundary } from "./internal/routing.js";
64
65
  import { withServerRoute } from "./internal/server-route.js";
65
66
 
66
67
  export type { FlightRoot, RouteState } from "./internal/flight.js";
68
+ // For `virtual:uf/rsc`, so a Server Component's `basePath()` is the project's.
69
+ export { installRouting } from "./internal/base-path.js";
67
70
 
68
71
  /** What a host may tell the renderer about one render. */
69
72
  export type FlightOptions = {|
@@ -139,6 +142,9 @@ export function createFlightRenderer(options: {|
139
142
  readonly notFound: RouteTable["notFound"],
140
143
  readonly errors: RouteTable["errors"],
141
144
  |}): FlightRenderer {
145
+ // Before anything else: on a React older than 19.3 nothing below can render,
146
+ // and React's Flight renderer would only say so from inside a render.
147
+ requireServerComponentsReact("@uniflowed/router/rsc");
142
148
  const table: RouteTable = {
143
149
  routes: options.routes,
144
150
  notFound: options.notFound,
@@ -72,6 +72,10 @@ export type {
72
72
  } from "./internal/runtime.js";
73
73
 
74
74
  export { Link, RouteView, RouterProvider, routerView } from "./internal/runtime.js";
75
+ // `app.router.basePath`, for a Server Component that builds an address itself.
76
+ // The rsc entry installs it; `./internal/base-path.js` has no directive, so this
77
+ // graph gets the function rather than a reference to it.
78
+ export { basePath } from "./internal/base-path.js";
75
79
 
76
80
  export {
77
81
  ForbiddenError,