Skip to content

Commit

Permalink
[Flight] Client and Server Reference Creation into Runtime (facebook#…
Browse files Browse the repository at this point in the history
…27033)

We already did this for Server References on the Client so this brings
us parity with that. This gives us some more flexibility with changing
the runtime implementation without having to affect the loaders.

We can also do more in the runtime such as adding `.bind()` support to
Server References.

I also moved the CommonJS Proxy creation into the runtime helper from
the register so that it can be handled in one place.

This lets us remove the forks from Next.js since the loaders can be
simplified there to just use these helpers.

This PR doesn't change the protocol or shape of the objects. They're
still specific to each bundler but ideally we should probably move this
to shared helpers that can be used by multiple bundler implementations.
  • Loading branch information
sebmarkbage authored and AndyPengc12 committed Apr 15, 2024
1 parent 10dfca5 commit e13059a
Show file tree
Hide file tree
Showing 19 changed files with 455 additions and 282 deletions.
5 changes: 5 additions & 0 deletions packages/react-server-dom-esm/src/ReactFlightDOMServerNode.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ import {

import {decodeAction} from 'react-server/src/ReactFlightActionServer';

export {
registerServerReference,
registerClientReference,
} from './ReactFlightESMReferences';

function createDrainHandler(destination: Destination, request: Request) {
return () => startFlowing(request, destination);
}
Expand Down
31 changes: 18 additions & 13 deletions packages/react-server-dom-esm/src/ReactFlightESMNodeLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,18 +178,20 @@ function transformServerModule(
continue;
}
}

if (localNames.size === 0) {
return source;
}
let newSrc = source + '\n\n;';
newSrc +=
'import {registerServerReference} from "react-server-dom-esm/server";\n';
localNames.forEach(function (exported, local) {
if (localTypes.get(local) !== 'function') {
// We first check if the export is a function and if so annotate it.
newSrc += 'if (typeof ' + local + ' === "function") ';
}
newSrc += 'Object.defineProperties(' + local + ',{';
newSrc += '$$typeof: {value: Symbol.for("react.server.reference")},';
newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + exported) + '},';
newSrc += '$$bound: { value: null }';
newSrc += '});\n';
newSrc += 'registerServerReference(' + local + ',';
newSrc += JSON.stringify(url) + ',';
newSrc += JSON.stringify(exported) + ');\n';
});
return newSrc;
}
Expand Down Expand Up @@ -313,13 +315,17 @@ async function transformClientModule(

await parseExportNamesInto(body, names, url, loader);

if (names.length === 0) {
return '';
}

let newSrc =
"const CLIENT_REFERENCE = Symbol.for('react.client.reference');\n";
'import {registerClientReference} from "react-server-dom-esm/server";\n';
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (name === 'default') {
newSrc += 'export default ';
newSrc += 'Object.defineProperties(function() {';
newSrc += 'registerClientReference(function() {';
newSrc +=
'throw new Error(' +
JSON.stringify(
Expand All @@ -331,7 +337,7 @@ async function transformClientModule(
');';
} else {
newSrc += 'export const ' + name + ' = ';
newSrc += 'Object.defineProperties(function() {';
newSrc += 'registerClientReference(function() {';
newSrc +=
'throw new Error(' +
JSON.stringify(
Expand All @@ -341,10 +347,9 @@ async function transformClientModule(
) +
');';
}
newSrc += '},{';
newSrc += '$$typeof: {value: CLIENT_REFERENCE},';
newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + name) + '}';
newSrc += '});\n';
newSrc += '},';
newSrc += JSON.stringify(url) + ',';
newSrc += JSON.stringify(name) + ');\n';
}
return newSrc;
}
Expand Down
74 changes: 74 additions & 0 deletions packages/react-server-dom-esm/src/ReactFlightESMReferences.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {ReactClientValue} from 'react-server/src/ReactFlightServer';

export type ServerReference<T: Function> = T & {
$$typeof: symbol,
$$id: string,
$$bound: null | Array<ReactClientValue>,
};

// eslint-disable-next-line no-unused-vars
export type ClientReference<T> = {
$$typeof: symbol,
$$id: string,
};

const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');

export function isClientReference(reference: Object): boolean {
return reference.$$typeof === CLIENT_REFERENCE_TAG;
}

export function isServerReference(reference: Object): boolean {
return reference.$$typeof === SERVER_REFERENCE_TAG;
}

export function registerClientReference<T>(
proxyImplementation: any,
id: string,
exportName: string,
): ClientReference<T> {
return Object.defineProperties(proxyImplementation, {
$$typeof: {value: CLIENT_REFERENCE_TAG},
$$id: {value: id + '#' + exportName},
});
}

// $FlowFixMe[method-unbinding]
const FunctionBind = Function.prototype.bind;
// $FlowFixMe[method-unbinding]
const ArraySlice = Array.prototype.slice;
function bind(this: ServerReference<any>) {
// $FlowFixMe[unsupported-syntax]
const newFn = FunctionBind.apply(this, arguments);
if (this.$$typeof === SERVER_REFERENCE_TAG) {
// $FlowFixMe[method-unbinding]
const args = ArraySlice.call(arguments, 1);
newFn.$$typeof = SERVER_REFERENCE_TAG;
newFn.$$id = this.$$id;
newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args;
}
return newFn;
}

export function registerServerReference<T>(
reference: ServerReference<T>,
id: string,
exportName: string,
): ServerReference<T> {
return Object.defineProperties((reference: any), {
$$typeof: {value: SERVER_REFERENCE_TAG},
$$id: {value: id + '#' + exportName},
$$bound: {value: null},
bind: {value: bind},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,16 @@

import type {ReactClientValue} from 'react-server/src/ReactFlightServer';

export type ClientManifest = string; // base URL on the file system
import type {
ClientReference,
ServerReference,
} from './ReactFlightESMReferences';

export type ServerReference<T: Function> = T & {
$$typeof: symbol,
$$id: string,
$$bound: null | Array<ReactClientValue>,
};
export type {ClientReference, ServerReference};

export type ServerReferenceId = string;
export type ClientManifest = string; // base URL on the file system

// eslint-disable-next-line no-unused-vars
export type ClientReference<T> = {
$$typeof: symbol,
$$id: string,
};
export type ServerReferenceId = string;

export type ClientReferenceMetadata = [
string, // module path
Expand All @@ -32,23 +27,14 @@ export type ClientReferenceMetadata = [

export type ClientReferenceKey = string;

const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
export {isClientReference, isServerReference} from './ReactFlightESMReferences';

export function getClientReferenceKey(
reference: ClientReference<any>,
): ClientReferenceKey {
return reference.$$id;
}

export function isClientReference(reference: Object): boolean {
return reference.$$typeof === CLIENT_REFERENCE_TAG;
}

export function isServerReference(reference: Object): boolean {
return reference.$$typeof === SERVER_REFERENCE_TAG;
}

export function resolveClientReferenceMetadata<T>(
config: ClientManifest,
clientReference: ClientReference<T>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ import {

import {decodeAction} from 'react-server/src/ReactFlightActionServer';

export {
registerServerReference,
registerClientReference,
createClientModuleProxy,
} from './ReactFlightWebpackReferences';

type Options = {
identifierPrefix?: string,
signal?: AbortSignal,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ import {

import {decodeAction} from 'react-server/src/ReactFlightActionServer';

export {
registerServerReference,
registerClientReference,
createClientModuleProxy,
} from './ReactFlightWebpackReferences';

type Options = {
identifierPrefix?: string,
signal?: AbortSignal,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ import {

import {decodeAction} from 'react-server/src/ReactFlightActionServer';

export {
registerServerReference,
registerClientReference,
createClientModuleProxy,
} from './ReactFlightWebpackReferences';

function createDrainHandler(destination: Destination, request: Request) {
return () => startFlowing(request, destination);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,19 @@

import type {ReactClientValue} from 'react-server/src/ReactFlightServer';

import type {
ClientReference,
ServerReference,
} from './ReactFlightWebpackReferences';

export type {ClientReference, ServerReference};

export type ClientManifest = {
[id: string]: ClientReferenceMetadata,
};

export type ServerReference<T: Function> = T & {
$$typeof: symbol,
$$id: string,
$$bound: null | Array<ReactClientValue>,
};

export type ServerReferenceId = string;

// eslint-disable-next-line no-unused-vars
export type ClientReference<T> = {
$$typeof: symbol,
$$id: string,
$$async: boolean,
};

export type ClientReferenceMetadata = {
id: string,
chunks: Array<string>,
Expand All @@ -37,23 +31,17 @@ export type ClientReferenceMetadata = {

export type ClientReferenceKey = string;

const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
export {
isClientReference,
isServerReference,
} from './ReactFlightWebpackReferences';

export function getClientReferenceKey(
reference: ClientReference<any>,
): ClientReferenceKey {
return reference.$$async ? reference.$$id + '#async' : reference.$$id;
}

export function isClientReference(reference: Object): boolean {
return reference.$$typeof === CLIENT_REFERENCE_TAG;
}

export function isServerReference(reference: Object): boolean {
return reference.$$typeof === SERVER_REFERENCE_TAG;
}

export function resolveClientReferenceMetadata<T>(
config: ClientManifest,
clientReference: ClientReference<T>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,18 +178,20 @@ function transformServerModule(
continue;
}
}

if (localNames.size === 0) {
return source;
}
let newSrc = source + '\n\n;';
newSrc +=
'import {registerServerReference} from "react-server-dom-webpack/server";\n';
localNames.forEach(function (exported, local) {
if (localTypes.get(local) !== 'function') {
// We first check if the export is a function and if so annotate it.
newSrc += 'if (typeof ' + local + ' === "function") ';
}
newSrc += 'Object.defineProperties(' + local + ',{';
newSrc += '$$typeof: {value: Symbol.for("react.server.reference")},';
newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + exported) + '},';
newSrc += '$$bound: { value: null }';
newSrc += '});\n';
newSrc += 'registerServerReference(' + local + ',';
newSrc += JSON.stringify(url) + ',';
newSrc += JSON.stringify(exported) + ');\n';
});
return newSrc;
}
Expand Down Expand Up @@ -313,13 +315,17 @@ async function transformClientModule(

await parseExportNamesInto(body, names, url, loader);

if (names.length === 0) {
return '';
}

let newSrc =
"const CLIENT_REFERENCE = Symbol.for('react.client.reference');\n";
'import {registerClientReference} from "react-server-dom-webpack/server";\n';
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (name === 'default') {
newSrc += 'export default ';
newSrc += 'Object.defineProperties(function() {';
newSrc += 'registerClientReference(function() {';
newSrc +=
'throw new Error(' +
JSON.stringify(
Expand All @@ -331,7 +337,7 @@ async function transformClientModule(
');';
} else {
newSrc += 'export const ' + name + ' = ';
newSrc += 'Object.defineProperties(function() {';
newSrc += 'registerClientReference(function() {';
newSrc +=
'throw new Error(' +
JSON.stringify(
Expand All @@ -341,10 +347,9 @@ async function transformClientModule(
) +
');';
}
newSrc += '},{';
newSrc += '$$typeof: {value: CLIENT_REFERENCE},';
newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + name) + '}';
newSrc += '});\n';
newSrc += '},';
newSrc += JSON.stringify(url) + ',';
newSrc += JSON.stringify(name) + ');\n';
}
return newSrc;
}
Expand Down
Loading

0 comments on commit e13059a

Please sign in to comment.