Commit 01c7c850 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by Janka Uryga

Freeze loaded manifests (#64313)

Manifests in the runtime should be treated as immutable objects to
ensure that side effects aren't created that depend on the mutability of
these shared objects. Instead, mutable references should be used in
places where this is desirable.

This also introduces the new `DeepReadonly` utility type, which when
paired with existing manifest types, will modify every field to be read
only, ensuring that the type system will help catch accidental
modifications to these loaded manifest values as well.

Future work could eliminate these types by modifying the manifest types
themselves to be read only, only allowing code that generated them to be
writable.

Closes NEXT-3069
parent a48be87f
...@@ -185,6 +185,7 @@ import { buildCustomRoute } from '../lib/build-custom-route' ...@@ -185,6 +185,7 @@ import { buildCustomRoute } from '../lib/build-custom-route'
import { createProgress } from './progress' import { createProgress } from './progress'
import { traceMemoryUsage } from '../lib/memory/trace' import { traceMemoryUsage } from '../lib/memory/trace'
import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils' import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
interface ExperimentalBypassForInfo { interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[] experimentalBypassFor?: RouteHas[]
...@@ -337,7 +338,7 @@ async function readManifest<T extends object>(filePath: string): Promise<T> { ...@@ -337,7 +338,7 @@ async function readManifest<T extends object>(filePath: string): Promise<T> {
async function writePrerenderManifest( async function writePrerenderManifest(
distDir: string, distDir: string,
manifest: Readonly<PrerenderManifest> manifest: DeepReadonly<PrerenderManifest>
): Promise<void> { ): Promise<void> {
await writeManifest(path.join(distDir, PRERENDER_MANIFEST), manifest) await writeManifest(path.join(distDir, PRERENDER_MANIFEST), manifest)
await writeEdgePartialPrerenderManifest(distDir, manifest) await writeEdgePartialPrerenderManifest(distDir, manifest)
...@@ -345,19 +346,20 @@ async function writePrerenderManifest( ...@@ -345,19 +346,20 @@ async function writePrerenderManifest(
async function writeEdgePartialPrerenderManifest( async function writeEdgePartialPrerenderManifest(
distDir: string, distDir: string,
manifest: Readonly<Partial<PrerenderManifest>> manifest: DeepReadonly<Partial<PrerenderManifest>>
): Promise<void> { ): Promise<void> {
// We need to write a partial prerender manifest to make preview mode settings available in edge middleware. // We need to write a partial prerender manifest to make preview mode settings available in edge middleware.
// Use env vars in JS bundle and inject the actual vars to edge manifest. // Use env vars in JS bundle and inject the actual vars to edge manifest.
const edgePartialPrerenderManifest: Partial<PrerenderManifest> = { const edgePartialPrerenderManifest: DeepReadonly<Partial<PrerenderManifest>> =
...manifest, {
preview: { ...manifest,
previewModeId: 'process.env.__NEXT_PREVIEW_MODE_ID', preview: {
previewModeSigningKey: 'process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY', previewModeId: 'process.env.__NEXT_PREVIEW_MODE_ID',
previewModeEncryptionKey: previewModeSigningKey: 'process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY',
'process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY', previewModeEncryptionKey:
}, 'process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY',
} },
}
await writeFileUtf8( await writeFileUtf8(
path.join(distDir, PRERENDER_MANIFEST.replace(/\.json$/, '.js')), path.join(distDir, PRERENDER_MANIFEST.replace(/\.json$/, '.js')),
`self.__PRERENDER_MANIFEST=${JSON.stringify( `self.__PRERENDER_MANIFEST=${JSON.stringify(
...@@ -367,7 +369,7 @@ async function writeEdgePartialPrerenderManifest( ...@@ -367,7 +369,7 @@ async function writeEdgePartialPrerenderManifest(
} }
async function writeClientSsgManifest( async function writeClientSsgManifest(
prerenderManifest: PrerenderManifest, prerenderManifest: DeepReadonly<PrerenderManifest>,
{ {
buildId, buildId,
distDir, distDir,
...@@ -3323,7 +3325,7 @@ export default async function build( ...@@ -3323,7 +3325,7 @@ export default async function build(
NextBuildContext.allowedRevalidateHeaderKeys = NextBuildContext.allowedRevalidateHeaderKeys =
config.experimental.allowedRevalidateHeaderKeys config.experimental.allowedRevalidateHeaderKeys
const prerenderManifest: Readonly<PrerenderManifest> = { const prerenderManifest: DeepReadonly<PrerenderManifest> = {
version: 4, version: 4,
routes: finalPrerenderRoutes, routes: finalPrerenderRoutes,
dynamicRoutes: finalDynamicRoutes, dynamicRoutes: finalDynamicRoutes,
......
...@@ -19,6 +19,7 @@ import type { SizeLimit } from '../../../../../types' ...@@ -19,6 +19,7 @@ import type { SizeLimit } from '../../../../../types'
import { internal_getCurrentFunctionWaitUntil } from '../../../../server/web/internal-edge-wait-until' import { internal_getCurrentFunctionWaitUntil } from '../../../../server/web/internal-edge-wait-until'
import type { PAGE_TYPES } from '../../../../lib/page-types' import type { PAGE_TYPES } from '../../../../lib/page-types'
import type { NextRequestHint } from '../../../../server/web/adapter' import type { NextRequestHint } from '../../../../server/web/adapter'
import type { DeepReadonly } from '../../../../shared/lib/deep-readonly'
export function getRender({ export function getRender({
dev, dev,
...@@ -53,7 +54,7 @@ export function getRender({ ...@@ -53,7 +54,7 @@ export function getRender({
renderToHTML?: any renderToHTML?: any
Document: DocumentType Document: DocumentType
buildManifest: BuildManifest buildManifest: BuildManifest
prerenderManifest: PrerenderManifest prerenderManifest: DeepReadonly<PrerenderManifest>
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
subresourceIntegrityManifest?: Record<string, string> subresourceIntegrityManifest?: Record<string, string>
interceptionRouteRewrites?: ManifestRewriteRoute[] interceptionRouteRewrites?: ManifestRewriteRoute[]
......
...@@ -70,7 +70,7 @@ export interface ManifestNode { ...@@ -70,7 +70,7 @@ export interface ManifestNode {
} }
export type ClientReferenceManifest = { export type ClientReferenceManifest = {
moduleLoading: { readonly moduleLoading: {
prefix: string prefix: string
crossOrigin: string | null crossOrigin: string | null
} }
......
...@@ -8,13 +8,16 @@ import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/ada ...@@ -8,13 +8,16 @@ import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/ada
// eslint-disable-next-line @typescript-eslint/no-unused-expressions // eslint-disable-next-line @typescript-eslint/no-unused-expressions
;('TURBOPACK { transition: next-shared }') ;('TURBOPACK { transition: next-shared }')
import { requestAsyncStorage } from './request-async-storage-instance' import { requestAsyncStorage } from './request-async-storage-instance'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
export interface RequestStore { export interface RequestStore {
readonly headers: ReadonlyHeaders readonly headers: ReadonlyHeaders
readonly cookies: ReadonlyRequestCookies readonly cookies: ReadonlyRequestCookies
readonly mutableCookies: ResponseCookies readonly mutableCookies: ResponseCookies
readonly draftMode: DraftModeProvider readonly draftMode: DraftModeProvider
readonly reactLoadableManifest: Record<string, { files: string[] }> readonly reactLoadableManifest: DeepReadonly<
Record<string, { files: string[] }>
>
readonly assetPrefix: string readonly assetPrefix: string
} }
......
...@@ -56,6 +56,7 @@ import { formatManifest } from '../build/manifests/formatter/format-manifest' ...@@ -56,6 +56,7 @@ import { formatManifest } from '../build/manifests/formatter/format-manifest'
import { validateRevalidate } from '../server/lib/patch-fetch' import { validateRevalidate } from '../server/lib/patch-fetch'
import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace' import { TurborepoAccessTraceResult } from '../build/turborepo-access-trace'
import { createProgress } from '../build/progress' import { createProgress } from '../build/progress'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
export class ExportError extends Error { export class ExportError extends Error {
code = 'NEXT_EXPORT_ERROR' code = 'NEXT_EXPORT_ERROR'
...@@ -188,7 +189,7 @@ export async function exportAppImpl( ...@@ -188,7 +189,7 @@ export async function exportAppImpl(
!options.pages && !options.pages &&
(require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST)) as PagesManifest) (require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST)) as PagesManifest)
let prerenderManifest: PrerenderManifest | undefined let prerenderManifest: DeepReadonly<PrerenderManifest> | undefined
try { try {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST)) prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
} catch {} } catch {}
......
...@@ -25,6 +25,7 @@ import { ...@@ -25,6 +25,7 @@ import {
} from '../shared/lib/html-context.shared-runtime' } from '../shared/lib/html-context.shared-runtime'
import type { HtmlProps } from '../shared/lib/html-context.shared-runtime' import type { HtmlProps } from '../shared/lib/html-context.shared-runtime'
import { encodeURIPath } from '../shared/lib/encode-uri-path' import { encodeURIPath } from '../shared/lib/encode-uri-path'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
export type { DocumentContext, DocumentInitialProps, DocumentProps } export type { DocumentContext, DocumentInitialProps, DocumentProps }
...@@ -360,7 +361,7 @@ function getAmpPath(ampPath: string, asPath: string): string { ...@@ -360,7 +361,7 @@ function getAmpPath(ampPath: string, asPath: string): string {
} }
function getNextFontLinkTags( function getNextFontLinkTags(
nextFontManifest: NextFontManifest | undefined, nextFontManifest: DeepReadonly<NextFontManifest> | undefined,
dangerousAsPath: string, dangerousAsPath: string,
assetPrefix: string = '' assetPrefix: string = ''
) { ) {
......
...@@ -110,6 +110,7 @@ import { ...@@ -110,6 +110,7 @@ import {
wrapClientComponentLoader, wrapClientComponentLoader,
} from '../client-component-renderer-logger' } from '../client-component-renderer-logger'
import { createServerModuleMap } from './action-utils' import { createServerModuleMap } from './action-utils'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -140,7 +141,7 @@ export type AppRenderContext = AppRenderBaseContext & { ...@@ -140,7 +141,7 @@ export type AppRenderContext = AppRenderBaseContext & {
requestId: string requestId: string
defaultRevalidate: Revalidate defaultRevalidate: Revalidate
pagePath: string pagePath: string
clientReferenceManifest: ClientReferenceManifest clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
assetPrefix: string assetPrefix: string
flightDataRendererErrorHandler: ErrorHandler flightDataRendererErrorHandler: ErrorHandler
serverComponentsErrorHandler: ErrorHandler serverComponentsErrorHandler: ErrorHandler
......
import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin' import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
// Keep the key in memory as it should never change during the lifetime of the server in // Keep the key in memory as it should never change during the lifetime of the server in
// both development and production. // both development and production.
...@@ -116,8 +117,8 @@ export function setReferenceManifestsSingleton({ ...@@ -116,8 +117,8 @@ export function setReferenceManifestsSingleton({
serverActionsManifest, serverActionsManifest,
serverModuleMap, serverModuleMap,
}: { }: {
clientReferenceManifest: ClientReferenceManifest clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: ActionManifest serverActionsManifest: DeepReadonly<ActionManifest>
serverModuleMap: { serverModuleMap: {
[id: string]: { [id: string]: {
id: string id: string
...@@ -160,8 +161,8 @@ export function getClientReferenceManifestSingleton() { ...@@ -160,8 +161,8 @@ export function getClientReferenceManifestSingleton() {
const serverActionsManifestSingleton = (globalThis as any)[ const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON SERVER_ACTION_MANIFESTS_SINGLETON
] as { ] as {
clientReferenceManifest: ClientReferenceManifest clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: ActionManifest serverActionsManifest: DeepReadonly<ActionManifest>
} }
if (!serverActionsManifestSingleton) { if (!serverActionsManifestSingleton) {
...@@ -181,8 +182,8 @@ export async function getActionEncryptionKey() { ...@@ -181,8 +182,8 @@ export async function getActionEncryptionKey() {
const serverActionsManifestSingleton = (globalThis as any)[ const serverActionsManifestSingleton = (globalThis as any)[
SERVER_ACTION_MANIFESTS_SINGLETON SERVER_ACTION_MANIFESTS_SINGLETON
] as { ] as {
clientReferenceManifest: ClientReferenceManifest clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
serverActionsManifest: ActionManifest serverActionsManifest: DeepReadonly<ActionManifest>
} }
if (!serverActionsManifestSingleton) { if (!serverActionsManifestSingleton) {
......
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin' import type { ClientReferenceManifest } 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: ClientReferenceManifest, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
filePath: string, filePath: string,
injectedCSS: Set<string>, injectedCSS: Set<string>,
injectedScripts: Set<string>, injectedScripts: Set<string>,
......
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
/** /**
* Get hrefs for fonts to preload * Get hrefs for fonts to preload
...@@ -8,7 +9,7 @@ import type { NextFontManifest } from '../../build/webpack/plugins/next-font-man ...@@ -8,7 +9,7 @@ import type { NextFontManifest } from '../../build/webpack/plugins/next-font-man
* Returns null if there are fonts but none to preload and at least some were previously preloaded * Returns null if there are fonts but none to preload and at least some were previously preloaded
*/ */
export function getPreloadableFonts( export function getPreloadableFonts(
nextFontManifest: NextFontManifest | undefined, nextFontManifest: DeepReadonly<NextFontManifest> | undefined,
filePath: string | undefined, filePath: string | undefined,
injectedFontPreloadTags: Set<string> injectedFontPreloadTags: Set<string>
): string[] | null { ): string[] | null {
......
...@@ -7,6 +7,7 @@ import type { ParsedUrlQuery } from 'querystring' ...@@ -7,6 +7,7 @@ import type { ParsedUrlQuery } from 'querystring'
import type { AppPageModule } from '../future/route-modules/app-page/module' import type { AppPageModule } from '../future/route-modules/app-page/module'
import type { SwrDelta } from '../lib/revalidate' import type { SwrDelta } from '../lib/revalidate'
import type { LoadingModuleData } from '../../shared/lib/app-router-context.shared-runtime' import type { LoadingModuleData } from '../../shared/lib/app-router-context.shared-runtime'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import s from 'next/dist/compiled/superstruct' import s from 'next/dist/compiled/superstruct'
...@@ -126,14 +127,14 @@ export interface RenderOptsPartial { ...@@ -126,14 +127,14 @@ export interface RenderOptsPartial {
buildId: string buildId: string
basePath: string basePath: string
trailingSlash: boolean trailingSlash: boolean
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
supportsDynamicHTML: boolean supportsDynamicHTML: boolean
runtime?: ServerRuntime runtime?: ServerRuntime
serverComponents?: boolean serverComponents?: boolean
enableTainting?: boolean enableTainting?: boolean
assetPrefix?: string assetPrefix?: string
crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined crossOrigin?: '' | 'anonymous' | 'use-credentials' | undefined
nextFontManifest?: NextFontManifest nextFontManifest?: DeepReadonly<NextFontManifest>
isBot?: boolean isBot?: boolean
incrementalCache?: import('../lib/incremental-cache').IncrementalCache incrementalCache?: import('../lib/incremental-cache').IncrementalCache
isRevalidate?: boolean isRevalidate?: boolean
......
...@@ -2,6 +2,7 @@ import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight ...@@ -2,6 +2,7 @@ import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight
import type { BinaryStreamOf } from './app-render' import type { BinaryStreamOf } from './app-render'
import { htmlEscapeJsonString } from '../htmlescape' import { htmlEscapeJsonString } from '../htmlescape'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -18,7 +19,7 @@ const encoder = new TextEncoder() ...@@ -18,7 +19,7 @@ const encoder = new TextEncoder()
*/ */
export function useFlightStream<T>( export function useFlightStream<T>(
flightStream: BinaryStreamOf<T>, flightStream: BinaryStreamOf<T>,
clientReferenceManifest: ClientReferenceManifest, clientReferenceManifest: DeepReadonly<ClientReferenceManifest>,
nonce?: string nonce?: string
): Promise<T> { ): Promise<T> {
const response = flightResponses.get(flightStream) const response = flightResponses.get(flightStream)
......
...@@ -135,6 +135,7 @@ import { NextDataPathnameNormalizer } from './future/normalizers/request/next-da ...@@ -135,6 +135,7 @@ import { NextDataPathnameNormalizer } from './future/normalizers/request/next-da
import { getIsServerAction } from './lib/server-action-request-meta' import { getIsServerAction } from './lib/server-action-request-meta'
import { isInterceptionRouteAppPath } from './future/helpers/interception-routes' import { isInterceptionRouteAppPath } from './future/helpers/interception-routes'
import { toRoute } from './lib/to-route' import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -285,9 +286,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -285,9 +286,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected readonly renderOpts: BaseRenderOpts protected readonly renderOpts: BaseRenderOpts
protected readonly serverOptions: Readonly<ServerOptions> protected readonly serverOptions: Readonly<ServerOptions>
protected readonly appPathRoutes?: Record<string, string[]> protected readonly appPathRoutes?: Record<string, string[]>
protected readonly clientReferenceManifest?: ClientReferenceManifest protected readonly clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
protected interceptionRoutePatterns: RegExp[] protected interceptionRoutePatterns: RegExp[]
protected nextFontManifest?: NextFontManifest protected nextFontManifest?: DeepReadonly<NextFontManifest>
private readonly responseCache: ResponseCacheBase private readonly responseCache: ResponseCacheBase
protected abstract getPublicDir(): string protected abstract getPublicDir(): string
...@@ -314,9 +315,11 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -314,9 +315,11 @@ export default abstract class Server<ServerOptions extends Options = Options> {
shouldEnsure?: boolean shouldEnsure?: boolean
url?: string url?: string
}): Promise<FindComponentsResult | null> }): Promise<FindComponentsResult | null>
protected abstract getFontManifest(): FontManifest | undefined protected abstract getFontManifest(): DeepReadonly<FontManifest> | undefined
protected abstract getPrerenderManifest(): PrerenderManifest protected abstract getPrerenderManifest(): DeepReadonly<PrerenderManifest>
protected abstract getNextFontManifest(): NextFontManifest | undefined protected abstract getNextFontManifest():
| DeepReadonly<NextFontManifest>
| undefined
protected abstract attachRequestMeta( protected abstract attachRequestMeta(
req: BaseNextRequest, req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery parsedUrl: NextUrlWithParsedQuery
......
...@@ -4,6 +4,7 @@ import type { AppConfig } from '../../../../build/utils' ...@@ -4,6 +4,7 @@ import type { AppConfig } from '../../../../build/utils'
import type { NextRequest } from '../../../web/spec-extension/request' import type { NextRequest } from '../../../web/spec-extension/request'
import type { PrerenderManifest } from '../../../../build' import type { PrerenderManifest } from '../../../../build'
import type { NextURL } from '../../../web/next-url' import type { NextURL } from '../../../web/next-url'
import type { DeepReadonly } from '../../../../shared/lib/deep-readonly'
import { import {
RouteModule, RouteModule,
...@@ -68,7 +69,7 @@ export type AppRouteModule = ...@@ -68,7 +69,7 @@ export type AppRouteModule =
*/ */
export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext { export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
renderOpts: StaticGenerationContext['renderOpts'] renderOpts: StaticGenerationContext['renderOpts']
prerenderManifest: PrerenderManifest prerenderManifest: DeepReadonly<PrerenderManifest>
} }
/** /**
......
...@@ -7,6 +7,7 @@ import type { ...@@ -7,6 +7,7 @@ import type {
IncrementalCacheKindHint, IncrementalCacheKindHint,
} from '../../response-cache' } from '../../response-cache'
import type { Revalidate } from '../revalidate' import type { Revalidate } from '../revalidate'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import FetchCache from './fetch-cache' import FetchCache from './fetch-cache'
import FileSystemCache from './file-system-cache' import FileSystemCache from './file-system-cache'
...@@ -69,7 +70,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -69,7 +70,7 @@ export class IncrementalCache implements IncrementalCacheType {
readonly disableForTestmode?: boolean readonly disableForTestmode?: boolean
readonly cacheHandler?: CacheHandler readonly cacheHandler?: CacheHandler
readonly hasCustomCacheHandler: boolean readonly hasCustomCacheHandler: boolean
readonly prerenderManifest: PrerenderManifest readonly prerenderManifest: DeepReadonly<PrerenderManifest>
readonly requestHeaders: Record<string, undefined | string | string[]> readonly requestHeaders: Record<string, undefined | string | string[]>
readonly requestProtocol?: 'http' | 'https' readonly requestProtocol?: 'http' | 'https'
readonly allowedRevalidateHeaderKeys?: string[] readonly allowedRevalidateHeaderKeys?: string[]
...@@ -117,7 +118,7 @@ export class IncrementalCache implements IncrementalCacheType { ...@@ -117,7 +118,7 @@ export class IncrementalCache implements IncrementalCacheType {
allowedRevalidateHeaderKeys?: string[] allowedRevalidateHeaderKeys?: string[]
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
getPrerenderManifest: () => PrerenderManifest getPrerenderManifest: () => DeepReadonly<PrerenderManifest>
fetchCacheKeyPrefix?: string fetchCacheKeyPrefix?: string
CurCacheHandler?: typeof CacheHandler CurCacheHandler?: typeof CacheHandler
experimental: { ppr: boolean } experimental: { ppr: boolean }
......
import type { PrerenderManifest } from '../../../build' import type { PrerenderManifest } from '../../../build'
import type { DeepReadonly } from '../../../shared/lib/deep-readonly'
import type { Revalidate } from '../revalidate' import type { Revalidate } from '../revalidate'
/** /**
...@@ -18,7 +19,9 @@ export class SharedRevalidateTimings { ...@@ -18,7 +19,9 @@ export class SharedRevalidateTimings {
* The prerender manifest that contains the initial revalidate timings for * The prerender manifest that contains the initial revalidate timings for
* routes. * routes.
*/ */
private readonly prerenderManifest: Pick<PrerenderManifest, 'routes'> private readonly prerenderManifest: DeepReadonly<
Pick<PrerenderManifest, 'routes'>
>
) {} ) {}
/** /**
......
...@@ -30,6 +30,7 @@ import { evalManifest, loadManifest } from './load-manifest' ...@@ -30,6 +30,7 @@ import { evalManifest, loadManifest } from './load-manifest'
import { wait } from '../lib/wait' import { wait } from '../lib/wait'
import { setReferenceManifestsSingleton } from './app-render/encryption-utils' import { setReferenceManifestsSingleton } from './app-render/encryption-utils'
import { createServerModuleMap } from './app-render/action-utils' import { createServerModuleMap } from './app-render/action-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
export type ManifestItem = { export type ManifestItem = {
id: number | string id: number | string
...@@ -52,10 +53,10 @@ export interface LoadableManifest { ...@@ -52,10 +53,10 @@ export interface LoadableManifest {
export type LoadComponentsReturnType<NextModule = any> = { export type LoadComponentsReturnType<NextModule = any> = {
Component: NextComponentType Component: NextComponentType
pageConfig: PageConfig pageConfig: PageConfig
buildManifest: BuildManifest buildManifest: DeepReadonly<BuildManifest>
subresourceIntegrityManifest?: Record<string, string> subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
serverActionsManifest?: any serverActionsManifest?: any
Document: DocumentType Document: DocumentType
App: AppType App: AppType
...@@ -71,13 +72,13 @@ export type LoadComponentsReturnType<NextModule = any> = { ...@@ -71,13 +72,13 @@ export type LoadComponentsReturnType<NextModule = any> = {
/** /**
* Load manifest file with retries, defaults to 3 attempts. * Load manifest file with retries, defaults to 3 attempts.
*/ */
export async function loadManifestWithRetries( export async function loadManifestWithRetries<T extends object>(
manifestPath: string, manifestPath: string,
attempts = 3 attempts = 3
): Promise<unknown> { ) {
while (true) { while (true) {
try { try {
return loadManifest(manifestPath) return loadManifest<T>(manifestPath)
} catch (err) { } catch (err) {
attempts-- attempts--
if (attempts <= 0) throw err if (attempts <= 0) throw err
...@@ -90,13 +91,13 @@ export async function loadManifestWithRetries( ...@@ -90,13 +91,13 @@ export async function loadManifestWithRetries(
/** /**
* Load manifest file with retries, defaults to 3 attempts. * Load manifest file with retries, defaults to 3 attempts.
*/ */
export async function evalManifestWithRetries( export async function evalManifestWithRetries<T extends object>(
manifestPath: string, manifestPath: string,
attempts = 3 attempts = 3
): Promise<unknown> { ) {
while (true) { while (true) {
try { try {
return evalManifest(manifestPath) return evalManifest<T>(manifestPath)
} catch (err) { } catch (err) {
attempts-- attempts--
if (attempts <= 0) throw err if (attempts <= 0) throw err
...@@ -109,12 +110,12 @@ export async function evalManifestWithRetries( ...@@ -109,12 +110,12 @@ export async function evalManifestWithRetries(
async function loadClientReferenceManifest( async function loadClientReferenceManifest(
manifestPath: string, manifestPath: string,
entryName: string entryName: string
): Promise<ClientReferenceManifest | undefined> { ) {
try { try {
const context = (await evalManifestWithRetries(manifestPath)) as { const context = await evalManifestWithRetries<{
__RSC_MANIFEST: { [key: string]: ClientReferenceManifest } __RSC_MANIFEST: { [key: string]: ClientReferenceManifest }
} }>(manifestPath)
return context.__RSC_MANIFEST[entryName] as ClientReferenceManifest return context.__RSC_MANIFEST[entryName]
} catch (err) { } catch (err) {
return undefined return undefined
} }
...@@ -149,12 +150,10 @@ async function loadComponentsImpl<N = any>({ ...@@ -149,12 +150,10 @@ async function loadComponentsImpl<N = any>({
clientReferenceManifest, clientReferenceManifest,
serverActionsManifest, serverActionsManifest,
] = await Promise.all([ ] = await Promise.all([
loadManifestWithRetries( loadManifestWithRetries<BuildManifest>(join(distDir, BUILD_MANIFEST)),
join(distDir, BUILD_MANIFEST) loadManifestWithRetries<ReactLoadableManifest>(
) as Promise<BuildManifest>,
loadManifestWithRetries(
join(distDir, REACT_LOADABLE_MANIFEST) join(distDir, REACT_LOADABLE_MANIFEST)
) as Promise<ReactLoadableManifest>, ),
hasClientManifest hasClientManifest
? loadClientReferenceManifest( ? loadClientReferenceManifest(
join( join(
...@@ -167,9 +166,9 @@ async function loadComponentsImpl<N = any>({ ...@@ -167,9 +166,9 @@ async function loadComponentsImpl<N = any>({
) )
: undefined, : undefined,
isAppPath isAppPath
? (loadManifestWithRetries( ? loadManifestWithRetries<ActionManifest>(
join(distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json') join(distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json')
).catch(() => null) as Promise<ActionManifest | null>) ).catch(() => null)
: null, : null,
]) ])
......
import { loadManifest } from './load-manifest'
import { readFileSync } from 'fs'
jest.mock('fs')
describe('loadManifest', () => {
const cache = new Map<string, unknown>()
afterEach(() => {
jest.resetAllMocks()
cache.clear()
})
it('should load the manifest from the file system when not cached', () => {
const mockManifest = { key: 'value' }
;(readFileSync as jest.Mock).mockReturnValue(JSON.stringify(mockManifest))
let result = loadManifest('path/to/manifest', false)
expect(result).toEqual(mockManifest)
expect(readFileSync).toHaveBeenCalledTimes(1)
expect(readFileSync).toHaveBeenCalledWith('path/to/manifest', 'utf8')
expect(cache.has('path/to/manifest')).toBe(false)
result = loadManifest('path/to/manifest', false)
expect(result).toEqual(mockManifest)
expect(readFileSync).toHaveBeenCalledTimes(2)
expect(readFileSync).toHaveBeenCalledWith('path/to/manifest', 'utf8')
expect(cache.has('path/to/manifest')).toBe(false)
})
it('should return the cached manifest when available', () => {
const mockManifest = { key: 'value' }
cache.set('path/to/manifest', mockManifest)
let result = loadManifest('path/to/manifest', true, cache)
expect(result).toBe(mockManifest)
expect(readFileSync).not.toHaveBeenCalled()
result = loadManifest('path/to/manifest', true, cache)
expect(result).toBe(mockManifest)
expect(readFileSync).not.toHaveBeenCalled()
})
it('should cache the manifest when not already cached', () => {
const mockManifest = { key: 'value' }
;(readFileSync as jest.Mock).mockReturnValue(JSON.stringify(mockManifest))
const result = loadManifest('path/to/manifest', true, cache)
expect(result).toEqual(mockManifest)
expect(cache.get('path/to/manifest')).toEqual(mockManifest)
expect(readFileSync).toHaveBeenCalledWith('path/to/manifest', 'utf8')
})
it('should throw an error when the manifest file cannot be read', () => {
;(readFileSync as jest.Mock).mockImplementation(() => {
throw new Error('File not found')
})
expect(() => loadManifest('path/to/manifest', false)).toThrow(
'File not found'
)
})
it('should freeze the manifest when caching', () => {
const mockManifest = { key: 'value', nested: { key: 'value' } }
;(readFileSync as jest.Mock).mockReturnValue(JSON.stringify(mockManifest))
const result = loadManifest(
'path/to/manifest',
true,
cache
) as typeof mockManifest
expect(Object.isFrozen(result)).toBe(true)
expect(Object.isFrozen(result.nested)).toBe(true)
const result2 = loadManifest('path/to/manifest', true, cache)
expect(Object.isFrozen(result2)).toBe(true)
expect(result).toBe(result2)
})
})
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import { runInNewContext } from 'vm' import { runInNewContext } from 'vm'
import { deepFreeze } from '../shared/lib/deep-freeze'
const cache = new Map<string, unknown>() const sharedCache = new Map<string, unknown>()
export function loadManifest( /**
* Load a manifest file from the file system. Optionally cache the manifest in
* memory to avoid reading the file multiple times using the provided cache or
* defaulting to a shared module cache. The manifest is frozen to prevent
* modifications if it is cached.
*
* @param path the path to the manifest file
* @param shouldCache whether to cache the manifest in memory
* @param cache the cache to use for storing the manifest
* @returns the manifest object
*/
export function loadManifest<T extends object>(
path: string,
shouldCache: false
): T
export function loadManifest<T extends object>(
path: string,
shouldCache?: boolean,
cache?: Map<string, unknown>
): DeepReadonly<T>
export function loadManifest<T extends object>(
path: string,
shouldCache?: true,
cache?: Map<string, unknown>
): DeepReadonly<T>
export function loadManifest<T extends object>(
path: string, path: string,
shouldCache: boolean = true shouldCache: boolean = true,
): unknown { cache = sharedCache
): T {
const cached = shouldCache && cache.get(path) const cached = shouldCache && cache.get(path)
if (cached) { if (cached) {
return cached return cached as T
} }
const manifest = JSON.parse(readFileSync(path, 'utf8')) let manifest = JSON.parse(readFileSync(path, 'utf8'))
// Freeze the manifest so it cannot be modified if we're caching it.
if (shouldCache) {
manifest = deepFreeze(manifest)
}
if (shouldCache) { if (shouldCache) {
cache.set(path, manifest) cache.set(path, manifest)
...@@ -22,14 +55,28 @@ export function loadManifest( ...@@ -22,14 +55,28 @@ export function loadManifest(
return manifest return manifest
} }
export function evalManifest( export function evalManifest<T extends object>(
path: string, path: string,
shouldCache: boolean = true shouldCache: false
): unknown { ): T
export function evalManifest<T extends object>(
path: string,
shouldCache?: boolean,
cache?: Map<string, unknown>
): DeepReadonly<T>
export function evalManifest<T extends object>(
path: string,
shouldCache?: true,
cache?: Map<string, unknown>
): DeepReadonly<T>
export function evalManifest<T extends object>(
path: string,
shouldCache: boolean = true,
cache = sharedCache
): T {
const cached = shouldCache && cache.get(path) const cached = shouldCache && cache.get(path)
if (cached) { if (cached) {
return cached return cached as T
} }
const content = readFileSync(path, 'utf8') const content = readFileSync(path, 'utf8')
...@@ -37,16 +84,21 @@ export function evalManifest( ...@@ -37,16 +84,21 @@ export function evalManifest(
throw new Error('Manifest file is empty') throw new Error('Manifest file is empty')
} }
const contextObject = {} let contextObject = {}
runInNewContext(content, contextObject) runInNewContext(content, contextObject)
// Freeze the context object so it cannot be modified if we're caching it.
if (shouldCache) {
contextObject = deepFreeze(contextObject)
}
if (shouldCache) { if (shouldCache) {
cache.set(path, contextObject) cache.set(path, contextObject)
} }
return contextObject return contextObject as T
} }
export function clearManifestCache(path: string): boolean { export function clearManifestCache(path: string, cache = sharedCache): boolean {
return cache.delete(path) return cache.delete(path)
} }
...@@ -1773,11 +1773,11 @@ export default class NextNodeServer extends BaseServer { ...@@ -1773,11 +1773,11 @@ export default class NextNodeServer extends BaseServer {
return this._cachedPreviewManifest return this._cachedPreviewManifest
} }
const manifest = loadManifest( this._cachedPreviewManifest = loadManifest(
join(this.distDir, PRERENDER_MANIFEST) join(this.distDir, PRERENDER_MANIFEST)
) as PrerenderManifest ) as PrerenderManifest
return (this._cachedPreviewManifest = manifest) return this._cachedPreviewManifest
} }
protected getRoutesManifest(): NormalizedRouteManifest | undefined { protected getRoutesManifest(): NormalizedRouteManifest | undefined {
......
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
} from './api-utils' } from './api-utils'
import { getCookieParser } from './api-utils/get-cookie-parser' import { getCookieParser } from './api-utils/get-cookie-parser'
import type { FontManifest, FontConfig } from './font-utils' import type { FontManifest, FontConfig } from './font-utils'
import type { LoadComponentsReturnType, ManifestItem } from './load-components' import type { LoadComponentsReturnType } from './load-components'
import type { import type {
GetServerSideProps, GetServerSideProps,
GetStaticProps, GetStaticProps,
...@@ -106,6 +106,7 @@ import { RenderSpan } from './lib/trace/constants' ...@@ -106,6 +106,7 @@ import { RenderSpan } from './lib/trace/constants'
import { ReflectAdapter } from './web/spec-extension/adapters/reflect' import { ReflectAdapter } from './web/spec-extension/adapters/reflect'
import { formatRevalidate } from './lib/revalidate' import { formatRevalidate } from './lib/revalidate'
import { getErrorSource } from '../shared/lib/error-source' import { getErrorSource } from '../shared/lib/error-source'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
let tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData let tryGetPreviewData: typeof import('./api-utils/node/try-get-preview-data').tryGetPreviewData
let warn: typeof import('../build/output/log').warn let warn: typeof import('../build/output/log').warn
...@@ -255,15 +256,15 @@ export type RenderOptsPartial = { ...@@ -255,15 +256,15 @@ export type RenderOptsPartial = {
unstable_runtimeJS?: false unstable_runtimeJS?: false
unstable_JsPreload?: false unstable_JsPreload?: false
optimizeFonts: FontConfig optimizeFonts: FontConfig
fontManifest?: FontManifest fontManifest?: DeepReadonly<FontManifest>
optimizeCss: any optimizeCss: any
nextConfigOutput?: 'standalone' | 'export' nextConfigOutput?: 'standalone' | 'export'
nextScriptWorkers: any nextScriptWorkers: any
assetQueryString?: string assetQueryString?: string
resolvedUrl?: string resolvedUrl?: string
resolvedAsPath?: string resolvedAsPath?: string
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
nextFontManifest?: NextFontManifest nextFontManifest?: DeepReadonly<NextFontManifest>
distDir?: string distDir?: string
locale?: string locale?: string
locales?: string[] locales?: string[]
...@@ -1436,7 +1437,7 @@ export async function renderToHTMLImpl( ...@@ -1436,7 +1437,7 @@ export async function renderToHTMLImpl(
const dynamicImports = new Set<string>() const dynamicImports = new Set<string>()
for (const mod of reactLoadableModules) { for (const mod of reactLoadableModules) {
const manifestItem: ManifestItem = reactLoadableManifest[mod] const manifestItem = reactLoadableManifest[mod]
if (manifestItem) { if (manifestItem) {
dynamicImportsIds.add(manifestItem.id) dynamicImportsIds.add(manifestItem.id)
......
...@@ -33,6 +33,7 @@ import type { PAGE_TYPES } from '../lib/page-types' ...@@ -33,6 +33,7 @@ import type { PAGE_TYPES } from '../lib/page-types'
import type { Rewrite } from '../lib/load-custom-routes' import type { Rewrite } from '../lib/load-custom-routes'
import { buildCustomRoute } from '../lib/build-custom-route' import { buildCustomRoute } from '../lib/build-custom-route'
import { UNDERSCORE_NOT_FOUND_ROUTE } from '../api/constants' import { UNDERSCORE_NOT_FOUND_ROUTE } from '../api/constants'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
interface WebServerOptions extends Options { interface WebServerOptions extends Options {
webServerConfig: { webServerConfig: {
...@@ -48,7 +49,7 @@ interface WebServerOptions extends Options { ...@@ -48,7 +49,7 @@ interface WebServerOptions extends Options {
| typeof import('./app-render/app-render').renderToHTMLOrFlight | typeof import('./app-render/app-render').renderToHTMLOrFlight
| undefined | undefined
incrementalCacheHandler?: any incrementalCacheHandler?: any
prerenderManifest: PrerenderManifest | undefined prerenderManifest: DeepReadonly<PrerenderManifest> | undefined
interceptionRouteRewrites?: Rewrite[] interceptionRouteRewrites?: Rewrite[]
} }
} }
......
import { deepFreeze } from './deep-freeze'
describe('freeze', () => {
it('should freeze an object', () => {
const obj = { a: 1, b: 2 }
deepFreeze(obj)
expect(Object.isFrozen(obj)).toBe(true)
})
it('should freeze an array', () => {
const arr = [1, 2, 3]
deepFreeze(arr)
expect(Object.isFrozen(arr)).toBe(true)
})
it('should freeze nested objects', () => {
const obj = { a: { b: 2 }, c: 3 }
deepFreeze(obj)
expect(Object.isFrozen(obj)).toBe(true)
expect(Object.isFrozen(obj.a)).toBe(true)
})
it('should freeze nested arrays', () => {
const arr = [
[1, 2],
[3, 4],
]
deepFreeze(arr)
expect(Object.isFrozen(arr)).toBe(true)
expect(Object.isFrozen(arr[0])).toBe(true)
expect(Object.isFrozen(arr[1])).toBe(true)
})
it('should freeze nested objects and arrays', () => {
const obj = { a: [1, 2], b: { c: 3 } }
deepFreeze(obj)
expect(Object.isFrozen(obj)).toBe(true)
expect(Object.isFrozen(obj.a)).toBe(true)
expect(Object.isFrozen(obj.b)).toBe(true)
})
})
import type { DeepReadonly } from './deep-readonly'
/**
* Recursively freezes an object and all of its properties. This prevents the
* object from being modified at runtime. When the JS runtime is running in
* strict mode, any attempts to modify a frozen object will throw an error.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
* @param obj The object to freeze.
*/
export function deepFreeze<T extends object>(obj: T): DeepReadonly<T> {
// If the object is already frozen, there's no need to freeze it again.
if (Object.isFrozen(obj)) return obj as DeepReadonly<T>
// An array is an object, but we also want to freeze each element in the array
// as well.
if (Array.isArray(obj)) {
for (const item of obj) {
if (!item || typeof item !== 'object') continue
deepFreeze(item)
}
return Object.freeze(obj) as DeepReadonly<T>
}
for (const value of Object.values(obj)) {
if (!value || typeof value !== 'object') continue
deepFreeze(value)
}
return Object.freeze(obj) as DeepReadonly<T>
}
/**
* A type that represents a deeply readonly object. This is similar to
* TypeScript's `Readonly` type, but it recursively applies the `readonly`
* modifier to all properties of an object and all elements of arrays.
*/
export type DeepReadonly<T> = T extends (infer R)[]
? ReadonlyArray<DeepReadonly<R>>
: T extends object
? {
readonly [K in keyof T]: DeepReadonly<T[K]>
}
: T
...@@ -3,6 +3,7 @@ import type { ServerRuntime } from 'next/types' ...@@ -3,6 +3,7 @@ import type { ServerRuntime } from 'next/types'
import type { NEXT_DATA } from './utils' import type { NEXT_DATA } from './utils'
import type { FontConfig } from '../../server/font-utils' import type { FontConfig } from '../../server/font-utils'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin' import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'
import type { DeepReadonly } from './deep-readonly'
import { createContext, useContext } from 'react' import { createContext, useContext } from 'react'
...@@ -45,7 +46,7 @@ export type HtmlProps = { ...@@ -45,7 +46,7 @@ export type HtmlProps = {
runtime?: ServerRuntime runtime?: ServerRuntime
hasConcurrentFeatures?: boolean hasConcurrentFeatures?: boolean
largePageDataBytes?: number largePageDataBytes?: number
nextFontManifest?: NextFontManifest nextFontManifest?: DeepReadonly<NextFontManifest>
} }
export const HtmlContext = createContext<HtmlProps | undefined>(undefined) export const HtmlContext = createContext<HtmlProps | undefined>(undefined)
......
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