Skip to content

Commit

Permalink
Improve Error Messages when Access Client References (#26059)
Browse files Browse the repository at this point in the history
This renames Module References to Client References, since they are in
the server->client direction.

I also changed the Proxies exposed from the `node-register` loader to
provide better error messages. Ideally, some of this should be
replicated in the ESM loader too but neither are the source of truth.
We'll replicate this in the static form in the Next.js loaders. cc
@huozhi @shuding

- All references are now functions so that when you call them on the
server, we can yield a better error message.
- References that are themselves already referring to an export name are
now proxies that error when you dot into them.
- `use(...)` can now be used on a client reference to unwrap it server
side and then pass a reference to the awaited value.
  • Loading branch information
sebmarkbage authored Jan 28, 2023
1 parent 78c4bec commit ce09ace
Show file tree
Hide file tree
Showing 23 changed files with 415 additions and 159 deletions.
12 changes: 6 additions & 6 deletions packages/react-client/src/ReactFlightClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ import type {Thenable} from 'shared/ReactTypes';
import type {LazyComponent} from 'react/src/ReactLazy';

import type {
ModuleReference,
ClientReference,
ModuleMetaData,
UninitializedModel,
Response,
BundlerConfig,
} from './ReactFlightClientHostConfig';

import {
resolveModuleReference,
resolveClientReference,
preloadModule,
requireModule,
parseModel,
Expand Down Expand Up @@ -67,7 +67,7 @@ type ResolvedModelChunk<T> = {
};
type ResolvedModuleChunk<T> = {
status: 'resolved_module',
value: ModuleReference<T>,
value: ClientReference<T>,
reason: null,
_response: Response,
then(resolve: (T) => mixed, reject: (mixed) => mixed): void,
Expand Down Expand Up @@ -262,7 +262,7 @@ function createResolvedModelChunk<T>(

function createResolvedModuleChunk<T>(
response: Response,
value: ModuleReference<T>,
value: ClientReference<T>,
): ResolvedModuleChunk<T> {
// $FlowFixMe Flow doesn't support functions as constructors
return new Chunk(RESOLVED_MODULE, value, null, response);
Expand Down Expand Up @@ -293,7 +293,7 @@ function resolveModelChunk<T>(

function resolveModuleChunk<T>(
chunk: SomeChunk<T>,
value: ModuleReference<T>,
value: ClientReference<T>,
): void {
if (chunk.status !== PENDING && chunk.status !== BLOCKED) {
// We already resolved. We didn't expect to see this.
Expand Down Expand Up @@ -589,7 +589,7 @@ export function resolveModule(
const chunks = response._chunks;
const chunk = chunks.get(id);
const moduleMetaData: ModuleMetaData = parseModel(response, model);
const moduleReference = resolveModuleReference(
const moduleReference = resolveClientReference(
response._bundlerConfig,
moduleMetaData,
);
Expand Down
55 changes: 37 additions & 18 deletions packages/react-client/src/__tests__/ReactFlight-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,16 @@ describe('ReactFlight', () => {
};
});

function moduleReference(value) {
return {
$$typeof: Symbol.for('react.module.reference'),
value: value,
};
function clientReference(value) {
return Object.defineProperties(
function() {
throw new Error('Cannot call a client function from the server.');
},
{
$$typeof: {value: Symbol.for('react.client.reference')},
value: {value: value},
},
);
}

it('can render a Server Component', async () => {
Expand Down Expand Up @@ -136,7 +141,7 @@ describe('ReactFlight', () => {
</span>
);
}
const User = moduleReference(UserClient);
const User = clientReference(UserClient);

function Greeting({firstName, lastName}) {
return <User greeting="Hello" name={firstName + ' ' + lastName} />;
Expand Down Expand Up @@ -327,7 +332,7 @@ describe('ReactFlight', () => {
return <div>I am client</div>;
}

const ClientComponentReference = moduleReference(ClientComponent);
const ClientComponentReference = clientReference(ClientComponent);

let load = null;
const loadClientComponentReference = () => {
Expand Down Expand Up @@ -369,7 +374,7 @@ describe('ReactFlight', () => {
function ClientImpl({children}) {
return children;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);

function EventHandlerProp() {
return (
Expand Down Expand Up @@ -488,7 +493,7 @@ describe('ReactFlight', () => {
);
}

const ClientComponentReference = moduleReference(ClientComponent);
const ClientComponentReference = clientReference(ClientComponent);

function Server() {
return (
Expand Down Expand Up @@ -576,7 +581,7 @@ describe('ReactFlight', () => {
function ClientImpl({value}) {
return <div>{value}</div>;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);
expect(() => {
const transport = ReactNoopFlightServer.render(
<Client value={new Date()} />,
Expand All @@ -593,7 +598,7 @@ describe('ReactFlight', () => {
function ClientImpl({children}) {
return <div>{children}</div>;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);
expect(() => {
const transport = ReactNoopFlightServer.render(
<Client>Current date: {new Date()}</Client>,
Expand All @@ -612,7 +617,7 @@ describe('ReactFlight', () => {
function ClientImpl({value}) {
return <div>{value}</div>;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);
expect(() => {
const transport = ReactNoopFlightServer.render(<Client value={Math} />);
ReactNoopFlightClient.read(transport);
Expand All @@ -629,7 +634,7 @@ describe('ReactFlight', () => {
function ClientImpl({value}) {
return <div>{value}</div>;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);
expect(() => {
const transport = ReactNoopFlightServer.render(
<Client value={{[Symbol.iterator]: {}}} />,
Expand All @@ -646,7 +651,7 @@ describe('ReactFlight', () => {
function ClientImpl({value}) {
return <div>{value}</div>;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);
expect(() => {
const transport = ReactNoopFlightServer.render(
<Client value={{hello: Math, title: <h1>hi</h1>}} />,
Expand All @@ -665,7 +670,7 @@ describe('ReactFlight', () => {
function ClientImpl({value}) {
return <div>{value}</div>;
}
const Client = moduleReference(ClientImpl);
const Client = clientReference(ClientImpl);
expect(() => {
const transport = ReactNoopFlightServer.render(
<Client
Expand Down Expand Up @@ -702,6 +707,20 @@ describe('ReactFlight', () => {
);
});

it('should warn in DEV if a a client reference is passed to useContext()', () => {
const Context = React.createContext();
const ClientContext = clientReference(Context);
function ServerComponent() {
return React.useContext(ClientContext);
}
expect(() => {
const transport = ReactNoopFlightServer.render(<ServerComponent />);
ReactNoopFlightClient.read(transport);
}).toErrorDev('Cannot read a Client Context from a Server Component.', {
withoutStack: true,
});
});

describe('Hooks', () => {
function DivWithId({children}) {
const id = React.useId();
Expand Down Expand Up @@ -776,7 +795,7 @@ describe('ReactFlight', () => {
);
}

const ClientDoublerModuleRef = moduleReference(ClientDoubler);
const ClientDoublerModuleRef = clientReference(ClientDoubler);

const transport = ReactNoopFlightServer.render(<App />);
expect(Scheduler).toHaveYielded([]);
Expand Down Expand Up @@ -1000,7 +1019,7 @@ describe('ReactFlight', () => {
return <span>{context}</span>;
}

const Bar = moduleReference(ClientBar);
const Bar = clientReference(ClientBar);

function Foo() {
return (
Expand Down Expand Up @@ -1077,7 +1096,7 @@ describe('ReactFlight', () => {
return <div>{value}</div>;
}

const Baz = moduleReference(ClientBaz);
const Baz = clientReference(ClientBaz);

function Bar() {
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ declare var $$$hostConfig: any;
export type Response = any;
export opaque type BundlerConfig = mixed;
export opaque type ModuleMetaData = mixed;
export opaque type ModuleReference<T> = mixed; // eslint-disable-line no-unused-vars
export const resolveModuleReference = $$$hostConfig.resolveModuleReference;
export opaque type ClientReference<T> = mixed; // eslint-disable-line no-unused-vars
export const resolveClientReference = $$$hostConfig.resolveClientReference;
export const preloadModule = $$$hostConfig.preloadModule;
export const requireModule = $$$hostConfig.requireModule;

Expand Down
2 changes: 1 addition & 1 deletion packages/react-noop-renderer/src/ReactNoopFlightClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type Source = Array<string>;

const {createResponse, processStringChunk, getRoot, close} = ReactFlightClient({
supportsBinaryStreams: false,
resolveModuleReference(bundlerConfig: null, idx: string) {
resolveClientReference(bundlerConfig: null, idx: string) {
return idx;
},
preloadModule(idx: string) {},
Expand Down
6 changes: 3 additions & 3 deletions packages/react-noop-renderer/src/ReactNoopFlightServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ const ReactNoopFlightServer = ReactFlightServer({
clonePrecomputedChunk(chunk: string): string {
return chunk;
},
isModuleReference(reference: Object): boolean {
return reference.$$typeof === Symbol.for('react.module.reference');
isClientReference(reference: Object): boolean {
return reference.$$typeof === Symbol.for('react.client.reference');
},
getModuleKey(reference: Object): Object {
getClientReferenceKey(reference: Object): Object {
return reference;
},
resolveModuleMetaData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type {JSResourceReference} from 'JSResourceReference';

import type {ModuleMetaData} from 'ReactFlightDOMRelayClientIntegration';

export type ModuleReference<T> = JSResourceReference<T>;
export type ClientReference<T> = JSResourceReference<T>;

import {
parseModelString,
Expand All @@ -25,7 +25,7 @@ export {
requireModule,
} from 'ReactFlightDOMRelayClientIntegration';

import {resolveModuleReference as resolveModuleReferenceImpl} from 'ReactFlightDOMRelayClientIntegration';
import {resolveClientReference as resolveClientReferenceImpl} from 'ReactFlightDOMRelayClientIntegration';

import isArray from 'shared/isArray';

Expand All @@ -37,11 +37,11 @@ export type UninitializedModel = JSONValue;

export type Response = ResponseBase;

export function resolveModuleReference<T>(
export function resolveClientReference<T>(
bundlerConfig: BundlerConfig,
moduleData: ModuleMetaData,
): ModuleReference<T> {
return resolveModuleReferenceImpl(moduleData);
): ClientReference<T> {
return resolveClientReferenceImpl(moduleData);
}

// $FlowFixMe[missing-local-annot]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import JSResourceReferenceImpl from 'JSResourceReferenceImpl';
import hasOwnProperty from 'shared/hasOwnProperty';
import isArray from 'shared/isArray';

export type ModuleReference<T> = JSResourceReference<T>;
export type ClientReference<T> = JSResourceReference<T>;

import type {
Destination,
Expand All @@ -39,21 +39,23 @@ export type {
ModuleMetaData,
} from 'ReactFlightDOMRelayServerIntegration';

export function isModuleReference(reference: Object): boolean {
export function isClientReference(reference: Object): boolean {
return reference instanceof JSResourceReferenceImpl;
}

export type ModuleKey = ModuleReference<any>;
export type ClientReferenceKey = ClientReference<any>;

export function getModuleKey(reference: ModuleReference<any>): ModuleKey {
export function getClientReferenceKey(
reference: ClientReference<any>,
): ClientReferenceKey {
// We use the reference object itself as the key because we assume the
// object will be cached by the bundler runtime.
return reference;
}

export function resolveModuleMetaData<T>(
config: BundlerConfig,
resource: ModuleReference<T>,
resource: ClientReference<T>,
): ModuleMetaData {
return resolveModuleMetaDataImpl(config, resource);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import JSResourceReferenceImpl from 'JSResourceReferenceImpl';

const ReactFlightDOMRelayClientIntegration = {
resolveModuleReference(moduleData) {
resolveClientReference(moduleData) {
return new JSResourceReferenceImpl(moduleData);
},
preloadModule(moduleReference) {},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ export opaque type ModuleMetaData = {
};

// eslint-disable-next-line no-unused-vars
export opaque type ModuleReference<T> = ModuleMetaData;
export opaque type ClientReference<T> = ModuleMetaData;

export function resolveModuleReference<T>(
export function resolveClientReference<T>(
bundlerConfig: BundlerConfig,
moduleData: ModuleMetaData,
): ModuleReference<T> {
): ClientReference<T> {
if (bundlerConfig) {
const resolvedModuleData = bundlerConfig[moduleData.id][moduleData.name];
if (moduleData.async) {
Expand Down Expand Up @@ -64,7 +64,7 @@ function ignoreReject() {
// Start preloading the modules since we might need them soon.
// This function doesn't suspend.
export function preloadModule<T>(
moduleData: ModuleReference<T>,
moduleData: ClientReference<T>,
): null | Thenable<any> {
const chunks = moduleData.chunks;
const promises = [];
Expand Down Expand Up @@ -117,7 +117,7 @@ export function preloadModule<T>(

// Actually require the module or suspend if it's not yet ready.
// Increase priority if necessary.
export function requireModule<T>(moduleData: ModuleReference<T>): T {
export function requireModule<T>(moduleData: ClientReference<T>): T {
let moduleExports;
if (moduleData.async) {
// We assume that preloadModule has been called before, which
Expand Down
Loading

0 comments on commit ce09ace

Please sign in to comment.