1. /**
    
  2.  * Copyright (c) Meta Platforms, Inc. and affiliates.
    
  3.  *
    
  4.  * This source code is licensed under the MIT license found in the
    
  5.  * LICENSE file in the root directory of this source tree.
    
  6.  *
    
  7.  * @flow
    
  8.  */
    
  9. 
    
  10. import type {
    
  11.   Request,
    
  12.   ReactClientValue,
    
  13. } from 'react-server/src/ReactFlightServer';
    
  14. import type {Destination} from 'react-server/src/ReactServerStreamConfigNode';
    
  15. import type {ClientManifest} from './ReactFlightServerConfigESMBundler';
    
  16. import type {ServerManifest} from 'react-client/src/ReactFlightClientConfig';
    
  17. import type {Busboy} from 'busboy';
    
  18. import type {Writable} from 'stream';
    
  19. import type {ServerContextJSONValue, Thenable} from 'shared/ReactTypes';
    
  20. 
    
  21. import {
    
  22.   createRequest,
    
  23.   startWork,
    
  24.   startFlowing,
    
  25.   stopFlowing,
    
  26.   abort,
    
  27. } from 'react-server/src/ReactFlightServer';
    
  28. 
    
  29. import {
    
  30.   createResponse,
    
  31.   reportGlobalError,
    
  32.   close,
    
  33.   resolveField,
    
  34.   resolveFileInfo,
    
  35.   resolveFileChunk,
    
  36.   resolveFileComplete,
    
  37.   getRoot,
    
  38. } from 'react-server/src/ReactFlightReplyServer';
    
  39. 
    
  40. import {
    
  41.   decodeAction,
    
  42.   decodeFormState,
    
  43. } from 'react-server/src/ReactFlightActionServer';
    
  44. 
    
  45. export {
    
  46.   registerServerReference,
    
  47.   registerClientReference,
    
  48. } from './ReactFlightESMReferences';
    
  49. 
    
  50. function createDrainHandler(destination: Destination, request: Request) {
    
  51.   return () => startFlowing(request, destination);
    
  52. }
    
  53. 
    
  54. type Options = {
    
  55.   onError?: (error: mixed) => void,
    
  56.   onPostpone?: (reason: string) => void,
    
  57.   context?: Array<[string, ServerContextJSONValue]>,
    
  58.   identifierPrefix?: string,
    
  59. };
    
  60. 
    
  61. type PipeableStream = {
    
  62.   abort(reason: mixed): void,
    
  63.   pipe<T: Writable>(destination: T): T,
    
  64. };
    
  65. 
    
  66. function renderToPipeableStream(
    
  67.   model: ReactClientValue,
    
  68.   moduleBasePath: ClientManifest,
    
  69.   options?: Options,
    
  70. ): PipeableStream {
    
  71.   const request = createRequest(
    
  72.     model,
    
  73.     moduleBasePath,
    
  74.     options ? options.onError : undefined,
    
  75.     options ? options.context : undefined,
    
  76.     options ? options.identifierPrefix : undefined,
    
  77.     options ? options.onPostpone : undefined,
    
  78.   );
    
  79.   let hasStartedFlowing = false;
    
  80.   startWork(request);
    
  81.   return {
    
  82.     pipe<T: Writable>(destination: T): T {
    
  83.       if (hasStartedFlowing) {
    
  84.         throw new Error(
    
  85.           'React currently only supports piping to one writable stream.',
    
  86.         );
    
  87.       }
    
  88.       hasStartedFlowing = true;
    
  89.       startFlowing(request, destination);
    
  90.       destination.on('drain', createDrainHandler(destination, request));
    
  91.       return destination;
    
  92.     },
    
  93.     abort(reason: mixed) {
    
  94.       stopFlowing(request);
    
  95.       abort(request, reason);
    
  96.     },
    
  97.   };
    
  98. }
    
  99. 
    
  100. function decodeReplyFromBusboy<T>(
    
  101.   busboyStream: Busboy,
    
  102.   moduleBasePath: ServerManifest,
    
  103. ): Thenable<T> {
    
  104.   const response = createResponse(moduleBasePath, '');
    
  105.   let pendingFiles = 0;
    
  106.   const queuedFields: Array<string> = [];
    
  107.   busboyStream.on('field', (name, value) => {
    
  108.     if (pendingFiles > 0) {
    
  109.       // Because the 'end' event fires two microtasks after the next 'field'
    
  110.       // we would resolve files and fields out of order. To handle this properly
    
  111.       // we queue any fields we receive until the previous file is done.
    
  112.       queuedFields.push(name, value);
    
  113.     } else {
    
  114.       resolveField(response, name, value);
    
  115.     }
    
  116.   });
    
  117.   busboyStream.on('file', (name, value, {filename, encoding, mimeType}) => {
    
  118.     if (encoding.toLowerCase() === 'base64') {
    
  119.       throw new Error(
    
  120.         "React doesn't accept base64 encoded file uploads because we don't expect " +
    
  121.           "form data passed from a browser to ever encode data that way. If that's " +
    
  122.           'the wrong assumption, we can easily fix it.',
    
  123.       );
    
  124.     }
    
  125.     pendingFiles++;
    
  126.     const file = resolveFileInfo(response, name, filename, mimeType);
    
  127.     value.on('data', chunk => {
    
  128.       resolveFileChunk(response, file, chunk);
    
  129.     });
    
  130.     value.on('end', () => {
    
  131.       resolveFileComplete(response, name, file);
    
  132.       pendingFiles--;
    
  133.       if (pendingFiles === 0) {
    
  134.         // Release any queued fields
    
  135.         for (let i = 0; i < queuedFields.length; i += 2) {
    
  136.           resolveField(response, queuedFields[i], queuedFields[i + 1]);
    
  137.         }
    
  138.         queuedFields.length = 0;
    
  139.       }
    
  140.     });
    
  141.   });
    
  142.   busboyStream.on('finish', () => {
    
  143.     close(response);
    
  144.   });
    
  145.   busboyStream.on('error', err => {
    
  146.     reportGlobalError(
    
  147.       response,
    
  148.       // $FlowFixMe[incompatible-call] types Error and mixed are incompatible
    
  149.       err,
    
  150.     );
    
  151.   });
    
  152.   return getRoot(response);
    
  153. }
    
  154. 
    
  155. function decodeReply<T>(
    
  156.   body: string | FormData,
    
  157.   moduleBasePath: ServerManifest,
    
  158. ): Thenable<T> {
    
  159.   if (typeof body === 'string') {
    
  160.     const form = new FormData();
    
  161.     form.append('0', body);
    
  162.     body = form;
    
  163.   }
    
  164.   const response = createResponse(moduleBasePath, '', body);
    
  165.   const root = getRoot<T>(response);
    
  166.   close(response);
    
  167.   return root;
    
  168. }
    
  169. 
    
  170. export {
    
  171.   renderToPipeableStream,
    
  172.   decodeReplyFromBusboy,
    
  173.   decodeReply,
    
  174.   decodeAction,
    
  175.   decodeFormState,
    
  176. };