refactor: cleans up the logic to de-duplicate some checks

parent 1f6defd4
import { Span } from '../trace'
import type { NextConfigComplete } from '../server/config-shared'
import type { PageInfoRegistry } from './page-info'
import {
TRACE_IGNORES,
......@@ -14,7 +15,6 @@ import {
import path from 'path'
import fs from 'fs/promises'
import type { PageInfo } from './utils'
import { loadBindings } from './swc'
import { nonNullable } from '../lib/non-nullable'
import * as ciEnvironment from '../telemetry/ci-info'
......@@ -67,7 +67,7 @@ export async function collectBuildTraces({
dir,
config,
distDir,
pageInfos,
pageInfoRegistry,
staticPages,
nextBuildSpan = new Span({ name: 'build' }),
hasSsrAmpPages,
......@@ -79,7 +79,7 @@ export async function collectBuildTraces({
staticPages: string[]
hasSsrAmpPages: boolean
outputFileTracingRoot: string
pageInfos: [string, PageInfo][]
pageInfoRegistry: PageInfoRegistry | undefined
nextBuildSpan?: Span
config: NextConfigComplete
buildTraceContext?: BuildTraceContext
......@@ -638,10 +638,8 @@ export async function collectBuildTraces({
}
// edge routes have no trace files
const [, pageInfo] = pageInfos.find((item) => item[0] === route) || []
if (pageInfo?.runtime === 'edge') {
return
}
const pageInfo = pageInfoRegistry?.get(route)
if (pageInfo?.runtime === 'edge') return
const combinedIncludes = new Set<string>()
const combinedExcludes = new Set<string>()
......
This diff is collapsed.
import type { ServerRuntime } from '../../types'
export interface PageInfo {
isHybridAmp?: boolean
size: number
totalSize: number
isStatic: boolean
isSSG: boolean
isPPR: boolean
ssgPageRoutes: string[] | null
initialRevalidateSeconds: number | false
pageDuration: number | undefined
ssgPageDurations: number[] | undefined
runtime: ServerRuntime
hasEmptyPrelude?: boolean
hasPostponed?: boolean
isDynamicAppRoute?: boolean
}
/**
* This class is used to store information about pages that is used for the
* build output.
*/
export class PageInfoRegistry extends Map<string, PageInfo> {
/**
* Updates the page info for a given page. If the page info doesn't exist,
* then it will throw an error.
*
* @param page the page to update
* @param update the update to apply
* @returns the updated page info
*/
public patch(page: string, update: Partial<PageInfo>): PageInfo {
const pageInfo = this.get(page, true)
this.set(page, { ...pageInfo, ...update })
return pageInfo
}
/**
* Gets the page info for a given page. If the page info doesn't exist, then
* it will throw an error if `errorIfMissing` is true.
*
* @param page the page to get
* @param throwIfUndefined whether to throw an error if the page info doesn't exist
*/
public get(page: string, throwIfUndefined: true): PageInfo
public get(page: string, throwIfUndefined?: boolean): PageInfo | undefined
public get(page: string, throwIfUndefined?: boolean): PageInfo | undefined {
const pageInfo = super.get(page)
if (!pageInfo && throwIfUndefined) {
throw new Error(`Invariant: Expected page "${page}" to exist`)
}
return pageInfo
}
}
This diff is collapsed.
export function interopDefault(mod: any) {
return mod.default || mod
export function interopDefault<T = any>(mod: unknown): T | undefined {
// If the module is falsy (like `null`), just return undefined.
if (!mod) return undefined
// If the module has a default export (named 'default'), return that.
if (
(typeof mod === 'object' || typeof mod === 'function') &&
'default' in mod &&
mod.default
) {
return mod.default as T
}
return mod as T
}
......@@ -703,7 +703,7 @@ export default class DevServer extends Server {
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize,
ppr: this.nextConfig.experimental.ppr === true,
nextConfigPPREnabled: this.nextConfig.experimental.ppr === true,
})
return pathsResult
} finally {
......
......@@ -38,7 +38,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize,
requestHeaders,
incrementalCacheHandlerPath,
ppr,
nextConfigPPREnabled,
}: {
dir: string
distDir: string
......@@ -54,7 +54,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
incrementalCacheHandlerPath?: string
ppr: boolean
nextConfigPPREnabled: boolean
}): Promise<{
paths?: string[]
encodedPaths?: string[]
......@@ -109,7 +109,7 @@ export async function loadStaticPaths({
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize,
ppr,
nextConfigPPREnabled,
ComponentMod: components.ComponentMod,
})
}
......
......@@ -45,15 +45,15 @@ export interface LoadableManifest {
}
export type LoadComponentsReturnType<NextModule = any> = {
Component: NextComponentType
Component?: NextComponentType
pageConfig: PageConfig
buildManifest: BuildManifest
subresourceIntegrityManifest?: Record<string, string>
reactLoadableManifest: ReactLoadableManifest
clientReferenceManifest?: ClientReferenceManifest
serverActionsManifest?: any
Document: DocumentType
App: AppType
Document?: DocumentType
App?: AppType
getStaticProps?: GetStaticProps
getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps
......@@ -108,14 +108,18 @@ async function loadComponentsImpl<N = any>({
page: string
isAppPath: boolean
}): Promise<LoadComponentsReturnType<N>> {
let DocumentMod = {}
let AppMod = {}
let Document: DocumentType | undefined
let App: AppType | undefined
if (!isAppPath) {
;[DocumentMod, AppMod] = await Promise.all([
const [DocumentMod, AppMod] = await Promise.all([
Promise.resolve().then(() => requirePage('/_document', distDir, false)),
Promise.resolve().then(() => requirePage('/_app', distDir, false)),
])
Document = interopDefault(DocumentMod)
App = interopDefault(AppMod)
}
const ComponentMod = await Promise.resolve().then(() =>
requirePage(page, distDir, isAppPath)
)
......@@ -153,9 +157,7 @@ async function loadComponentsImpl<N = any>({
: null,
])
const Component = interopDefault(ComponentMod)
const Document = interopDefault(DocumentMod)
const App = interopDefault(AppMod)
const Component = interopDefault<NextComponentType>(ComponentMod)
const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =
ComponentMod
......
......@@ -452,15 +452,17 @@ export async function renderToHTMLImpl(
runtime: globalRuntime,
isExperimentalCompile,
} = renderOpts
if (!renderOpts.Component) {
throw new Error('Invariant: Cannot render without a Component')
}
const { App } = extra
let { Document } = extra
const assetQueryString = metadata.assetQueryString
let Document = extra.Document
let Component: React.ComponentType<{}> | ((props: any) => JSX.Element) =
renderOpts.Component
const OriginComponent = Component
const { Component } = renderOpts
let serverComponentsInlinedTransformStream: TransformStream<
Uint8Array,
......@@ -772,7 +774,7 @@ export async function renderToHTMLImpl(
AppTree: (props: any) => {
return (
<AppContainerWithIsomorphicFiberStructure>
{renderPageTree(App, OriginComponent, { ...props, router })}
{renderPageTree(App, Component, { ...props, router })}
</AppContainerWithIsomorphicFiberStructure>
)
},
......@@ -1521,7 +1523,7 @@ export async function renderToHTMLImpl(
)
if (process.env.NODE_ENV !== 'production') {
const nonRenderedComponents = []
const nonRenderedComponents: string[] = []
const expectedDocComponents = ['Main', 'Head', 'NextScript', 'Html']
for (const comp of expectedDocComponents) {
......@@ -1587,5 +1589,18 @@ export const renderToHTML: PagesRender = (
query,
renderOpts
) => {
return renderToHTMLImpl(req, res, pathname, query, renderOpts, renderOpts)
if (!renderOpts.App) {
throw new Error('Invariant: missing App in renderOpts')
}
if (!renderOpts.Document) {
throw new Error('Invariant: missing Document in renderOpts')
}
const extra = {
App: renderOpts.App,
Document: renderOpts.Document,
}
return renderToHTMLImpl(req, res, pathname, query, renderOpts, extra)
}
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