| 1 | /**
|
| 2 | * react-router v8.0.0
|
| 3 | *
|
| 4 | * Copyright (c) Remix Software Inc.
|
| 5 | *
|
| 6 | * This source code is licensed under the MIT license found in the
|
| 7 | * LICENSE.md file in the root directory of this source tree.
|
| 8 | *
|
| 9 | * @license MIT
|
| 10 | */
|
| 11 | //#region lib/rsc/html-stream/browser.ts
|
| 12 | /**
|
| 13 | * Get the prerendered [RSC](https://react.dev/reference/rsc/server-components)
|
| 14 | * stream for hydration. Usually passed directly to your
|
| 15 | * `react-server-dom-xyz/client`'s `createFromReadableStream`.
|
| 16 | *
|
| 17 | * @example
|
| 18 | * import { startTransition, StrictMode } from "react";
|
| 19 | * import { hydrateRoot } from "react-dom/client";
|
| 20 | * import {
|
| 21 | * unstable_getRSCStream as getRSCStream,
|
| 22 | * unstable_RSCHydratedRouter as RSCHydratedRouter,
|
| 23 | * } from "react-router";
|
| 24 | * import type { unstable_RSCPayload as RSCPayload } from "react-router";
|
| 25 | *
|
| 26 | * createFromReadableStream(getRSCStream()).then(
|
| 27 | * (payload: RSCServerPayload) => {
|
| 28 | * startTransition(async () => {
|
| 29 | * hydrateRoot(
|
| 30 | * document,
|
| 31 | * <StrictMode>
|
| 32 | * <RSCHydratedRouter {...props} />
|
| 33 | * </StrictMode>,
|
| 34 | * {
|
| 35 | * // Options
|
| 36 | * }
|
| 37 | * );
|
| 38 | * });
|
| 39 | * }
|
| 40 | * );
|
| 41 | *
|
| 42 | * @name unstable_getRSCStream
|
| 43 | * @public
|
| 44 | * @category RSC
|
| 45 | * @mode data
|
| 46 | * @returns A [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
|
| 47 | * that contains the [RSC](https://react.dev/reference/rsc/server-components)
|
| 48 | * data for hydration.
|
| 49 | */
|
| 50 | function getRSCStream() {
|
| 51 | let encoder = new TextEncoder();
|
| 52 | let streamController = null;
|
| 53 | let rscStream = new ReadableStream({ start(controller) {
|
| 54 | if (typeof window === "undefined") return;
|
| 55 | let handleChunk = (chunk) => {
|
| 56 | if (typeof chunk === "string") controller.enqueue(encoder.encode(chunk));
|
| 57 | else controller.enqueue(chunk);
|
| 58 | };
|
| 59 | window.__FLIGHT_DATA ||= [];
|
| 60 | window.__FLIGHT_DATA.forEach(handleChunk);
|
| 61 | window.__FLIGHT_DATA.push = (chunk) => {
|
| 62 | handleChunk(chunk);
|
| 63 | return 0;
|
| 64 | };
|
| 65 | streamController = controller;
|
| 66 | } });
|
| 67 | if (typeof document !== "undefined" && document.readyState === "loading") document.addEventListener("DOMContentLoaded", () => {
|
| 68 | streamController?.close();
|
| 69 | });
|
| 70 | else streamController?.close();
|
| 71 | return rscStream;
|
| 72 | }
|
| 73 | //#endregion
|
| 74 | export { getRSCStream };
|