Unverified Commit 8303bbd4 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Handle cross-page client reference contamination in development (#86591)

parent 2307d46f
...@@ -947,5 +947,9 @@ ...@@ -947,5 +947,9 @@
"946": "Failed to deserialize errors.", "946": "Failed to deserialize errors.",
"947": "Expected `sendErrorsToBrowser` to be defined in renderOpts.", "947": "Expected `sendErrorsToBrowser` to be defined in renderOpts.",
"948": "Failed to serialize errors.", "948": "Failed to serialize errors.",
"949": "Route %s errored during %s. These errors are normally ignored and may not prevent the route from prerendering but are logged here because build debugging is enabled.\n \nOriginal Error: %s" "949": "Route %s errored during %s. These errors are normally ignored and may not prevent the route from prerendering but are logged here because build debugging is enabled.\n \nOriginal Error: %s",
"950": "The manifests singleton was not initialized.",
"951": "The client reference manifest for route \"%s\" does not exist.",
"952": "Cannot access \"%s\" without a work store.",
"953": "This is a proxied client reference manifest. The property \"%s\" is not handled."
} }
...@@ -21,12 +21,11 @@ import { ...@@ -21,12 +21,11 @@ import {
createOpaqueFallbackRouteParams, createOpaqueFallbackRouteParams,
type OpaqueFallbackRouteParams, type OpaqueFallbackRouteParams,
} from '../../server/request/fallback-params' } from '../../server/request/fallback-params'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { import {
isHtmlBotRequest, isHtmlBotRequest,
shouldServeStreamingMetadata, shouldServeStreamingMetadata,
} from '../../server/lib/streaming-metadata' } from '../../server/lib/streaming-metadata'
import { createServerModuleMap } from '../../server/app-render/action-utils'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta' import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta'
import { import {
...@@ -400,13 +399,10 @@ export async function handler( ...@@ -400,13 +399,10 @@ export async function handler(
// set the reference manifests to our global store so Server Action's // set the reference manifests to our global store so Server Action's
// encryption util can access to them at the top level of the page module. // encryption util can access to them at the top level of the page module.
if (serverActionsManifest && clientReferenceManifest) { if (serverActionsManifest && clientReferenceManifest) {
setReferenceManifestsSingleton({ setManifestsSingleton({
page: srcPage, page: srcPage,
clientReferenceManifest, clientReferenceManifest,
serverActionsManifest, serverActionsManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest,
}),
}) })
} }
...@@ -540,8 +536,6 @@ export async function handler( ...@@ -540,8 +536,6 @@ export async function handler(
nextFontManifest, nextFontManifest,
reactLoadableManifest, reactLoadableManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
serverActionsManifest,
clientReferenceManifest,
setCacheStatus: routerServerContext?.setCacheStatus, setCacheStatus: routerServerContext?.setCacheStatus,
setIsrStatus: routerServerContext?.setIsrStatus, setIsrStatus: routerServerContext?.setIsrStatus,
setReactDebugChannel: routerServerContext?.setReactDebugChannel, setReactDebugChannel: routerServerContext?.setReactDebugChannel,
......
...@@ -8,8 +8,7 @@ import { patchFetch as _patchFetch } from '../../server/lib/patch-fetch' ...@@ -8,8 +8,7 @@ import { patchFetch as _patchFetch } from '../../server/lib/patch-fetch'
import type { IncomingMessage, ServerResponse } from 'node:http' import type { IncomingMessage, ServerResponse } from 'node:http'
import { addRequestMeta, getRequestMeta } from '../../server/request-meta' import { addRequestMeta, getRequestMeta } from '../../server/request-meta'
import { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer' import { getTracer, type Span, SpanKind } from '../../server/lib/trace/tracer'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { createServerModuleMap } from '../../server/app-render/action-utils'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node' import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { import {
...@@ -185,13 +184,10 @@ export async function handler( ...@@ -185,13 +184,10 @@ export async function handler(
// set the reference manifests to our global store so Server Action's // set the reference manifests to our global store so Server Action's
// encryption util can access to them at the top level of the page module. // encryption util can access to them at the top level of the page module.
if (serverActionsManifest && clientReferenceManifest) { if (serverActionsManifest && clientReferenceManifest) {
setReferenceManifestsSingleton({ setManifestsSingleton({
page: srcPage, page: srcPage,
clientReferenceManifest, clientReferenceManifest,
serverActionsManifest, serverActionsManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest,
}),
}) })
} }
......
import { createServerModuleMap } from '../../server/app-render/action-utils' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils'
import type { NextConfigComplete } from '../../server/config-shared' import type { NextConfigComplete } from '../../server/config-shared'
import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper' import { EdgeRouteModuleWrapper } from '../../server/web/edge-route-module-wrapper'
...@@ -16,13 +15,10 @@ const rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE'] ...@@ -16,13 +15,10 @@ const rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']
const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
if (rscManifest && rscServerManifest) { if (rscManifest && rscServerManifest) {
setReferenceManifestsSingleton({ setManifestsSingleton({
page: 'VAR_PAGE', page: 'VAR_PAGE',
clientReferenceManifest: rscManifest, clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest, serverActionsManifest: rscServerManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest: rscServerManifest,
}),
}) })
} }
......
...@@ -6,8 +6,7 @@ import * as pageMod from 'VAR_USERLAND' ...@@ -6,8 +6,7 @@ import * as pageMod from 'VAR_USERLAND'
import type { RequestData } from '../../server/web/types' import type { RequestData } from '../../server/web/types'
import type { NextConfigComplete } from '../../server/config-shared' import type { NextConfigComplete } from '../../server/config-shared'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils' import { setManifestsSingleton } from '../../server/app-render/manifests-singleton'
import { createServerModuleMap } from '../../server/app-render/action-utils'
import { initializeCacheHandlers } from '../../server/use-cache/handlers' import { initializeCacheHandlers } from '../../server/use-cache/handlers'
import { BaseServerSpan } from '../../server/lib/trace/constants' import { BaseServerSpan } from '../../server/lib/trace/constants'
import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer' import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer'
...@@ -40,13 +39,10 @@ const rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE'] ...@@ -40,13 +39,10 @@ const rscManifest = self.__RSC_MANIFEST?.['VAR_PAGE']
const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST) const rscServerManifest = maybeJSONParse(self.__RSC_SERVER_MANIFEST)
if (rscManifest && rscServerManifest) { if (rscManifest && rscServerManifest) {
setReferenceManifestsSingleton({ setManifestsSingleton({
page: 'VAR_PAGE', page: 'VAR_PAGE',
clientReferenceManifest: rscManifest, clientReferenceManifest: rscManifest,
serverActionsManifest: rscServerManifest, serverActionsManifest: rscServerManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest: rscServerManifest,
}),
}) })
} }
...@@ -81,12 +77,10 @@ async function requestHandler( ...@@ -81,12 +77,10 @@ async function requestHandler(
buildManifest, buildManifest,
prerenderManifest, prerenderManifest,
reactLoadableManifest, reactLoadableManifest,
clientReferenceManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
dynamicCssManifest, dynamicCssManifest,
nextFontManifest, nextFontManifest,
resolvedPathname, resolvedPathname,
serverActionsManifest,
interceptionRoutePatterns, interceptionRoutePatterns,
routerServerContext, routerServerContext,
} = prepareResult } = prepareResult
...@@ -129,8 +123,6 @@ async function requestHandler( ...@@ -129,8 +123,6 @@ async function requestHandler(
reactLoadableManifest, reactLoadableManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
dynamicCssManifest, dynamicCssManifest,
serverActionsManifest,
clientReferenceManifest,
setIsrStatus: routerServerContext?.setIsrStatus, setIsrStatus: routerServerContext?.setIsrStatus,
dir: pageRouteModule.relativeProjectDir, dir: pageRouteModule.relativeProjectDir,
......
...@@ -682,7 +682,14 @@ const nextAppLoader: AppLoader = async function nextAppLoader() { ...@@ -682,7 +682,14 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
const buildInfo = getModuleBuildInfo((this as any)._module) const buildInfo = getModuleBuildInfo((this as any)._module)
const collectedDeclarations: [string, string][] = [] const collectedDeclarations: [string, string][] = []
const page = name.replace(/^app/, '')
// Use the page from loaderOptions directly instead of deriving it from name.
// The name (bundlePath) may have been normalized with normalizePagePath()
// which is designed for Pages Router and incorrectly duplicates /index paths
// (e.g., /index/page -> /index/index/page). The page parameter contains the
// correct unnormalized value.
const page = loaderOptions.page
const middlewareConfig: ProxyConfig = JSON.parse( const middlewareConfig: ProxyConfig = JSON.parse(
Buffer.from(middlewareConfigBase64, 'base64').toString() Buffer.from(middlewareConfigBase64, 'base64').toString()
) )
......
...@@ -41,7 +41,7 @@ interface Options { ...@@ -41,7 +41,7 @@ interface Options {
type ModuleId = string | number /*| null*/ type ModuleId = string | number /*| null*/
// double indexed chunkId, filename // double indexed chunkId, filename
export type ManifestChunks = Array<string> export type ManifestChunks = ReadonlyArray<string>
const pluginState = getProxiedPluginState({ const pluginState = getProxiedPluginState({
ssrModules: {} as { [ssrModuleId: string]: ModuleInfo }, ssrModules: {} as { [ssrModuleId: string]: ModuleInfo },
......
...@@ -385,11 +385,6 @@ async function exportAppImpl( ...@@ -385,11 +385,6 @@ async function exportAppImpl(
join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`) join(distDir, 'server', `${NEXT_FONT_MANIFEST}.json`)
), ),
images: nextConfig.images, images: nextConfig.images,
...(enabledDirectories.app
? {
serverActionsManifest,
}
: {}),
deploymentId: nextConfig.deploymentId, deploymentId: nextConfig.deploymentId,
htmlLimitedBots: nextConfig.htmlLimitedBots.source, htmlLimitedBots: nextConfig.htmlLimitedBots.source,
experimental: { experimental: {
......
...@@ -49,7 +49,7 @@ import { warn } from '../../build/output/log' ...@@ -49,7 +49,7 @@ import { warn } from '../../build/output/log'
import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies' import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers' import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import { fromNodeOutgoingHttpHeaders } from '../web/utils' import { fromNodeOutgoingHttpHeaders } from '../web/utils'
import { selectWorkerForForwarding } from './action-utils' import { selectWorkerForForwarding, type ServerModuleMap } from './action-utils'
import { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers' import { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers'
import { RedirectStatusCode } from '../../client/components/redirect-status-code' import { RedirectStatusCode } from '../../client/components/redirect-status-code'
import { synchronizeMutableCookies } from '../async-storage/request-store' import { synchronizeMutableCookies } from '../async-storage/request-store'
...@@ -59,7 +59,7 @@ import { InvariantError } from '../../shared/lib/invariant-error' ...@@ -59,7 +59,7 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { executeRevalidates } from '../revalidation-utils' import { executeRevalidates } from '../revalidation-utils'
import { getRequestMeta } from '../request-meta' import { getRequestMeta } from '../request-meta'
import { setCacheBustingSearchParam } from '../../client/components/router-reducer/set-cache-busting-search-param' import { setCacheBustingSearchParam } from '../../client/components/router-reducer/set-cache-busting-search-param'
import { getServerModuleMap } from './encryption-utils' import { getServerModuleMap } from './manifests-singleton'
function formDataFromSearchQueryString(query: string) { function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query) const searchParams = new URLSearchParams(query)
...@@ -473,15 +473,6 @@ export function parseHostHeader( ...@@ -473,15 +473,6 @@ export function parseHostHeader(
: undefined : undefined
} }
type ServerModuleMap = Record<
string,
{
id: string
chunks: string[]
name: string
}
>
type ServerActionsConfig = { type ServerActionsConfig = {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedOrigins?: string[] allowedOrigins?: string[]
...@@ -522,7 +513,7 @@ export async function handleAction({ ...@@ -522,7 +513,7 @@ export async function handleAction({
metadata: AppPageRenderResultMetadata metadata: AppPageRenderResultMetadata
}): Promise<HandleActionResult> { }): Promise<HandleActionResult> {
const contentType = req.headers['content-type'] const contentType = req.headers['content-type']
const { serverActionsManifest, page } = ctx.renderOpts const { page } = ctx.renderOpts
const serverModuleMap = getServerModuleMap() const serverModuleMap = getServerModuleMap()
const { const {
...@@ -640,11 +631,7 @@ export async function handleAction({ ...@@ -640,11 +631,7 @@ export async function handleAction({
const actionWasForwarded = Boolean(req.headers['x-action-forwarded']) const actionWasForwarded = Boolean(req.headers['x-action-forwarded'])
if (actionId) { if (actionId) {
const forwardedWorker = selectWorkerForForwarding( const forwardedWorker = selectWorkerForForwarding(actionId, page)
actionId,
page,
serverActionsManifest
)
// If forwardedWorker is truthy, it means there isn't a worker for the action // If forwardedWorker is truthy, it means there isn't a worker for the action
// in the current handler, so we forward the request to a worker that has the action. // in the current handler, so we forward the request to a worker that has the action.
...@@ -685,7 +672,7 @@ export async function handleAction({ ...@@ -685,7 +672,7 @@ export async function handleAction({
{ isAction: true }, { isAction: true },
async (): Promise<HandleActionResult> => { async (): Promise<HandleActionResult> => {
// We only use these for fetch actions -- MPA actions handle them inside `decodeAction`. // We only use these for fetch actions -- MPA actions handle them inside `decodeAction`.
let actionModId: string | undefined let actionModId: string | number | undefined
let boundActionArguments: unknown[] = [] let boundActionArguments: unknown[] = []
if ( if (
...@@ -1214,7 +1201,7 @@ async function executeActionAndPrepareForRender< ...@@ -1214,7 +1201,7 @@ async function executeActionAndPrepareForRender<
function getActionModIdOrError( function getActionModIdOrError(
actionId: string | null, actionId: string | null,
serverModuleMap: ServerModuleMap serverModuleMap: ServerModuleMap
): string { ): string | number {
// if we're missing the action ID header, we can't do any further processing // if we're missing the action ID header, we can't do any further processing
if (!actionId) { if (!actionId) {
throw new InvariantError("Missing 'next-action' header.") throw new InvariantError("Missing 'next-action' header.")
......
...@@ -2,8 +2,18 @@ import type { ActionManifest } from '../../build/webpack/plugins/flight-client-e ...@@ -2,8 +2,18 @@ import type { ActionManifest } from '../../build/webpack/plugins/flight-client-e
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'
import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'
import { getServerActionsManifest } from './manifests-singleton'
import { workAsyncStorage } from './work-async-storage.external' import { workAsyncStorage } from './work-async-storage.external'
export interface ServerModuleMap {
readonly [name: string]: {
readonly id: string | number
readonly name: string
readonly chunks: Readonly<Array<string>> // currently not used
readonly async?: boolean
}
}
// This function creates a Flight-acceptable server module map proxy from our // This function creates a Flight-acceptable server module map proxy from our
// Server Reference Manifest similar to our client module map. // Server Reference Manifest similar to our client module map.
// This is because our manifest contains a lot of internal Next.js data that // This is because our manifest contains a lot of internal Next.js data that
...@@ -12,7 +22,7 @@ export function createServerModuleMap({ ...@@ -12,7 +22,7 @@ export function createServerModuleMap({
serverActionsManifest, serverActionsManifest,
}: { }: {
serverActionsManifest: ActionManifest serverActionsManifest: ActionManifest
}) { }): ServerModuleMap {
return new Proxy( return new Proxy(
{}, {},
{ {
...@@ -61,11 +71,8 @@ export function createServerModuleMap({ ...@@ -61,11 +71,8 @@ export function createServerModuleMap({
* Checks if the requested action has a worker for the current page. * Checks if the requested action has a worker for the current page.
* If not, it returns the first worker that has a handler for the action. * If not, it returns the first worker that has a handler for the action.
*/ */
export function selectWorkerForForwarding( export function selectWorkerForForwarding(actionId: string, pageName: string) {
actionId: string, const serverActionsManifest = getServerActionsManifest()
pageName: string,
serverActionsManifest: ActionManifest
) {
const workers = const workers =
serverActionsManifest[ serverActionsManifest[
process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node' process.env.NEXT_RUNTIME === 'edge' ? 'edge' : 'node'
......
...@@ -22,7 +22,6 @@ export async function createComponentStylesAndScripts({ ...@@ -22,7 +22,6 @@ export async function createComponentStylesAndScripts({
componentMod: { createElement }, componentMod: { createElement },
} = ctx } = ctx
const { styles: entryCssFiles, scripts: jsHrefs } = getLinkAndScriptTags( const { styles: entryCssFiles, scripts: jsHrefs } = getLinkAndScriptTags(
ctx.clientReferenceManifest,
filePath, filePath,
injectedCSS, injectedCSS,
injectedJS injectedJS
......
import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'
import type {
ClientReferenceManifest,
ClientReferenceManifestForRsc,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths' import { getServerActionsManifest } from './manifests-singleton'
import { workAsyncStorage } from './work-async-storage.external'
let __next_loaded_action_key: CryptoKey let __next_loaded_action_key: CryptoKey
...@@ -71,127 +64,16 @@ export function decrypt( ...@@ -71,127 +64,16 @@ export function decrypt(
) )
} }
// This is a global singleton that is used to encode/decode the action bound args from
// the closure. This can't be using a AsyncLocalStorage as it might happen on the module
// level. Since the client reference manifest won't be mutated, let's use a global singleton
// to keep it.
const SERVER_ACTION_MANIFESTS_SINGLETON = Symbol.for(
'next.server.action-manifests'
)
export function setReferenceManifestsSingleton({
page,
clientReferenceManifest,
serverActionsManifest,
serverModuleMap,
}: {
page: string
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: DeepReadonly<ActionManifest>
serverModuleMap: {
[id: string]: {
id: string
chunks: string[]
name: string
}
}
}) {
// @ts-expect-error
const clientReferenceManifestsPerPage = globalThis[
SERVER_ACTION_MANIFESTS_SINGLETON
]?.clientReferenceManifestsPerPage as
| undefined
| DeepReadonly<Record<string, ClientReferenceManifest>>
// @ts-expect-error
globalThis[SERVER_ACTION_MANIFESTS_SINGLETON] = {
clientReferenceManifestsPerPage: {
...clientReferenceManifestsPerPage,
[normalizeAppPath(page)]: clientReferenceManifest,
},
serverActionsManifest,
serverModuleMap,
}
}
export function getServerModuleMap() {
const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON
] as {
serverModuleMap: {
[id: string]: {
id: string
chunks: string[]
name: string
}
}
}
if (!serverActionsManifestSingleton) {
throw new InvariantError('Missing manifest for Server Actions.')
}
return serverActionsManifestSingleton.serverModuleMap
}
export function getClientReferenceManifestForRsc(): DeepReadonly<ClientReferenceManifestForRsc> {
const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON
] as {
clientReferenceManifestsPerPage: DeepReadonly<
Record<string, ClientReferenceManifest>
>
}
if (!serverActionsManifestSingleton) {
throw new InvariantError('Missing manifest for Server Actions.')
}
const { clientReferenceManifestsPerPage } = serverActionsManifestSingleton
const workStore = workAsyncStorage.getStore()
if (!workStore) {
// If there's no work store defined, we can assume that a client reference
// manifest is needed during module evaluation, e.g. to create a server
// action using a higher-order function. This might also use client
// components which need to be serialized by Flight, and therefore client
// references need to be resolvable. To make this work, we're returning a
// merged manifest across all pages. This is fine as long as the module IDs
// are not page specific, which they are not for Webpack. TODO: Fix this in
// Turbopack.
return mergeClientReferenceManifests(clientReferenceManifestsPerPage)
}
const clientReferenceManifest =
clientReferenceManifestsPerPage[workStore.route]
if (!clientReferenceManifest) {
throw new InvariantError(
`Missing Client Reference Manifest for ${workStore.route}.`
)
}
return clientReferenceManifest
}
export async function getActionEncryptionKey() { export async function getActionEncryptionKey() {
if (__next_loaded_action_key) { if (__next_loaded_action_key) {
return __next_loaded_action_key return __next_loaded_action_key
} }
const serverActionsManifestSingleton = (globalThis as any)[ const serverActionsManifest = getServerActionsManifest()
SERVER_ACTION_MANIFESTS_SINGLETON
] as {
serverActionsManifest: DeepReadonly<ActionManifest>
}
if (!serverActionsManifestSingleton) {
throw new InvariantError('Missing manifest for Server Actions.')
}
const rawKey = const rawKey =
process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY || process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY ||
serverActionsManifestSingleton.serverActionsManifest.encryptionKey serverActionsManifest.encryptionKey
if (rawKey === undefined) { if (rawKey === undefined) {
throw new InvariantError('Missing encryption key for Server Actions') throw new InvariantError('Missing encryption key for Server Actions')
...@@ -207,36 +89,3 @@ export async function getActionEncryptionKey() { ...@@ -207,36 +89,3 @@ export async function getActionEncryptionKey() {
return __next_loaded_action_key return __next_loaded_action_key
} }
function mergeClientReferenceManifests(
clientReferenceManifestsPerPage: DeepReadonly<
Record<string, ClientReferenceManifest>
>
): ClientReferenceManifestForRsc {
const clientReferenceManifests = Object.values(
clientReferenceManifestsPerPage as Record<string, ClientReferenceManifest>
)
const mergedClientReferenceManifest: ClientReferenceManifestForRsc = {
clientModules: {},
edgeRscModuleMapping: {},
rscModuleMapping: {},
}
for (const clientReferenceManifest of clientReferenceManifests) {
mergedClientReferenceManifest.clientModules = {
...mergedClientReferenceManifest.clientModules,
...clientReferenceManifest.clientModules,
}
mergedClientReferenceManifest.edgeRscModuleMapping = {
...mergedClientReferenceManifest.edgeRscModuleMapping,
...clientReferenceManifest.edgeRscModuleMapping,
}
mergedClientReferenceManifest.rscModuleMapping = {
...mergedClientReferenceManifest.rscModuleMapping,
...clientReferenceManifest.rscModuleMapping,
}
}
return mergedClientReferenceManifest
}
...@@ -12,10 +12,12 @@ import { ...@@ -12,10 +12,12 @@ import {
decrypt, decrypt,
encrypt, encrypt,
getActionEncryptionKey, getActionEncryptionKey,
getClientReferenceManifestForRsc,
getServerModuleMap,
stringToUint8Array, stringToUint8Array,
} from './encryption-utils' } from './encryption-utils'
import {
getClientReferenceManifest,
getServerModuleMap,
} from './manifests-singleton'
import { import {
getCacheSignal, getCacheSignal,
getPrerenderResumeDataCache, getPrerenderResumeDataCache,
...@@ -111,7 +113,7 @@ export const encryptActionBoundArgs = React.cache( ...@@ -111,7 +113,7 @@ export const encryptActionBoundArgs = React.cache(
? getCacheSignal(workUnitStore) ? getCacheSignal(workUnitStore)
: undefined : undefined
const { clientModules } = getClientReferenceManifestForRsc() const { clientModules } = getClientReferenceManifest()
// Create an error before any asynchronous calls, to capture the original // Create an error before any asynchronous calls, to capture the original
// call stack in case we need it when the serialization errors. // call stack in case we need it when the serialization errors.
...@@ -250,7 +252,7 @@ export async function decryptActionBoundArgs( ...@@ -250,7 +252,7 @@ export async function decryptActionBoundArgs(
} }
const { edgeRscModuleMapping, rscModuleMapping } = const { edgeRscModuleMapping, rscModuleMapping } =
getClientReferenceManifestForRsc() getClientReferenceManifest()
// Using Flight to deserialize the args from the string. // Using Flight to deserialize the args from the string.
const deserialized = await createFromReadableStream( const deserialized = await createFromReadableStream(
......
import type { import type { CssResource } from '../../build/webpack/plugins/flight-manifest-plugin'
ClientReferenceManifest, import { getClientReferenceManifest } from './manifests-singleton'
CssResource,
} from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
/** /**
* Get external stylesheet link hrefs based on server CSS manifest. * Get external stylesheet link hrefs based on server CSS manifest.
*/ */
export function getLinkAndScriptTags( export function getLinkAndScriptTags(
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
filePath: string, filePath: string,
injectedCSS: Set<string>, injectedCSS: Set<string>,
injectedScripts: Set<string>, injectedScripts: Set<string>,
...@@ -17,14 +13,12 @@ export function getLinkAndScriptTags( ...@@ -17,14 +13,12 @@ export function getLinkAndScriptTags(
const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '') const filePathWithoutExt = filePath.replace(/\.[^.]+$/, '')
const cssChunks = new Set<CssResource>() const cssChunks = new Set<CssResource>()
const jsChunks = new Set<string>() const jsChunks = new Set<string>()
const { entryCSSFiles, entryJSFiles } = getClientReferenceManifest()
const cssFiles = entryCSSFiles[filePathWithoutExt]
const jsFiles = entryJSFiles?.[filePathWithoutExt]
const entryCSSFiles = if (cssFiles) {
clientReferenceManifest.entryCSSFiles[filePathWithoutExt] for (const css of cssFiles) {
const entryJSFiles =
clientReferenceManifest.entryJSFiles?.[filePathWithoutExt] ?? []
if (entryCSSFiles) {
for (const css of entryCSSFiles) {
if (!injectedCSS.has(css.path)) { if (!injectedCSS.has(css.path)) {
if (collectNewImports) { if (collectNewImports) {
injectedCSS.add(css.path) injectedCSS.add(css.path)
...@@ -34,8 +28,8 @@ export function getLinkAndScriptTags( ...@@ -34,8 +28,8 @@ export function getLinkAndScriptTags(
} }
} }
if (entryJSFiles) { if (jsFiles) {
for (const file of entryJSFiles) { for (const file of jsFiles) {
if (!injectedScripts.has(file)) { if (!injectedScripts.has(file)) {
if (collectNewImports) { if (collectNewImports) {
injectedScripts.add(file) injectedScripts.add(file)
......
...@@ -26,7 +26,6 @@ export function getLayerAssets({ ...@@ -26,7 +26,6 @@ export function getLayerAssets({
} = ctx } = ctx
const { styles: styleTags, scripts: scriptTags } = layoutOrPagePath const { styles: styleTags, scripts: scriptTags } = layoutOrPagePath
? getLinkAndScriptTags( ? getLinkAndScriptTags(
ctx.clientReferenceManifest,
layoutOrPagePath, layoutOrPagePath,
injectedCSSWithCurrentLayout, injectedCSSWithCurrentLayout,
injectedJSWithCurrentLayout, injectedJSWithCurrentLayout,
......
import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import { InvariantError } from '../../shared/lib/invariant-error'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { createServerModuleMap, type ServerModuleMap } from './action-utils'
import { workAsyncStorage } from './work-async-storage.external'
// This is a global singleton that is, among other things, also used to
// encode/decode bound args of server function closures. This can't be using a
// AsyncLocalStorage as it might happen at the module level.
const MANIFESTS_SINGLETON = Symbol.for('next.server.manifests')
interface ManifestsSingleton {
readonly clientReferenceManifestsPerRoute: Map<
string,
DeepReadonly<ClientReferenceManifest>
>
readonly proxiedClientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: DeepReadonly<ActionManifest>
serverModuleMap: ServerModuleMap
}
type GlobalThisWithManifests = typeof globalThis & {
[MANIFESTS_SINGLETON]?: ManifestsSingleton
}
type ClientReferenceManifestMappingProp =
| 'clientModules'
| 'rscModuleMapping'
| 'edgeRscModuleMapping'
| 'ssrModuleMapping'
| 'edgeSSRModuleMapping'
const globalThisWithManifests = globalThis as GlobalThisWithManifests
function createProxiedClientReferenceManifest(
clientReferenceManifestsPerRoute: Map<
string,
DeepReadonly<ClientReferenceManifest>
>
): DeepReadonly<ClientReferenceManifest> {
const createMappingProxy = (prop: ClientReferenceManifestMappingProp) => {
return new Proxy(
{},
{
get(_, id: string) {
const workStore = workAsyncStorage.getStore()
if (workStore) {
const currentManifest = clientReferenceManifestsPerRoute.get(
workStore.route
)
if (currentManifest?.[prop][id]) {
return currentManifest[prop][id]
}
// In development, we also check all other manifests to see if the
// module exists there. This is to support a scenario where React's
// I/O tracking (dev-only) creates a connection from one page to
// another through an emitted async I/O node that references client
// components from the other page, e.g. in owner props.
// TODO: Maybe we need to add a `debugBundlerConfig` option to React
// to avoid this workaround. The current workaround has the
// disadvantage that one might accidentally or intentionally share
// client references across pages (e.g. by storing them in a global
// variable), which would then only be caught in production.
if (process.env.NODE_ENV !== 'production') {
for (const [
route,
manifest,
] of clientReferenceManifestsPerRoute) {
if (route === workStore.route) {
continue
}
const entry = manifest[prop][id]
if (entry !== undefined) {
return entry
}
}
}
} else {
// If there's no work store defined, we can assume that a client
// reference manifest is needed during module evaluation, e.g. to
// create a server function using a higher-order function. This
// might also use client components which need to be serialized by
// Flight, and therefore client references need to be resolvable. In
// that case we search all page manifests to find the module.
for (const manifest of clientReferenceManifestsPerRoute.values()) {
const entry = manifest[prop][id]
if (entry !== undefined) {
return entry
}
}
}
return undefined
},
}
)
}
const mappingProxies = new Map<
ClientReferenceManifestMappingProp,
ReturnType<typeof createMappingProxy>
>()
return new Proxy(
{},
{
get(_, prop) {
const workStore = workAsyncStorage.getStore()
switch (prop) {
case 'moduleLoading':
case 'entryCSSFiles':
case 'entryJSFiles': {
if (!workStore) {
throw new InvariantError(
`Cannot access "${prop}" without a work store.`
)
}
const currentManifest = clientReferenceManifestsPerRoute.get(
workStore.route
)
if (!currentManifest) {
throw new InvariantError(
`The client reference manifest for route "${workStore.route}" does not exist.`
)
}
return currentManifest[prop]
}
case 'clientModules':
case 'rscModuleMapping':
case 'edgeRscModuleMapping':
case 'ssrModuleMapping':
case 'edgeSSRModuleMapping': {
let proxy = mappingProxies.get(prop)
if (!proxy) {
proxy = createMappingProxy(prop)
mappingProxies.set(prop, proxy)
}
return proxy
}
default: {
throw new InvariantError(
`This is a proxied client reference manifest. The property "${String(prop)}" is not handled.`
)
}
}
},
}
) as DeepReadonly<ClientReferenceManifest>
}
export function setManifestsSingleton({
page,
clientReferenceManifest,
serverActionsManifest,
}: {
page: string
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: DeepReadonly<ActionManifest>
}) {
const existingSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]
if (existingSingleton) {
existingSingleton.clientReferenceManifestsPerRoute.set(
normalizeAppPath(page),
clientReferenceManifest
)
existingSingleton.serverActionsManifest = serverActionsManifest
existingSingleton.serverModuleMap = createServerModuleMap({
serverActionsManifest,
})
} else {
const clientReferenceManifestsPerRoute = new Map<
string,
DeepReadonly<ClientReferenceManifest>
>([[normalizeAppPath(page), clientReferenceManifest]])
const proxiedClientReferenceManifest = createProxiedClientReferenceManifest(
clientReferenceManifestsPerRoute
)
const serverModuleMap = createServerModuleMap({
serverActionsManifest,
})
globalThisWithManifests[MANIFESTS_SINGLETON] = {
clientReferenceManifestsPerRoute,
proxiedClientReferenceManifest,
serverActionsManifest,
serverModuleMap,
}
}
}
function getManifestsSingleton(): ManifestsSingleton {
const manifestSingleton = globalThisWithManifests[MANIFESTS_SINGLETON]
if (!manifestSingleton) {
throw new InvariantError('The manifests singleton was not initialized.')
}
return manifestSingleton
}
export function getClientReferenceManifest(): DeepReadonly<ClientReferenceManifest> {
return getManifestsSingleton().proxiedClientReferenceManifest
}
export function getServerActionsManifest(): DeepReadonly<ActionManifest> {
return getManifestsSingleton().serverActionsManifest
}
export function getServerModuleMap() {
return getManifestsSingleton().serverModuleMap
}
...@@ -4,7 +4,6 @@ import type { ...@@ -4,7 +4,6 @@ import type {
ExperimentalConfig, ExperimentalConfig,
NextConfigComplete, NextConfigComplete,
} from '../../server/config-shared' } from '../../server/config-shared'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { AppPageModule } from '../route-modules/app-page/module' import type { AppPageModule } from '../route-modules/app-page/module'
...@@ -94,7 +93,6 @@ export interface RenderOptsPartial { ...@@ -94,7 +93,6 @@ export interface RenderOptsPartial {
cacheComponents: boolean cacheComponents: boolean
trailingSlash: boolean trailingSlash: boolean
images: ImageConfigComplete images: ImageConfigComplete
clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
supportsDynamicResponse: boolean supportsDynamicResponse: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
......
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { BinaryStreamOf } from './app-render' import type { BinaryStreamOf } from './app-render'
import type { Readable } from 'node:stream' import type { Readable } from 'node:stream'
import { htmlEscapeJsonString } from '../htmlescape' import { htmlEscapeJsonString } from '../htmlescape'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import { workUnitAsyncStorage } from './work-unit-async-storage.external' import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { getClientReferenceManifest } from './manifests-singleton'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -34,7 +33,6 @@ export function getFlightStream<T>( ...@@ -34,7 +33,6 @@ export function getFlightStream<T>(
flightStream: Readable | BinaryStreamOf<T>, flightStream: Readable | BinaryStreamOf<T>,
debugStream: Readable | ReadableStream<Uint8Array> | undefined, debugStream: Readable | ReadableStream<Uint8Array> | undefined,
debugEndTime: number | undefined, debugEndTime: number | undefined,
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
nonce: string | undefined nonce: string | undefined
): Promise<T> { ): Promise<T> {
const response = flightResponses.get(flightStream) const response = flightResponses.get(flightStream)
...@@ -43,6 +41,9 @@ export function getFlightStream<T>( ...@@ -43,6 +41,9 @@ export function getFlightStream<T>(
return response return response
} }
const { moduleLoading, edgeSSRModuleMapping, ssrModuleMapping } =
getClientReferenceManifest()
let newResponse: Promise<T> let newResponse: Promise<T>
if (flightStream instanceof ReadableStream) { if (flightStream instanceof ReadableStream) {
// The types of flightStream and debugStream should match. // The types of flightStream and debugStream should match.
...@@ -58,10 +59,8 @@ export function getFlightStream<T>( ...@@ -58,10 +59,8 @@ export function getFlightStream<T>(
newResponse = createFromReadableStream<T>(flightStream, { newResponse = createFromReadableStream<T>(flightStream, {
findSourceMapURL, findSourceMapURL,
serverConsumerManifest: { serverConsumerManifest: {
moduleLoading: clientReferenceManifest.moduleLoading, moduleLoading,
moduleMap: isEdgeRuntime moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,
? clientReferenceManifest.edgeSSRModuleMapping
: clientReferenceManifest.ssrModuleMapping,
serverModuleMap: null, serverModuleMap: null,
}, },
nonce, nonce,
...@@ -90,10 +89,8 @@ export function getFlightStream<T>( ...@@ -90,10 +89,8 @@ export function getFlightStream<T>(
newResponse = createFromNodeStream<T>( newResponse = createFromNodeStream<T>(
flightStream, flightStream,
{ {
moduleLoading: clientReferenceManifest.moduleLoading, moduleLoading,
moduleMap: isEdgeRuntime moduleMap: isEdgeRuntime ? edgeSSRModuleMapping : ssrModuleMapping,
? clientReferenceManifest.edgeSSRModuleMapping
: clientReferenceManifest.ssrModuleMapping,
serverModuleMap: null, serverModuleMap: null,
}, },
{ {
......
...@@ -252,7 +252,6 @@ export async function walkTreeWithFlightRouterState({ ...@@ -252,7 +252,6 @@ export async function walkTreeWithFlightRouterState({
) )
if (layoutPath) { if (layoutPath) {
getLinkAndScriptTags( getLinkAndScriptTags(
ctx.clientReferenceManifest,
layoutPath, layoutPath,
injectedCSSWithCurrentLayout, injectedCSSWithCurrentLayout,
injectedJSWithCurrentLayout, injectedJSWithCurrentLayout,
......
...@@ -29,8 +29,7 @@ import { getTracer } from './lib/trace/tracer' ...@@ -29,8 +29,7 @@ import { getTracer } from './lib/trace/tracer'
import { LoadComponentsSpan } from './lib/trace/constants' import { LoadComponentsSpan } from './lib/trace/constants'
import { evalManifest, loadManifest } from './load-manifest.external' import { evalManifest, loadManifest } from './load-manifest.external'
import { wait } from '../lib/wait' import { wait } from '../lib/wait'
import { setReferenceManifestsSingleton } from './app-render/encryption-utils' import { setManifestsSingleton } from './app-render/manifests-singleton'
import { createServerModuleMap } from './app-render/action-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly' import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route' import { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'
...@@ -66,8 +65,6 @@ export type LoadComponentsReturnType<NextModule = any> = { ...@@ -66,8 +65,6 @@ export type LoadComponentsReturnType<NextModule = any> = {
subresourceIntegrityManifest?: DeepReadonly<Record<string, string>> subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>
reactLoadableManifest: DeepReadonly<ReactLoadableManifest> reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
dynamicCssManifest?: DeepReadonly<DynamicCssManifest> dynamicCssManifest?: DeepReadonly<DynamicCssManifest>
clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
serverActionsManifest?: any
Document: DocumentType Document: DocumentType
App: AppType App: AppType
getStaticProps?: GetStaticProps getStaticProps?: GetStaticProps
...@@ -279,13 +276,10 @@ async function loadComponentsImpl<N = any>({ ...@@ -279,13 +276,10 @@ async function loadComponentsImpl<N = any>({
// manifests to our global store so Server Action's encryption util can access // manifests to our global store so Server Action's encryption util can access
// to them at the top level of the page module. // to them at the top level of the page module.
if (serverActionsManifest && clientReferenceManifest) { if (serverActionsManifest && clientReferenceManifest) {
setReferenceManifestsSingleton({ setManifestsSingleton({
page, page,
clientReferenceManifest, clientReferenceManifest,
serverActionsManifest, serverActionsManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest,
}),
}) })
} }
...@@ -311,8 +305,6 @@ async function loadComponentsImpl<N = any>({ ...@@ -311,8 +305,6 @@ async function loadComponentsImpl<N = any>({
getServerSideProps, getServerSideProps,
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
clientReferenceManifest,
serverActionsManifest,
isAppPath, isAppPath,
page, page,
routeModule, routeModule,
......
...@@ -3,7 +3,6 @@ import type { ...@@ -3,7 +3,6 @@ import type {
DocumentType, DocumentType,
NextComponentType, NextComponentType,
} from '../shared/lib/utils' } from '../shared/lib/utils'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type { import type {
PageConfig, PageConfig,
GetStaticPaths, GetStaticPaths,
...@@ -32,8 +31,6 @@ export type LoadComponentsReturnType = { ...@@ -32,8 +31,6 @@ export type LoadComponentsReturnType = {
buildManifest: BuildManifest buildManifest: BuildManifest
subresourceIntegrityManifest?: Record<string, string> subresourceIntegrityManifest?: Record<string, string>
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
clientReferenceManifest?: ClientReferenceManifest
serverActionsManifest?: any
Document: DocumentType Document: DocumentType
App: AppType App: AppType
getStaticProps?: GetStaticProps getStaticProps?: GetStaticProps
......
...@@ -42,12 +42,12 @@ import { ...@@ -42,12 +42,12 @@ import {
makeHangingPromise, makeHangingPromise,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import type { ClientReferenceManifestForRsc } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import { import {
getClientReferenceManifestForRsc, getClientReferenceManifest,
getServerModuleMap, getServerModuleMap,
} from '../app-render/encryption-utils' } from '../app-render/manifests-singleton'
import type { CacheEntry } from '../lib/cache-handlers/types' import type { CacheEntry } from '../lib/cache-handlers/types'
import type { CacheSignal } from '../app-render/cache-signal' import type { CacheSignal } from '../app-render/cache-signal'
import { decryptActionBoundArgs } from '../app-render/encryption' import { decryptActionBoundArgs } from '../app-render/encryption'
...@@ -134,7 +134,7 @@ const findSourceMapURL = ...@@ -134,7 +134,7 @@ const findSourceMapURL =
function generateCacheEntry( function generateCacheEntry(
workStore: WorkStore, workStore: WorkStore,
cacheContext: CacheContext, cacheContext: CacheContext,
clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
encodedArguments: FormData | string, encodedArguments: FormData | string,
fn: (...args: unknown[]) => Promise<unknown>, fn: (...args: unknown[]) => Promise<unknown>,
timeoutError: UseCacheTimeoutError timeoutError: UseCacheTimeoutError
...@@ -158,7 +158,7 @@ function generateCacheEntry( ...@@ -158,7 +158,7 @@ function generateCacheEntry(
function generateCacheEntryWithRestoredWorkStore( function generateCacheEntryWithRestoredWorkStore(
workStore: WorkStore, workStore: WorkStore,
cacheContext: CacheContext, cacheContext: CacheContext,
clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
encodedArguments: FormData | string, encodedArguments: FormData | string,
fn: (...args: unknown[]) => Promise<unknown>, fn: (...args: unknown[]) => Promise<unknown>,
timeoutError: UseCacheTimeoutError timeoutError: UseCacheTimeoutError
...@@ -281,7 +281,7 @@ function assertDefaultCacheLife( ...@@ -281,7 +281,7 @@ function assertDefaultCacheLife(
function generateCacheEntryWithCacheContext( function generateCacheEntryWithCacheContext(
workStore: WorkStore, workStore: WorkStore,
cacheContext: CacheContext, cacheContext: CacheContext,
clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
encodedArguments: FormData | string, encodedArguments: FormData | string,
fn: (...args: unknown[]) => Promise<unknown>, fn: (...args: unknown[]) => Promise<unknown>,
timeoutError: UseCacheTimeoutError timeoutError: UseCacheTimeoutError
...@@ -521,7 +521,7 @@ async function generateCacheEntryImpl( ...@@ -521,7 +521,7 @@ async function generateCacheEntryImpl(
workStore: WorkStore, workStore: WorkStore,
cacheContext: CacheContext, cacheContext: CacheContext,
innerCacheStore: UseCacheStore, innerCacheStore: UseCacheStore,
clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
encodedArguments: FormData | string, encodedArguments: FormData | string,
fn: (...args: unknown[]) => Promise<unknown>, fn: (...args: unknown[]) => Promise<unknown>,
timeoutError: UseCacheTimeoutError timeoutError: UseCacheTimeoutError
...@@ -978,7 +978,7 @@ export async function cache( ...@@ -978,7 +978,7 @@ export async function cache(
// Get the clientReferenceManifest while we're still in the outer Context. // Get the clientReferenceManifest while we're still in the outer Context.
// In case getClientReferenceManifestSingleton is implemented using AsyncLocalStorage. // In case getClientReferenceManifestSingleton is implemented using AsyncLocalStorage.
const clientReferenceManifest = getClientReferenceManifestForRsc() const clientReferenceManifest = getClientReferenceManifest()
// Because the Action ID is not yet unique per implementation of that Action we can't // Because the Action ID is not yet unique per implementation of that Action we can't
// safely reuse the results across builds yet. In the meantime we add the buildId to the // safely reuse the results across builds yet. In the meantime we add the buildId to the
......
...@@ -226,9 +226,9 @@ declare module 'react-server-dom-webpack/server.node' { ...@@ -226,9 +226,9 @@ declare module 'react-server-dom-webpack/server.node' {
export type TemporaryReferenceSet = WeakMap<any, string> export type TemporaryReferenceSet = WeakMap<any, string>
export type ImportManifestEntry = { export type ImportManifestEntry = {
id: string id: string | number
// chunks is a double indexed array of chunkId / chunkFilename pairs // chunks is a double indexed array of chunkId / chunkFilename pairs
chunks: Array<string> chunks: ReadonlyArray<string>
name: string name: string
async?: boolean async?: boolean
} }
...@@ -279,7 +279,7 @@ declare module 'react-server-dom-webpack/static' { ...@@ -279,7 +279,7 @@ declare module 'react-server-dom-webpack/static' {
webpackMap: { webpackMap: {
readonly [id: string]: { readonly [id: string]: {
readonly id: string | number readonly id: string | number
readonly chunks: readonly string[] readonly chunks: ReadonlyArray<string>
readonly name: string readonly name: string
readonly async?: boolean readonly async?: boolean
} }
......
...@@ -105,6 +105,13 @@ function webpack5(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) { ...@@ -105,6 +105,13 @@ function webpack5(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) {
`options.factory = ${runtimeTemplate.basicFunction( `options.factory = ${runtimeTemplate.basicFunction(
'moduleObject, moduleExports, webpackRequire', 'moduleObject, moduleExports, webpackRequire',
[ [
// If the original factory is missing, e.g. due to race condition
// when compiling multiple entries concurrently, recover by doing
// a full page reload.
'if (!originalFactory) {',
Template.indent('document.location.reload();'),
Template.indent('return;'),
'}',
// Legacy CSS implementations will `eval` browser code in a Node.js // Legacy CSS implementations will `eval` browser code in a Node.js
// context to extract CSS. For backwards compatibility, we need to check // context to extract CSS. For backwards compatibility, we need to check
// we're in a browser context before continuing. // we're in a browser context before continuing.
......
import { Suspense } from 'react'
export default function Root({ children }: { children: React.ReactNode }) {
return <Suspense>{children}</Suspense>
}
'use client'
export function Component() {
return <p>Component</p>
}
import { subscribeToHMR } from './subscribeToHMR'
import { Component } from './Component'
// The (unused) client component prop is crucial to reproduce the issue. It will
// be serialized as a client reference in the props of this component, which
// acts as the owner of the I/O inside subscribeToHMR, which is also serialized
// as part of the async I/O sequence in page 2.
const RootPage = async ({ Component }: { Component: React.ComponentType }) => {
await subscribeToHMR()
return (
<html>
<body>
<iframe src="/page2" />
</body>
</html>
)
}
export default function Page1() {
return <RootPage Component={Component} />
}
declare global {
var _testState: {
initialized: boolean
reload: boolean | Promise<void>
}
}
if (!globalThis._testState) {
globalThis._testState = {
initialized: false,
reload: false,
}
}
export const subscribeToHMR = async () => {
const state = globalThis._testState
if (state.initialized) {
if (state.reload === true) {
let resolve: () => void
state.reload = new Promise<void>((res) => (resolve = res))
await new Promise((resolve) => setTimeout(resolve, 200))
resolve()
}
if (state.reload instanceof Promise) {
await state.reload
}
return
}
state.initialized = true
const ws = new WebSocket(
`ws://localhost:${process.env.PORT}/_next/webpack-hmr`
)
ws.onmessage = (event: any) => {
if (typeof event.data === 'string') {
const data = JSON.parse(event.data)
if (data.type === 'serverComponentChanges') {
state.reload = true
}
}
}
}
import { subscribeToHMR } from '../page1/subscribeToHMR'
export default async function Page2() {
await subscribeToHMR()
return (
<html>
<body>
<p>content</p>
</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
import { waitForNoRedbox } from 'next-test-utils'
describe('hmr-iframe', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should do HMR when rendering two server component changes at the same time', async () => {
let browser = await next.browser('/page1')
expect(
await (await (await browser.elementByCss('iframe')).contentFrame())
.locator('p')
.innerText()
).toEqual('content')
let cliOutputLength = next.cliOutput.length
await next.patchFile('app/page2/page.tsx', (content) =>
content.replace('content', 'content-new')
)
await waitForNoRedbox(browser)
expect(
await (await (await browser.elementByCss('iframe')).contentFrame())
.locator('p')
.innerText()
).toEqual('content-new')
const cliOutput = next.cliOutput.slice(cliOutputLength)
expect(cliOutput).not.toContain('Error')
expect(cliOutput).not.toContain('Could not find the module')
await next.stop()
await next.clean()
})
})
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