@samitouri / QOS-React-2 / commits / fdc8c81e07

[Flight] Client and Server Reference Creation into Runtime (#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.

Sebastian Markbåge committed Jul 7, 2023 at 11:09 UTC fdc8c81e07e9b3b49604afe524ee6d130fd3e03e
19 files changed +455 -282
packages/react-server-dom-esm/src/ReactFlightDOMServerNode.js
+5
@@ -38,6 +38,11 @@ import {
38
39 import {decodeAction} from 'react-server/src/ReactFlightActionServer';
40
41 +export {
42 + registerServerReference,
43 + registerClientReference,
44 +} from './ReactFlightESMReferences';
45 +
46 function createDrainHandler(destination: Destination, request: Request) {
47 return () => startFlowing(request, destination);
48 }
packages/react-server-dom-esm/src/ReactFlightESMNodeLoader.js
+18 -13
@@ -178,18 +178,20 @@ function transformServerModule(
178 continue;
179 }
180 }
181 -
181 + if (localNames.size === 0) {
182 + return source;
183 + }
184 let newSrc = source + '\n\n;';
185 + newSrc +=
186 + 'import {registerServerReference} from "react-server-dom-esm/server";\n';
187 localNames.forEach(function (exported, local) {
188 if (localTypes.get(local) !== 'function') {
189 // We first check if the export is a function and if so annotate it.
190 newSrc += 'if (typeof ' + local + ' === "function") ';
191 }
188 - newSrc += 'Object.defineProperties(' + local + ',{';
189 - newSrc += '$$typeof: {value: Symbol.for("react.server.reference")},';
190 - newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + exported) + '},';
191 - newSrc += '$$bound: { value: null }';
192 - newSrc += '});\n';
192 + newSrc += 'registerServerReference(' + local + ',';
193 + newSrc += JSON.stringify(url) + ',';
194 + newSrc += JSON.stringify(exported) + ');\n';
195 });
196 return newSrc;
197 }
@@ -313,13 +315,17 @@ async function transformClientModule(
315
316 await parseExportNamesInto(body, names, url, loader);
317
318 + if (names.length === 0) {
319 + return '';
320 + }
321 +
322 let newSrc =
317 - "const CLIENT_REFERENCE = Symbol.for('react.client.reference');\n";
323 + 'import {registerClientReference} from "react-server-dom-esm/server";\n';
324 for (let i = 0; i < names.length; i++) {
325 const name = names[i];
326 if (name === 'default') {
327 newSrc += 'export default ';
322 - newSrc += 'Object.defineProperties(function() {';
328 + newSrc += 'registerClientReference(function() {';
329 newSrc +=
330 'throw new Error(' +
331 JSON.stringify(
@@ -331,7 +337,7 @@ async function transformClientModule(
337 ');';
338 } else {
339 newSrc += 'export const ' + name + ' = ';
334 - newSrc += 'Object.defineProperties(function() {';
340 + newSrc += 'registerClientReference(function() {';
341 newSrc +=
342 'throw new Error(' +
343 JSON.stringify(
@@ -341,10 +347,9 @@ async function transformClientModule(
347 ) +
348 ');';
349 }
344 - newSrc += '},{';
345 - newSrc += '$$typeof: {value: CLIENT_REFERENCE},';
346 - newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + name) + '}';
347 - newSrc += '});\n';
350 + newSrc += '},';
351 + newSrc += JSON.stringify(url) + ',';
352 + newSrc += JSON.stringify(name) + ');\n';
353 }
354 return newSrc;
355 }
packages/react-server-dom-esm/src/ReactFlightESMReferences.js new
+74
@@ -0,0 +1,74 @@
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 {ReactClientValue} from 'react-server/src/ReactFlightServer';
11 +
12 +export type ServerReference<T: Function> = T & {
13 + $$typeof: symbol,
14 + $$id: string,
15 + $$bound: null | Array<ReactClientValue>,
16 +};
17 +
18 +// eslint-disable-next-line no-unused-vars
19 +export type ClientReference<T> = {
20 + $$typeof: symbol,
21 + $$id: string,
22 +};
23 +
24 +const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
25 +const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
26 +
27 +export function isClientReference(reference: Object): boolean {
28 + return reference.$$typeof === CLIENT_REFERENCE_TAG;
29 +}
30 +
31 +export function isServerReference(reference: Object): boolean {
32 + return reference.$$typeof === SERVER_REFERENCE_TAG;
33 +}
34 +
35 +export function registerClientReference<T>(
36 + proxyImplementation: any,
37 + id: string,
38 + exportName: string,
39 +): ClientReference<T> {
40 + return Object.defineProperties(proxyImplementation, {
41 + $$typeof: {value: CLIENT_REFERENCE_TAG},
42 + $$id: {value: id + '#' + exportName},
43 + });
44 +}
45 +
46 +// $FlowFixMe[method-unbinding]
47 +const FunctionBind = Function.prototype.bind;
48 +// $FlowFixMe[method-unbinding]
49 +const ArraySlice = Array.prototype.slice;
50 +function bind(this: ServerReference<any>) {
51 + // $FlowFixMe[unsupported-syntax]
52 + const newFn = FunctionBind.apply(this, arguments);
53 + if (this.$$typeof === SERVER_REFERENCE_TAG) {
54 + // $FlowFixMe[method-unbinding]
55 + const args = ArraySlice.call(arguments, 1);
56 + newFn.$$typeof = SERVER_REFERENCE_TAG;
57 + newFn.$$id = this.$$id;
58 + newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args;
59 + }
60 + return newFn;
61 +}
62 +
63 +export function registerServerReference<T>(
64 + reference: ServerReference<T>,
65 + id: string,
66 + exportName: string,
67 +): ServerReference<T> {
68 + return Object.defineProperties((reference: any), {
69 + $$typeof: {value: SERVER_REFERENCE_TAG},
70 + $$id: {value: id + '#' + exportName},
71 + $$bound: {value: null},
72 + bind: {value: bind},
73 + });
74 +}
packages/react-server-dom-esm/src/ReactFlightServerConfigESMBundler.js
+8 -22
@@ -9,21 +9,16 @@
9
10 import type {ReactClientValue} from 'react-server/src/ReactFlightServer';
11
12 -export type ClientManifest = string; // base URL on the file system
12 +import type {
13 + ClientReference,
14 + ServerReference,
15 +} from './ReactFlightESMReferences';
16
14 -export type ServerReference<T: Function> = T & {
15 - $$typeof: symbol,
16 - $$id: string,
17 - $$bound: null | Array<ReactClientValue>,
18 -};
17 +export type {ClientReference, ServerReference};
18
20 -export type ServerReferenceId = string;
19 +export type ClientManifest = string; // base URL on the file system
20
22 -// eslint-disable-next-line no-unused-vars
23 -export type ClientReference<T> = {
24 - $$typeof: symbol,
25 - $$id: string,
26 -};
21 +export type ServerReferenceId = string;
22
23 export type ClientReferenceMetadata = [
24 string, // module path
@@ -32,8 +27,7 @@ export type ClientReferenceMetadata = [
27
28 export type ClientReferenceKey = string;
29
35 -const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
36 -const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
30 +export {isClientReference, isServerReference} from './ReactFlightESMReferences';
31
32 export function getClientReferenceKey(
33 reference: ClientReference<any>,
@@ -41,14 +35,6 @@ export function getClientReferenceKey(
35 return reference.$$id;
36 }
37
44 -export function isClientReference(reference: Object): boolean {
45 - return reference.$$typeof === CLIENT_REFERENCE_TAG;
46 -}
47 -
48 -export function isServerReference(reference: Object): boolean {
49 - return reference.$$typeof === SERVER_REFERENCE_TAG;
50 -}
51 -
38 export function resolveClientReferenceMetadata<T>(
39 config: ClientManifest,
40 clientReference: ClientReference<T>,
packages/react-server-dom-webpack/src/ReactFlightDOMServerBrowser.js
+6
@@ -27,6 +27,12 @@ import {
27
28 import {decodeAction} from 'react-server/src/ReactFlightActionServer';
29
30 +export {
31 + registerServerReference,
32 + registerClientReference,
33 + createClientModuleProxy,
34 +} from './ReactFlightWebpackReferences';
35 +
36 type Options = {
37 identifierPrefix?: string,
38 signal?: AbortSignal,
packages/react-server-dom-webpack/src/ReactFlightDOMServerEdge.js
+6
@@ -27,6 +27,12 @@ import {
27
28 import {decodeAction} from 'react-server/src/ReactFlightActionServer';
29
30 +export {
31 + registerServerReference,
32 + registerClientReference,
33 + createClientModuleProxy,
34 +} from './ReactFlightWebpackReferences';
35 +
36 type Options = {
37 identifierPrefix?: string,
38 signal?: AbortSignal,
packages/react-server-dom-webpack/src/ReactFlightDOMServerNode.js
+6
@@ -38,6 +38,12 @@ import {
38
39 import {decodeAction} from 'react-server/src/ReactFlightActionServer';
40
41 +export {
42 + registerServerReference,
43 + registerClientReference,
44 + createClientModuleProxy,
45 +} from './ReactFlightWebpackReferences';
46 +
47 function createDrainHandler(destination: Destination, request: Request) {
48 return () => startFlowing(request, destination);
49 }
packages/react-server-dom-webpack/src/ReactFlightServerConfigWebpackBundler.js
+11 -23
@@ -9,25 +9,19 @@
9
10 import type {ReactClientValue} from 'react-server/src/ReactFlightServer';
11
12 +import type {
13 + ClientReference,
14 + ServerReference,
15 +} from './ReactFlightWebpackReferences';
16 +
17 +export type {ClientReference, ServerReference};
18 +
19 export type ClientManifest = {
20 [id: string]: ClientReferenceMetadata,
21 };
22
16 -export type ServerReference<T: Function> = T & {
17 - $$typeof: symbol,
18 - $$id: string,
19 - $$bound: null | Array<ReactClientValue>,
20 -};
21 -
23 export type ServerReferenceId = string;
24
24 -// eslint-disable-next-line no-unused-vars
25 -export type ClientReference<T> = {
26 - $$typeof: symbol,
27 - $$id: string,
28 - $$async: boolean,
29 -};
30 -
25 export type ClientReferenceMetadata = {
26 id: string,
27 chunks: Array<string>,
@@ -37,8 +31,10 @@ export type ClientReferenceMetadata = {
31
32 export type ClientReferenceKey = string;
33
40 -const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
41 -const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
34 +export {
35 + isClientReference,
36 + isServerReference,
37 +} from './ReactFlightWebpackReferences';
38
39 export function getClientReferenceKey(
40 reference: ClientReference<any>,
@@ -46,14 +42,6 @@ export function getClientReferenceKey(
42 return reference.$$async ? reference.$$id + '#async' : reference.$$id;
43 }
44
49 -export function isClientReference(reference: Object): boolean {
50 - return reference.$$typeof === CLIENT_REFERENCE_TAG;
51 -}
52 -
53 -export function isServerReference(reference: Object): boolean {
54 - return reference.$$typeof === SERVER_REFERENCE_TAG;
55 -}
56 -
45 export function resolveClientReferenceMetadata<T>(
46 config: ClientManifest,
47 clientReference: ClientReference<T>,
packages/react-server-dom-webpack/src/ReactFlightWebpackNodeLoader.js
+18 -13
@@ -178,18 +178,20 @@ function transformServerModule(
178 continue;
179 }
180 }
181 -
181 + if (localNames.size === 0) {
182 + return source;
183 + }
184 let newSrc = source + '\n\n;';
185 + newSrc +=
186 + 'import {registerServerReference} from "react-server-dom-webpack/server";\n';
187 localNames.forEach(function (exported, local) {
188 if (localTypes.get(local) !== 'function') {
189 // We first check if the export is a function and if so annotate it.
190 newSrc += 'if (typeof ' + local + ' === "function") ';
191 }
188 - newSrc += 'Object.defineProperties(' + local + ',{';
189 - newSrc += '$$typeof: {value: Symbol.for("react.server.reference")},';
190 - newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + exported) + '},';
191 - newSrc += '$$bound: { value: null }';
192 - newSrc += '});\n';
192 + newSrc += 'registerServerReference(' + local + ',';
193 + newSrc += JSON.stringify(url) + ',';
194 + newSrc += JSON.stringify(exported) + ');\n';
195 });
196 return newSrc;
197 }
@@ -313,13 +315,17 @@ async function transformClientModule(
315
316 await parseExportNamesInto(body, names, url, loader);
317
318 + if (names.length === 0) {
319 + return '';
320 + }
321 +
322 let newSrc =
317 - "const CLIENT_REFERENCE = Symbol.for('react.client.reference');\n";
323 + 'import {registerClientReference} from "react-server-dom-webpack/server";\n';
324 for (let i = 0; i < names.length; i++) {
325 const name = names[i];
326 if (name === 'default') {
327 newSrc += 'export default ';
322 - newSrc += 'Object.defineProperties(function() {';
328 + newSrc += 'registerClientReference(function() {';
329 newSrc +=
330 'throw new Error(' +
331 JSON.stringify(
@@ -331,7 +337,7 @@ async function transformClientModule(
337 ');';
338 } else {
339 newSrc += 'export const ' + name + ' = ';
334 - newSrc += 'Object.defineProperties(function() {';
340 + newSrc += 'registerClientReference(function() {';
341 newSrc +=
342 'throw new Error(' +
343 JSON.stringify(
@@ -341,10 +347,9 @@ async function transformClientModule(
347 ) +
348 ');';
349 }
344 - newSrc += '},{';
345 - newSrc += '$$typeof: {value: CLIENT_REFERENCE},';
346 - newSrc += '$$id: {value: ' + JSON.stringify(url + '#' + name) + '}';
347 - newSrc += '});\n';
350 + newSrc += '},';
351 + newSrc += JSON.stringify(url) + ',';
352 + newSrc += JSON.stringify(name) + ');\n';
353 }
354 return newSrc;
355 }
packages/react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js
+10 -209
@@ -14,198 +14,9 @@ const url = require('url');
14 const Module = require('module');
15
16 module.exports = function register() {
17 - const CLIENT_REFERENCE = Symbol.for('react.client.reference');
18 - const SERVER_REFERENCE = Symbol.for('react.server.reference');
19 - const PROMISE_PROTOTYPE = Promise.prototype;
20 -
21 - // Patch bind on the server to ensure that this creates another
22 - // bound server reference with the additional arguments.
23 - const originalBind = Function.prototype.bind;
24 - /*eslint-disable no-extend-native */
25 - Function.prototype.bind = (function bind(this: any, self: any) {
26 - // $FlowFixMe[unsupported-syntax]
27 - const newFn = originalBind.apply(this, arguments);
28 - if (this.$$typeof === SERVER_REFERENCE) {
29 - // $FlowFixMe[method-unbinding]
30 - const args = Array.prototype.slice.call(arguments, 1);
31 - newFn.$$typeof = SERVER_REFERENCE;
32 - newFn.$$id = this.$$id;
33 - newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args;
34 - }
35 - return newFn;
36 - }: any);
37 -
38 - const deepProxyHandlers = {
39 - get: function (target: Function, name: string, receiver: Proxy<Function>) {
40 - switch (name) {
41 - // These names are read by the Flight runtime if you end up using the exports object.
42 - case '$$typeof':
43 - // These names are a little too common. We should probably have a way to
44 - // have the Flight runtime extract the inner target instead.
45 - return target.$$typeof;
46 - case '$$id':
47 - return target.$$id;
48 - case '$$async':
49 - return target.$$async;
50 - case 'name':
51 - return target.name;
52 - case 'displayName':
53 - return undefined;
54 - // We need to special case this because createElement reads it if we pass this
55 - // reference.
56 - case 'defaultProps':
57 - return undefined;
58 - // Avoid this attempting to be serialized.
59 - case 'toJSON':
60 - return undefined;
61 - case Symbol.toPrimitive:
62 - // $FlowFixMe[prop-missing]
63 - return Object.prototype[Symbol.toPrimitive];
64 - case 'Provider':
65 - throw new Error(
66 - `Cannot render a Client Context Provider on the Server. ` +
67 - `Instead, you can export a Client Component wrapper ` +
68 - `that itself renders a Client Context Provider.`,
69 - );
70 - }
71 - // eslint-disable-next-line react-internal/safe-string-coercion
72 - const expression = String(target.name) + '.' + String(name);
73 - throw new Error(
74 - `Cannot access ${expression} on the server. ` +
75 - 'You cannot dot into a client module from a server component. ' +
76 - 'You can only pass the imported name through.',
77 - );
78 - },
79 - set: function () {
80 - throw new Error('Cannot assign to a client module from a server module.');
81 - },
82 - };
83 -
84 - const proxyHandlers = {
85 - get: function (
86 - target: Function,
87 - name: string,
88 - receiver: Proxy<Function>,
89 - ): $FlowFixMe {
90 - switch (name) {
91 - // These names are read by the Flight runtime if you end up using the exports object.
92 - case '$$typeof':
93 - return target.$$typeof;
94 - case '$$id':
95 - return target.$$id;
96 - case '$$async':
97 - return target.$$async;
98 - case 'name':
99 - return target.name;
100 - // We need to special case this because createElement reads it if we pass this
101 - // reference.
102 - case 'defaultProps':
103 - return undefined;
104 - // Avoid this attempting to be serialized.
105 - case 'toJSON':
106 - return undefined;
107 - case Symbol.toPrimitive:
108 - // $FlowFixMe[prop-missing]
109 - return Object.prototype[Symbol.toPrimitive];
110 - case '__esModule':
111 - // Something is conditionally checking which export to use. We'll pretend to be
112 - // an ESM compat module but then we'll check again on the client.
113 - const moduleId = target.$$id;
114 - target.default = Object.defineProperties(
115 - (function () {
116 - throw new Error(
117 - `Attempted to call the default export of ${moduleId} from the server ` +
118 - `but it's on the client. It's not possible to invoke a client function from ` +
119 - `the server, it can only be rendered as a Component or passed to props of a ` +
120 - `Client Component.`,
121 - );
122 - }: any),
123 - {
124 - $$typeof: {value: CLIENT_REFERENCE},
125 - // This a placeholder value that tells the client to conditionally use the
126 - // whole object or just the default export.
127 - $$id: {value: target.$$id + '#'},
128 - $$async: {value: target.$$async},
129 - },
130 - );
131 - return true;
132 - case 'then':
133 - if (target.then) {
134 - // Use a cached value
135 - return target.then;
136 - }
137 - if (!target.$$async) {
138 - // If this module is expected to return a Promise (such as an AsyncModule) then
139 - // we should resolve that with a client reference that unwraps the Promise on
140 - // the client.
141 -
142 - const clientReference = Object.defineProperties(({}: any), {
143 - $$typeof: {value: CLIENT_REFERENCE},
144 - $$id: {value: target.$$id},
145 - $$async: {value: true},
146 - });
147 - const proxy = new Proxy(clientReference, proxyHandlers);
148 -
149 - // Treat this as a resolved Promise for React's use()
150 - target.status = 'fulfilled';
151 - target.value = proxy;
152 -
153 - const then = (target.then = Object.defineProperties(
154 - (function then(resolve, reject: any) {
155 - // Expose to React.
156 - return Promise.resolve(resolve(proxy));
157 - }: any),
158 - // If this is not used as a Promise but is treated as a reference to a `.then`
159 - // export then we should treat it as a reference to that name.
160 - {
161 - $$typeof: {value: CLIENT_REFERENCE},
162 - $$id: {value: target.$$id + '#then'},
163 - $$async: {value: false},
164 - },
165 - ));
166 - return then;
167 - } else {
168 - // Since typeof .then === 'function' is a feature test we'd continue recursing
169 - // indefinitely if we return a function. Instead, we return an object reference
170 - // if we check further.
171 - return undefined;
172 - }
173 - }
174 - let cachedReference = target[name];
175 - if (!cachedReference) {
176 - const reference = Object.defineProperties(
177 - (function () {
178 - throw new Error(
179 - // eslint-disable-next-line react-internal/safe-string-coercion
180 - `Attempted to call ${String(name)}() from the server but ${String(
181 - name,
182 - )} is on the client. ` +
183 - `It's not possible to invoke a client function from the server, it can ` +
184 - `only be rendered as a Component or passed to props of a Client Component.`,
185 - );
186 - }: any),
187 - {
188 - name: {value: name},
189 - $$typeof: {value: CLIENT_REFERENCE},
190 - $$id: {value: target.$$id + '#' + name},
191 - $$async: {value: target.$$async},
192 - },
193 - );
194 - cachedReference = target[name] = new Proxy(
195 - reference,
196 - deepProxyHandlers,
197 - );
198 - }
199 - return cachedReference;
200 - },
201 - getPrototypeOf(target: Function): Object {
202 - // Pretend to be a Promise in case anyone asks.
203 - return PROMISE_PROTOTYPE;
204 - },
205 - set: function (): empty {
206 - throw new Error('Cannot assign to a client module from a server module.');
207 - },
208 - };
17 + const Server: any = require('react-server-dom-webpack/server');
18 + const registerServerReference = Server.registerServerReference;
19 + const createClientModuleProxy = Server.createClientModuleProxy;
20
21 // $FlowFixMe[prop-missing] found when upgrading Flow
22 const originalCompile = Module.prototype._compile;
@@ -264,13 +75,7 @@ module.exports = function register() {
75
76 if (useClient) {
77 const moduleId: string = (url.pathToFileURL(filename).href: any);
267 - const clientReference = Object.defineProperties(({}: any), {
268 - $$typeof: {value: CLIENT_REFERENCE},
269 - // Represents the whole Module object instead of a particular import.
270 - $$id: {value: moduleId},
271 - $$async: {value: false},
272 - });
273 - this.exports = new Proxy(clientReference, proxyHandlers);
78 + this.exports = createClientModuleProxy(moduleId);
79 }
80
81 if (useServer) {
@@ -284,23 +89,19 @@ module.exports = function register() {
89 // reference. If there are any functions in the export.
90 if (typeof exports === 'function') {
91 // The module exports a function directly,
287 - Object.defineProperties((exports: any), {
288 - $$typeof: {value: SERVER_REFERENCE},
92 + registerServerReference(
93 + (exports: any),
94 + moduleId,
95 // Represents the whole Module object instead of a particular import.
290 - $$id: {value: moduleId},
291 - $$bound: {value: null},
292 - });
96 + null,
97 + );
98 } else {
99 const keys = Object.keys(exports);
100 for (let i = 0; i < keys.length; i++) {
101 const key = keys[i];
102 const value = exports[keys[i]];
103 if (typeof value === 'function') {
299 - Object.defineProperties((value: any), {
300 - $$typeof: {value: SERVER_REFERENCE},
301 - $$id: {value: moduleId + '#' + key},
302 - $$bound: {value: null},
303 - });
104 + registerServerReference((value: any), moduleId, key);
105 }
106 }
107 }
packages/react-server-dom-webpack/src/ReactFlightWebpackReferences.js new
+256
@@ -0,0 +1,256 @@
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 {ReactClientValue} from 'react-server/src/ReactFlightServer';
11 +
12 +export type ServerReference<T: Function> = T & {
13 + $$typeof: symbol,
14 + $$id: string,
15 + $$bound: null | Array<ReactClientValue>,
16 +};
17 +
18 +// eslint-disable-next-line no-unused-vars
19 +export type ClientReference<T> = {
20 + $$typeof: symbol,
21 + $$id: string,
22 + $$async: boolean,
23 +};
24 +
25 +const CLIENT_REFERENCE_TAG = Symbol.for('react.client.reference');
26 +const SERVER_REFERENCE_TAG = Symbol.for('react.server.reference');
27 +
28 +export function isClientReference(reference: Object): boolean {
29 + return reference.$$typeof === CLIENT_REFERENCE_TAG;
30 +}
31 +
32 +export function isServerReference(reference: Object): boolean {
33 + return reference.$$typeof === SERVER_REFERENCE_TAG;
34 +}
35 +
36 +export function registerClientReference<T>(
37 + proxyImplementation: any,
38 + id: string,
39 + exportName: string,
40 +): ClientReference<T> {
41 + return registerClientReferenceImpl(
42 + proxyImplementation,
43 + id + '#' + exportName,
44 + false,
45 + );
46 +}
47 +
48 +function registerClientReferenceImpl<T>(
49 + proxyImplementation: any,
50 + id: string,
51 + async: boolean,
52 +): ClientReference<T> {
53 + return Object.defineProperties(proxyImplementation, {
54 + $$typeof: {value: CLIENT_REFERENCE_TAG},
55 + $$id: {value: id},
56 + $$async: {value: async},
57 + });
58 +}
59 +
60 +// $FlowFixMe[method-unbinding]
61 +const FunctionBind = Function.prototype.bind;
62 +// $FlowFixMe[method-unbinding]
63 +const ArraySlice = Array.prototype.slice;
64 +function bind(this: ServerReference<any>) {
65 + // $FlowFixMe[unsupported-syntax]
66 + const newFn = FunctionBind.apply(this, arguments);
67 + if (this.$$typeof === SERVER_REFERENCE_TAG) {
68 + const args = ArraySlice.call(arguments, 1);
69 + newFn.$$typeof = SERVER_REFERENCE_TAG;
70 + newFn.$$id = this.$$id;
71 + newFn.$$bound = this.$$bound ? this.$$bound.concat(args) : args;
72 + }
73 + return newFn;
74 +}
75 +
76 +export function registerServerReference<T>(
77 + reference: ServerReference<T>,
78 + id: string,
79 + exportName: null | string,
80 +): ServerReference<T> {
81 + return Object.defineProperties((reference: any), {
82 + $$typeof: {value: SERVER_REFERENCE_TAG},
83 + $$id: {value: exportName === null ? id : id + '#' + exportName},
84 + $$bound: {value: null},
85 + bind: {value: bind},
86 + });
87 +}
88 +
89 +const PROMISE_PROTOTYPE = Promise.prototype;
90 +
91 +const deepProxyHandlers = {
92 + get: function (target: Function, name: string, receiver: Proxy<Function>) {
93 + switch (name) {
94 + // These names are read by the Flight runtime if you end up using the exports object.
95 + case '$$typeof':
96 + // These names are a little too common. We should probably have a way to
97 + // have the Flight runtime extract the inner target instead.
98 + return target.$$typeof;
99 + case '$$id':
100 + return target.$$id;
101 + case '$$async':
102 + return target.$$async;
103 + case 'name':
104 + return target.name;
105 + case 'displayName':
106 + return undefined;
107 + // We need to special case this because createElement reads it if we pass this
108 + // reference.
109 + case 'defaultProps':
110 + return undefined;
111 + // Avoid this attempting to be serialized.
112 + case 'toJSON':
113 + return undefined;
114 + case Symbol.toPrimitive:
115 + // $FlowFixMe[prop-missing]
116 + return Object.prototype[Symbol.toPrimitive];
117 + case 'Provider':
118 + throw new Error(
119 + `Cannot render a Client Context Provider on the Server. ` +
120 + `Instead, you can export a Client Component wrapper ` +
121 + `that itself renders a Client Context Provider.`,
122 + );
123 + }
124 + // eslint-disable-next-line react-internal/safe-string-coercion
125 + const expression = String(target.name) + '.' + String(name);
126 + throw new Error(
127 + `Cannot access ${expression} on the server. ` +
128 + 'You cannot dot into a client module from a server component. ' +
129 + 'You can only pass the imported name through.',
130 + );
131 + },
132 + set: function () {
133 + throw new Error('Cannot assign to a client module from a server module.');
134 + },
135 +};
136 +
137 +const proxyHandlers = {
138 + get: function (
139 + target: Function,
140 + name: string,
141 + receiver: Proxy<Function>,
142 + ): $FlowFixMe {
143 + switch (name) {
144 + // These names are read by the Flight runtime if you end up using the exports object.
145 + case '$$typeof':
146 + return target.$$typeof;
147 + case '$$id':
148 + return target.$$id;
149 + case '$$async':
150 + return target.$$async;
151 + case 'name':
152 + return target.name;
153 + // We need to special case this because createElement reads it if we pass this
154 + // reference.
155 + case 'defaultProps':
156 + return undefined;
157 + // Avoid this attempting to be serialized.
158 + case 'toJSON':
159 + return undefined;
160 + case Symbol.toPrimitive:
161 + // $FlowFixMe[prop-missing]
162 + return Object.prototype[Symbol.toPrimitive];
163 + case '__esModule':
164 + // Something is conditionally checking which export to use. We'll pretend to be
165 + // an ESM compat module but then we'll check again on the client.
166 + const moduleId = target.$$id;
167 + target.default = registerClientReferenceImpl(
168 + (function () {
169 + throw new Error(
170 + `Attempted to call the default export of ${moduleId} from the server ` +
171 + `but it's on the client. It's not possible to invoke a client function from ` +
172 + `the server, it can only be rendered as a Component or passed to props of a ` +
173 + `Client Component.`,
174 + );
175 + }: any),
176 + target.$$id + '#',
177 + target.$$async,
178 + );
179 + return true;
180 + case 'then':
181 + if (target.then) {
182 + // Use a cached value
183 + return target.then;
184 + }
185 + if (!target.$$async) {
186 + // If this module is expected to return a Promise (such as an AsyncModule) then
187 + // we should resolve that with a client reference that unwraps the Promise on
188 + // the client.
189 +
190 + const clientReference: ClientReference<any> =
191 + registerClientReferenceImpl(({}: any), target.$$id, true);
192 + const proxy = new Proxy(clientReference, proxyHandlers);
193 +
194 + // Treat this as a resolved Promise for React's use()
195 + target.status = 'fulfilled';
196 + target.value = proxy;
197 +
198 + const then = (target.then = registerClientReferenceImpl(
199 + (function then(resolve, reject: any) {
200 + // Expose to React.
201 + return Promise.resolve(resolve(proxy));
202 + }: any),
203 + // If this is not used as a Promise but is treated as a reference to a `.then`
204 + // export then we should treat it as a reference to that name.
205 + target.$$id + '#then',
206 + false,
207 + ));
208 + return then;
209 + } else {
210 + // Since typeof .then === 'function' is a feature test we'd continue recursing
211 + // indefinitely if we return a function. Instead, we return an object reference
212 + // if we check further.
213 + return undefined;
214 + }
215 + }
216 + let cachedReference = target[name];
217 + if (!cachedReference) {
218 + const reference: ClientReference<any> = registerClientReferenceImpl(
219 + (function () {
220 + throw new Error(
221 + // eslint-disable-next-line react-internal/safe-string-coercion
222 + `Attempted to call ${String(name)}() from the server but ${String(
223 + name,
224 + )} is on the client. ` +
225 + `It's not possible to invoke a client function from the server, it can ` +
226 + `only be rendered as a Component or passed to props of a Client Component.`,
227 + );
228 + }: any),
229 + target.$$id + '#' + name,
230 + target.$$async,
231 + );
232 + Object.defineProperty((reference: any), 'name', {value: name});
233 + cachedReference = target[name] = new Proxy(reference, deepProxyHandlers);
234 + }
235 + return cachedReference;
236 + },
237 + getPrototypeOf(target: Function): Object {
238 + // Pretend to be a Promise in case anyone asks.
239 + return PROMISE_PROTOTYPE;
240 + },
241 + set: function (): empty {
242 + throw new Error('Cannot assign to a client module from a server module.');
243 + },
244 +};
245 +
246 +export function createClientModuleProxy<T>(
247 + moduleId: string,
248 +): ClientReference<T> {
249 + const clientReference: ClientReference<T> = registerClientReferenceImpl(
250 + ({}: any),
251 + // Represents the whole Module object instead of a particular import.
252 + moduleId,
253 + false,
254 + );
255 + return new Proxy(clientReference, proxyHandlers);
256 +}
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOM-test.js
+8 -1
@@ -36,6 +36,14 @@ let ErrorBoundary;
36 describe('ReactFlightDOM', () => {
37 beforeEach(() => {
38 jest.resetModules();
39 +
40 + // Simulate the condition resolution
41 + jest.mock('react-server-dom-webpack/server', () =>
42 + require('react-server-dom-webpack/server.node.unbundled'),
43 + );
44 +
45 + ReactServerDOMClient = require('react-server-dom-webpack/client');
46 +
47 act = require('internal-test-utils').act;
48 const WebpackMock = require('./utils/WebpackMock');
49 clientExports = WebpackMock.clientExports;
@@ -49,7 +57,6 @@ describe('ReactFlightDOM', () => {
57 use = React.use;
58 Suspense = React.Suspense;
59 ReactDOMClient = require('react-dom/client');
52 - ReactServerDOMClient = require('react-server-dom-webpack/client');
60 ReactServerDOMServer = require('react-server-dom-webpack/server.node.unbundled');
61
62 ErrorBoundary = class extends React.Component {
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMBrowser-test.js
+6
@@ -32,6 +32,12 @@ let use;
32 describe('ReactFlightDOMBrowser', () => {
33 beforeEach(() => {
34 jest.resetModules();
35 +
36 + // Simulate the condition resolution
37 + jest.mock('react-server-dom-webpack/server', () =>
38 + require('react-server-dom-webpack/server.browser'),
39 + );
40 +
41 act = require('internal-test-utils').act;
42 const WebpackMock = require('./utils/WebpackMock');
43 clientExports = WebpackMock.clientExports;
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMEdge-test.js
+6
@@ -31,6 +31,12 @@ let use;
31 describe('ReactFlightDOMEdge', () => {
32 beforeEach(() => {
33 jest.resetModules();
34 +
35 + // Simulate the condition resolution
36 + jest.mock('react-server-dom-webpack/server', () =>
37 + require('react-server-dom-webpack/server.edge'),
38 + );
39 +
40 const WebpackMock = require('./utils/WebpackMock');
41 clientExports = WebpackMock.clientExports;
42 webpackMap = WebpackMock.webpackMap;
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMForm-test.js
+4
@@ -32,6 +32,10 @@ let ReactServerDOMClient;
32 describe('ReactFlightDOMForm', () => {
33 beforeEach(() => {
34 jest.resetModules();
35 + // Simulate the condition resolution
36 + jest.mock('react-server-dom-webpack/server', () =>
37 + require('react-server-dom-webpack/server.edge'),
38 + );
39 const WebpackMock = require('./utils/WebpackMock');
40 serverExports = WebpackMock.serverExports;
41 webpackServerMap = WebpackMock.webpackServerMap;
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMNode-test.js
+6
@@ -26,6 +26,12 @@ let use;
26 describe('ReactFlightDOMNode', () => {
27 beforeEach(() => {
28 jest.resetModules();
29 +
30 + // Simulate the condition resolution
31 + jest.mock('react-server-dom-webpack/server', () =>
32 + require('react-server-dom-webpack/server.node'),
33 + );
34 +
35 const WebpackMock = require('./utils/WebpackMock');
36 clientExports = WebpackMock.clientExports;
37 webpackMap = WebpackMock.webpackMap;
packages/react-server-dom-webpack/src/__tests__/ReactFlightDOMReply-test.js
+4
@@ -23,6 +23,10 @@ let ReactServerDOMClient;
23 describe('ReactFlightDOMReply', () => {
24 beforeEach(() => {
25 jest.resetModules();
26 + // Simulate the condition resolution
27 + jest.mock('react-server-dom-webpack/server', () =>
28 + require('react-server-dom-webpack/server.browser'),
29 + );
30 const WebpackMock = require('./utils/WebpackMock');
31 // serverExports = WebpackMock.serverExports;
32 webpackServerMap = WebpackMock.webpackServerMap;
scripts/rollup/bundles.js
+1 -1
@@ -447,7 +447,7 @@ const bundles = [
447 global: 'ReactFlightWebpackNodeRegister',
448 minifyWithProdErrorCodes: false,
449 wrapWithModuleBoundaries: false,
450 - externals: ['url', 'module'],
450 + externals: ['url', 'module', 'react-server-dom-webpack/server'],
451 },
452
453 /******* React Server DOM ESM Server *******/
scripts/shared/inlinedHostConfigs.js
+2
@@ -145,6 +145,8 @@ module.exports = [
145 'react-server-dom-webpack/server',
146 'react-server-dom-webpack/server.node',
147 'react-server-dom-webpack/src/ReactFlightDOMServerNode.js', // react-server-dom-webpack/server.node
148 + 'react-server-dom-webpack/node-register',
149 + 'react-server-dom-webpack/src/ReactFlightWebpackNodeRegister.js',
150 'react-devtools',
151 'react-devtools-core',
152 'react-devtools-shell',