Unverified Commit 40b2d138 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Unwrap promise with experimental_use (#40575)

x-ref: https://github.com/facebook/react/pull/25267

Bump the version of `react-server-dom-webpack` and use `experimental_use` to unwrap the promise to access RSC payload instead of using `readRoot`. `readRoot` is removed from the response type.
parent 33a6dca7
...@@ -14,6 +14,9 @@ declare global { ...@@ -14,6 +14,9 @@ declare global {
const __webpack_require__: any const __webpack_require__: any
} }
// TODO-APP: change to React.use once it becomes stable
const use = (React as any).experimental_use
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
const getChunkScriptFilename = __webpack_require__.u const getChunkScriptFilename = __webpack_require__.u
const chunkFilenameMap: any = {} const chunkFilenameMap: any = {}
...@@ -143,7 +146,7 @@ function ServerRoot({ cacheKey }: { cacheKey: string }) { ...@@ -143,7 +146,7 @@ function ServerRoot({ cacheKey }: { cacheKey: string }) {
rscCache.delete(cacheKey) rscCache.delete(cacheKey)
}) })
const response = useInitialServerResponse(cacheKey) const response = useInitialServerResponse(cacheKey)
const root = response.readRoot() const root = use(response)
return root return root
} }
......
...@@ -65,8 +65,8 @@ export function fetchServerResponse( ...@@ -65,8 +65,8 @@ export function fetchServerResponse(
url: URL, url: URL,
flightRouterState: FlightRouterState, flightRouterState: FlightRouterState,
prefetch?: true prefetch?: true
): { readRoot: () => FlightData } { ): Promise<FlightData> {
// Handle the `fetch` readable stream that can be read using `readRoot`. // Handle the `fetch` readable stream that can be unwrapped by `React.use`.
return createFromReadableStream(fetchFlight(url, flightRouterState, prefetch)) return createFromReadableStream(fetchFlight(url, flightRouterState, prefetch))
} }
...@@ -212,20 +212,15 @@ export default function AppRouter({ ...@@ -212,20 +212,15 @@ export default function AppRouter({
window.history.state?.tree || initialTree, window.history.state?.tree || initialTree,
true true
) )
try { const flightData = await r
r.readRoot() // @ts-ignore startTransition exists
} catch (e) { React.startTransition(() => {
await e dispatch({
const flightData = r.readRoot() type: ACTION_PREFETCH,
// @ts-ignore startTransition exists url,
React.startTransition(() => { flightData,
dispatch({
type: ACTION_PREFETCH,
url,
flightData,
})
}) })
} })
} catch (err) { } catch (err) {
console.error('PREFETCH ERROR', err) console.error('PREFETCH ERROR', err)
} }
......
...@@ -17,6 +17,9 @@ import { ...@@ -17,6 +17,9 @@ import {
import { fetchServerResponse } from './app-router.client' import { fetchServerResponse } from './app-router.client'
// import { matchSegment } from './match-segments' // import { matchSegment } from './match-segments'
// TODO-APP: change to React.use once it becomes stable
const use = (React as any).experimental_use
/** /**
* Check if every segment in array a and b matches * Check if every segment in array a and b matches
*/ */
...@@ -218,14 +221,14 @@ export function InnerLayoutRouter({ ...@@ -218,14 +221,14 @@ export function InnerLayoutRouter({
throw new Error('Child node should not have both subTreeData and data') throw new Error('Child node should not have both subTreeData and data')
} }
// If cache node has a data request we have to readRoot and update the cache. // If cache node has a data request we have to unwrap response by `use` and update the cache.
if (childNode.data) { if (childNode.data) {
// TODO-APP: error case // TODO-APP: error case
/** /**
* Flight response data * Flight response data
*/ */
// When the data has not resolved yet readRoot will suspend here. // When the data has not resolved yet `use` will suspend here.
const flightData = childNode.data.readRoot() const flightData = use(childNode.data)
// Handle case when navigating to page in `pages` from `app` // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
......
...@@ -6,9 +6,13 @@ import type { ...@@ -6,9 +6,13 @@ import type {
FlightSegmentPath, FlightSegmentPath,
Segment, Segment,
} from '../../server/app-render' } from '../../server/app-render'
import React from 'react'
import { matchSegment } from './match-segments' import { matchSegment } from './match-segments'
import { fetchServerResponse } from './app-router.client' import { fetchServerResponse } from './app-router.client'
// TODO-APP: change to React.use once it becomes stable
const use = (React as any).experimental_use
/** /**
* Invalidate cache one level down from the router state. * Invalidate cache one level down from the router state.
*/ */
...@@ -730,8 +734,7 @@ export function reducer( ...@@ -730,8 +734,7 @@ export function reducer(
cache, cache,
state.cache, state.cache,
segments.slice(1), segments.slice(1),
(): { readRoot: () => FlightData } => (): Promise<FlightData> => fetchServerResponse(url, optimisticTree)
fetchServerResponse(url, optimisticTree)
) )
// If optimistic fetch couldn't happen it falls back to the non-optimistic case. // If optimistic fetch couldn't happen it falls back to the non-optimistic case.
...@@ -761,8 +764,8 @@ export function reducer( ...@@ -761,8 +764,8 @@ export function reducer(
cache.data = fetchServerResponse(url, state.tree) cache.data = fetchServerResponse(url, state.tree)
} }
// readRoot to suspend here (in the reducer) until the fetch resolves. // Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
const flightData = cache.data.readRoot() const flightData = use(cache.data)
// Handle case when navigating to page in `pages` from `app` // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
...@@ -953,7 +956,7 @@ export function reducer( ...@@ -953,7 +956,7 @@ export function reducer(
'refetch', 'refetch',
]) ])
} }
const flightData = cache.data.readRoot() const flightData = use(cache.data)
// Handle case when navigating to page in `pages` from `app` // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') { if (typeof flightData === 'string') {
......
...@@ -162,6 +162,7 @@ function processErrorChunk(request, id, message, stack) { ...@@ -162,6 +162,7 @@ function processErrorChunk(request, id, message, stack) {
return stringToChunk(row); return stringToChunk(row);
} }
function processModelChunk(request, id, model) { function processModelChunk(request, id, model) {
// $FlowFixMe: `json` might be `undefined` when model is a symbol.
var json = stringify(model, request.toJSON); var json = stringify(model, request.toJSON);
var row = serializeRowHeader('J', id) + json + '\n'; var row = serializeRowHeader('J', id) + json + '\n';
return stringToChunk(row); return stringToChunk(row);
...@@ -172,6 +173,7 @@ function processReferenceChunk(request, id, reference) { ...@@ -172,6 +173,7 @@ function processReferenceChunk(request, id, reference) {
return stringToChunk(row); return stringToChunk(row);
} }
function processModuleChunk(request, id, moduleMetaData) { function processModuleChunk(request, id, moduleMetaData) {
// $FlowFixMe: `json` might be `undefined` when moduleMetaData is a symbol.
var json = stringify(moduleMetaData); var json = stringify(moduleMetaData);
var row = serializeRowHeader('M', id) + json + '\n'; var row = serializeRowHeader('M', id) + json + '\n';
return stringToChunk(row); return stringToChunk(row);
...@@ -894,8 +896,8 @@ function readContext(context) { ...@@ -894,8 +896,8 @@ function readContext(context) {
return value; return value;
} }
// Corresponds to ReactFiberWakeable module. Generally, changes to one module // Corresponds to ReactFiberWakeable and ReactFizzWakeable modules. Generally,
// should be reflected in the other. // changes to one module should be reflected in the others.
// TODO: Rename this module and the corresponding Fiber one to "Thenable" // TODO: Rename this module and the corresponding Fiber one to "Thenable"
// instead of "Wakeable". Or some other more appropriate name. // instead of "Wakeable". Or some other more appropriate name.
// TODO: Sparse arrays are bad for performance. // TODO: Sparse arrays are bad for performance.
...@@ -917,11 +919,6 @@ function trackSuspendedWakeable(wakeable) { ...@@ -917,11 +919,6 @@ function trackSuspendedWakeable(wakeable) {
// a listener that will update its status and result when it resolves. // a listener that will update its status and result when it resolves.
switch (thenable.status) { switch (thenable.status) {
case 'pending':
// Since the status is already "pending", we can assume it will be updated
// when it resolves, either by React or something in userspace.
break;
case 'fulfilled': case 'fulfilled':
case 'rejected': case 'rejected':
// A thenable that already resolved shouldn't have been thrown, so this is // A thenable that already resolved shouldn't have been thrown, so this is
...@@ -933,9 +930,13 @@ function trackSuspendedWakeable(wakeable) { ...@@ -933,9 +930,13 @@ function trackSuspendedWakeable(wakeable) {
default: default:
{ {
// TODO: Only instrument the thenable if the status if not defined. If if (typeof thenable.status === 'string') {
// it's defined, but an unknown value, assume it's been instrumented by // Only instrument the thenable if the status if not defined. If
// some custom userspace implementation. // it's defined, but an unknown value, assume it's been instrumented by
// some custom userspace implementation. We treat it as "pending".
break;
}
var pendingThenable = thenable; var pendingThenable = thenable;
pendingThenable.status = 'pending'; pendingThenable.status = 'pending';
pendingThenable.then(function (fulfilledValue) { pendingThenable.then(function (fulfilledValue) {
...@@ -990,7 +991,9 @@ function prepareToUseHooksForComponent(prevThenableState) { ...@@ -990,7 +991,9 @@ function prepareToUseHooksForComponent(prevThenableState) {
thenableState = prevThenableState; thenableState = prevThenableState;
} }
function getThenableStateAfterSuspending() { function getThenableStateAfterSuspending() {
return thenableState; var state = thenableState;
thenableState = null;
return state;
} }
function readContext$1(context) { function readContext$1(context) {
...@@ -1149,6 +1152,9 @@ function use(usable) { ...@@ -1149,6 +1152,9 @@ function use(usable) {
} }
} }
} }
} else if (usable.$$typeof === REACT_SERVER_CONTEXT_TYPE) {
var context = usable;
return readContext$1(context);
} }
} // eslint-disable-next-line react-internal/safe-string-coercion } // eslint-disable-next-line react-internal/safe-string-coercion
...@@ -1159,7 +1165,8 @@ function use(usable) { ...@@ -1159,7 +1165,8 @@ function use(usable) {
var ContextRegistry = ReactSharedInternals.ContextRegistry; var ContextRegistry = ReactSharedInternals.ContextRegistry;
function getOrCreateServerContext(globalName) { function getOrCreateServerContext(globalName) {
if (!ContextRegistry[globalName]) { if (!ContextRegistry[globalName]) {
ContextRegistry[globalName] = React.createServerContext(globalName, REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED); ContextRegistry[globalName] = React.createServerContext(globalName, // $FlowFixMe function signature doesn't reflect the symbol value
REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED);
} }
return ContextRegistry[globalName]; return ContextRegistry[globalName];
...@@ -1292,7 +1299,8 @@ function attemptResolveElement(type, key, ref, props, prevThenableState) { ...@@ -1292,7 +1299,8 @@ function attemptResolveElement(type, key, ref, props, prevThenableState) {
if (extraKeys.length !== 0) { if (extraKeys.length !== 0) {
error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys)); error('ServerContext can only have a value prop and children. Found: %s', JSON.stringify(extraKeys));
} }
} } // $FlowFixMe issue discovered when updating Flow
return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider. return [REACT_ELEMENT_TYPE, type, key, // Rely on __popProvider being serialized last to pop the provider.
{ {
...@@ -1677,7 +1685,8 @@ function resolveModelToJSON(request, parent, key, value) { ...@@ -1677,7 +1685,8 @@ function resolveModelToJSON(request, parent, key, value) {
} }
} }
} }
} } // $FlowFixMe
return value; return value;
} }
...@@ -1708,12 +1717,14 @@ function resolveModelToJSON(request, parent, key, value) { ...@@ -1708,12 +1717,14 @@ function resolveModelToJSON(request, parent, key, value) {
if (existingId !== undefined) { if (existingId !== undefined) {
return serializeByValueID(existingId); return serializeByValueID(existingId);
} } // $FlowFixMe `description` might be undefined
var name = value.description; var name = value.description; // $FlowFixMe `name` might be undefined
if (Symbol.for(name) !== value) { if (Symbol.for(name) !== value) {
throw new Error('Only global symbols received from Symbol.for(...) can be passed to client components. ' + ("The symbol Symbol.for(" + value.description + ") cannot be found among global symbols. ") + ("Remove " + describeKeyForErrorMessage(key) + " from this object, or avoid the entire object: " + describeObjectForErrorMessage(parent))); throw new Error('Only global symbols received from Symbol.for(...) can be passed to client components. ' + ("The symbol Symbol.for(" + // $FlowFixMe `description` might be undefined
value.description + ") cannot be found among global symbols. ") + ("Remove " + describeKeyForErrorMessage(key) + " from this object, or avoid the entire object: " + describeObjectForErrorMessage(parent)));
} }
request.pendingChunks++; request.pendingChunks++;
...@@ -1772,6 +1783,7 @@ function emitErrorChunk(request, id, error) { ...@@ -1772,6 +1783,7 @@ function emitErrorChunk(request, id, error) {
} }
function emitModuleChunk(request, id, moduleMetaData) { function emitModuleChunk(request, id, moduleMetaData) {
// $FlowFixMe ModuleMetaData is not a ReactModel
var processedChunk = processModuleChunk(request, id, moduleMetaData); var processedChunk = processModuleChunk(request, id, moduleMetaData);
request.completedModuleChunks.push(processedChunk); request.completedModuleChunks.push(processedChunk);
} }
......
...@@ -244,7 +244,7 @@ ...@@ -244,7 +244,7 @@
"raw-body": "2.4.1", "raw-body": "2.4.1",
"react-is": "17.0.2", "react-is": "17.0.2",
"react-refresh": "0.12.0", "react-refresh": "0.12.0",
"react-server-dom-webpack": "0.0.0-experimental-7028ce745-20220907", "react-server-dom-webpack": "0.0.0-experimental-975b64464-20220914",
"regenerator-runtime": "0.13.4", "regenerator-runtime": "0.13.4",
"sass-loader": "12.4.0", "sass-loader": "12.4.0",
"schema-utils2": "npm:schema-utils@2.7.1", "schema-utils2": "npm:schema-utils@2.7.1",
......
...@@ -29,6 +29,9 @@ import { FlushEffectsContext } from '../client/components/hooks-client' ...@@ -29,6 +29,9 @@ import { FlushEffectsContext } from '../client/components/hooks-client'
import { stripInternalQueries } from './internal-utils' import { stripInternalQueries } from './internal-utils'
import type { ComponentsType } from '../build/webpack/loaders/next-app-loader' import type { ComponentsType } from '../build/webpack/loaders/next-app-loader'
// TODO-APP: change to React.use once it becomes stable
const use = (React as any).experimental_use
// this needs to be required lazily so that `next-server` can set // this needs to be required lazily so that `next-server` can set
// the env before we require // the env before we require
const ReactDOMServer = shouldUseReactRoot const ReactDOMServer = shouldUseReactRoot
...@@ -251,7 +254,7 @@ function createServerComponentRenderer( ...@@ -251,7 +254,7 @@ function createServerComponentRenderer(
flightResponseRef, flightResponseRef,
nonce nonce
) )
return response.readRoot() return use(response)
} }
} }
......
...@@ -548,7 +548,7 @@ importers: ...@@ -548,7 +548,7 @@ importers:
raw-body: 2.4.1 raw-body: 2.4.1
react-is: 17.0.2 react-is: 17.0.2
react-refresh: 0.12.0 react-refresh: 0.12.0
react-server-dom-webpack: 0.0.0-experimental-7028ce745-20220907 react-server-dom-webpack: 0.0.0-experimental-975b64464-20220914
regenerator-runtime: 0.13.4 regenerator-runtime: 0.13.4
sass-loader: 12.4.0 sass-loader: 12.4.0
schema-utils2: npm:schema-utils@2.7.1 schema-utils2: npm:schema-utils@2.7.1
...@@ -737,7 +737,7 @@ importers: ...@@ -737,7 +737,7 @@ importers:
raw-body: 2.4.1 raw-body: 2.4.1
react-is: 17.0.2 react-is: 17.0.2
react-refresh: 0.12.0 react-refresh: 0.12.0
react-server-dom-webpack: 0.0.0-experimental-7028ce745-20220907_webpack@5.74.0 react-server-dom-webpack: 0.0.0-experimental-975b64464-20220914_webpack@5.74.0
regenerator-runtime: 0.13.4 regenerator-runtime: 0.13.4
sass-loader: 12.4.0_webpack@5.74.0 sass-loader: 12.4.0_webpack@5.74.0
schema-utils2: /schema-utils/2.7.1 schema-utils2: /schema-utils/2.7.1
...@@ -24444,14 +24444,14 @@ packages: ...@@ -24444,14 +24444,14 @@ packages:
engines: { node: '>=0.10.0' } engines: { node: '>=0.10.0' }
dev: true dev: true
/react-server-dom-webpack/0.0.0-experimental-7028ce745-20220907_webpack@5.74.0: /react-server-dom-webpack/0.0.0-experimental-975b64464-20220914_webpack@5.74.0:
resolution: resolution:
{ {
integrity: sha512-DqVpIa9DdgQNre2urGq5brXRrgtd6jqCUO4Ax5yBAHvmWW5L2XkU3jI+YCMMZdxVwcP+NIJoB9mkIsFyIo8NAQ==, integrity: sha512-RU8yWstn6EpbprfOEnpCpp4fzSTgRLIjvWjJYZq2AiVrXXaAl54stVC1LlZ5Ox4hNXBc6K/FAuQqF4nopXx5Aw==,
} }
engines: { node: '>=0.10.0' } engines: { node: '>=0.10.0' }
peerDependencies: peerDependencies:
react: 0.0.0-experimental-7028ce745-20220907 react: 0.0.0-experimental-975b64464-20220914
webpack: ^5.59.0 webpack: ^5.59.0
dependencies: dependencies:
acorn: 6.4.2 acorn: 6.4.2
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment