Unverified Commit 8703c55f authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

export config into functions config manifest (#51700)

remaining:
- add tests

caveat: this only works at the route level, we won't inherit from the layout or anything. I think that's fine
Co-authored-by: 's avatarFlorentin / 珞辰 <8146736+ecklf@users.noreply.github.com>
parent 484bdebc
...@@ -19,6 +19,10 @@ import { isEdgeRuntime } from '../../lib/is-edge-runtime' ...@@ -19,6 +19,10 @@ import { isEdgeRuntime } from '../../lib/is-edge-runtime'
import { RSC_MODULE_TYPES } from '../../shared/lib/constants' import { RSC_MODULE_TYPES } from '../../shared/lib/constants'
import type { RSCMeta } from '../webpack/loaders/get-module-build-info' import type { RSCMeta } from '../webpack/loaders/get-module-build-info'
// TODO: migrate preferredRegion here
// Don't forget to update the next-types-plugin file as well
const AUTHORIZED_EXTRA_PROPS = ['maxDuration']
export interface MiddlewareConfig { export interface MiddlewareConfig {
matchers?: MiddlewareMatcher[] matchers?: MiddlewareMatcher[]
unstable_allowDynamicGlobs?: string[] unstable_allowDynamicGlobs?: string[]
...@@ -41,6 +45,7 @@ export interface PageStaticInfo { ...@@ -41,6 +45,7 @@ export interface PageStaticInfo {
rsc?: RSCModuleType rsc?: RSCModuleType
middleware?: MiddlewareConfig middleware?: MiddlewareConfig
amp?: boolean | 'hybrid' amp?: boolean | 'hybrid'
extraConfig?: Record<string, any>
} }
const CLIENT_MODULE_LABEL = const CLIENT_MODULE_LABEL =
...@@ -86,6 +91,7 @@ function checkExports(swcAST: any): { ...@@ -86,6 +91,7 @@ function checkExports(swcAST: any): {
preferredRegion?: string | string[] preferredRegion?: string | string[]
generateImageMetadata?: boolean generateImageMetadata?: boolean
generateSitemaps?: boolean generateSitemaps?: boolean
extraProperties?: Set<string>
} { } {
const exportsSet = new Set<string>([ const exportsSet = new Set<string>([
'getStaticProps', 'getStaticProps',
...@@ -101,6 +107,7 @@ function checkExports(swcAST: any): { ...@@ -101,6 +107,7 @@ function checkExports(swcAST: any): {
let ssg: boolean = false let ssg: boolean = false
let generateImageMetadata: boolean = false let generateImageMetadata: boolean = false
let generateSitemaps: boolean = false let generateSitemaps: boolean = false
let extraProperties = new Set<string>()
for (const node of swcAST.body) { for (const node of swcAST.body) {
if ( if (
...@@ -110,9 +117,7 @@ function checkExports(swcAST: any): { ...@@ -110,9 +117,7 @@ function checkExports(swcAST: any): {
for (const declaration of node.declaration?.declarations) { for (const declaration of node.declaration?.declarations) {
if (declaration.id.value === 'runtime') { if (declaration.id.value === 'runtime') {
runtime = declaration.init.value runtime = declaration.init.value
} } else if (declaration.id.value === 'preferredRegion') {
if (declaration.id.value === 'preferredRegion') {
if (declaration.init.type === 'ArrayExpression') { if (declaration.init.type === 'ArrayExpression') {
const elements: string[] = [] const elements: string[] = []
for (const element of declaration.init.elements) { for (const element of declaration.init.elements) {
...@@ -126,6 +131,8 @@ function checkExports(swcAST: any): { ...@@ -126,6 +131,8 @@ function checkExports(swcAST: any): {
} else { } else {
preferredRegion = declaration.init.value preferredRegion = declaration.init.value
} }
} else {
extraProperties.add(declaration.id.value)
} }
} }
} }
...@@ -181,6 +188,7 @@ function checkExports(swcAST: any): { ...@@ -181,6 +188,7 @@ function checkExports(swcAST: any): {
preferredRegion, preferredRegion,
generateImageMetadata, generateImageMetadata,
generateSitemaps, generateSitemaps,
extraProperties,
} }
} catch (err) {} } catch (err) {}
} }
...@@ -192,6 +200,7 @@ function checkExports(swcAST: any): { ...@@ -192,6 +200,7 @@ function checkExports(swcAST: any): {
preferredRegion: undefined, preferredRegion: undefined,
generateImageMetadata: false, generateImageMetadata: false,
generateSitemaps: false, generateSitemaps: false,
extraProperties: undefined,
} }
} }
...@@ -393,12 +402,13 @@ export async function getPageStaticInfo(params: { ...@@ -393,12 +402,13 @@ export async function getPageStaticInfo(params: {
const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || '' const fileContent = (await tryToReadFile(pageFilePath, !isDev)) || ''
if ( if (
/runtime|preferredRegion|getStaticProps|getServerSideProps|export const config/.test( /runtime|preferredRegion|getStaticProps|getServerSideProps|export const/.test(
fileContent fileContent
) )
) { ) {
const swcAST = await parseModule(pageFilePath, fileContent) const swcAST = await parseModule(pageFilePath, fileContent)
const { ssg, ssr, runtime, preferredRegion } = checkExports(swcAST) const { ssg, ssr, runtime, preferredRegion, extraProperties } =
checkExports(swcAST)
const rsc = getRSCModuleInformation(fileContent).type const rsc = getRSCModuleInformation(fileContent).type
// default / failsafe value for config // default / failsafe value for config
...@@ -411,6 +421,24 @@ export async function getPageStaticInfo(params: { ...@@ -411,6 +421,24 @@ export async function getPageStaticInfo(params: {
} }
// `export config` doesn't exist, or other unknown error throw by swc, silence them // `export config` doesn't exist, or other unknown error throw by swc, silence them
} }
let extraConfig: Record<string, any> | undefined
if (extraProperties) {
extraConfig = {}
for (const prop of extraProperties) {
if (!AUTHORIZED_EXTRA_PROPS.includes(prop)) continue
try {
extraConfig[prop] = extractExportedConstValue(swcAST, prop)
} catch (e) {
if (e instanceof UnsupportedValueError) {
warnAboutUnsupportedValue(pageFilePath, page, e)
}
}
}
}
if (pageType === 'app') { if (pageType === 'app') {
if (config) { if (config) {
const message = `\`export const config\` in ${pageFilePath} is deprecated. Please change \`runtime\` property to segment export config. See https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config` const message = `\`export const config\` in ${pageFilePath} is deprecated. Please change \`runtime\` property to segment export config. See https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config`
...@@ -493,6 +521,7 @@ export async function getPageStaticInfo(params: { ...@@ -493,6 +521,7 @@ export async function getPageStaticInfo(params: {
...(middlewareConfig && { middleware: middlewareConfig }), ...(middlewareConfig && { middleware: middlewareConfig }),
...(resolvedRuntime && { runtime: resolvedRuntime }), ...(resolvedRuntime && { runtime: resolvedRuntime }),
preferredRegion, preferredRegion,
extraConfig,
} }
} }
......
...@@ -70,6 +70,7 @@ import { ...@@ -70,6 +70,7 @@ import {
TURBO_TRACE_DEFAULT_MEMORY_LIMIT, TURBO_TRACE_DEFAULT_MEMORY_LIMIT,
TRACE_OUTPUT_VERSION, TRACE_OUTPUT_VERSION,
SERVER_REFERENCE_MANIFEST, SERVER_REFERENCE_MANIFEST,
FUNCTIONS_CONFIG_MANIFEST,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils' import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
import { __ApiPreviewProps } from '../server/api-utils' import { __ApiPreviewProps } from '../server/api-utils'
...@@ -1241,6 +1242,8 @@ export default async function build( ...@@ -1241,6 +1242,8 @@ export default async function build(
const analysisBegin = process.hrtime() const analysisBegin = process.hrtime()
const staticCheckSpan = nextBuildSpan.traceChild('static-check') const staticCheckSpan = nextBuildSpan.traceChild('static-check')
const functionsConfigManifest = {} as Record<string, Record<string, any>>
const { const {
customAppGetInitialProps, customAppGetInitialProps,
namedExports, namedExports,
...@@ -1431,6 +1434,10 @@ export default async function build( ...@@ -1431,6 +1434,10 @@ export default async function build(
}) })
: undefined : undefined
if (staticInfo?.extraConfig) {
functionsConfigManifest[page] = staticInfo.extraConfig
}
const pageRuntime = middlewareManifest.functions[ const pageRuntime = middlewareManifest.functions[
originalAppPath || page originalAppPath || page
] ]
...@@ -1741,6 +1748,13 @@ export default async function build( ...@@ -1741,6 +1748,13 @@ export default async function build(
) )
} }
if (Object.keys(functionsConfigManifest).length > 0) {
await promises.writeFile(
path.join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST),
JSON.stringify(functionsConfigManifest, null, 2)
)
}
const nextServerTraceOutput = path.join( const nextServerTraceOutput = path.join(
distDir, distDir,
'next-server.js.nft.json' 'next-server.js.nft.json'
......
...@@ -68,6 +68,7 @@ checkFields<Diff<{ ...@@ -68,6 +68,7 @@ checkFields<Diff<{
fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache' fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache'
preferredRegion?: 'auto' | 'global' | 'home' | string | string[] preferredRegion?: 'auto' | 'global' | 'home' | string | string[]
runtime?: 'nodejs' | 'experimental-edge' | 'edge' runtime?: 'nodejs' | 'experimental-edge' | 'edge'
maxDuration?: number
${ ${
options.type === 'route' options.type === 'route'
? '' ? ''
......
...@@ -31,6 +31,7 @@ export const APP_PATHS_MANIFEST = 'app-paths-manifest.json' ...@@ -31,6 +31,7 @@ export const APP_PATHS_MANIFEST = 'app-paths-manifest.json'
export const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json' export const APP_PATH_ROUTES_MANIFEST = 'app-path-routes-manifest.json'
export const BUILD_MANIFEST = 'build-manifest.json' export const BUILD_MANIFEST = 'build-manifest.json'
export const APP_BUILD_MANIFEST = 'app-build-manifest.json' export const APP_BUILD_MANIFEST = 'app-build-manifest.json'
export const FUNCTIONS_CONFIG_MANIFEST = 'functions-config-manifest.json'
export const SUBRESOURCE_INTEGRITY_MANIFEST = 'subresource-integrity-manifest' export const SUBRESOURCE_INTEGRITY_MANIFEST = 'subresource-integrity-manifest'
export const NEXT_FONT_MANIFEST = 'next-font-manifest' export const NEXT_FONT_MANIFEST = 'next-font-manifest'
export const EXPORT_MARKER = 'export-marker.json' export const EXPORT_MARKER = 'export-marker.json'
......
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ hello: 'app-edge' })
}
export const runtime = 'edge'
export const maxDuration = 2
import { NextResponse } from 'next/server'
export async function GET() {
return NextResponse.json({ hello: 'app' })
}
export const maxDuration = 1
export default function Page() {
return <p>app-edge-ssr</p>
}
export const runtime = 'edge'
export const maxDuration = 4
export default function Page() {
return <p>app-ssr</p>
}
export const maxDuration = 3
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { NextApiResponse, NextApiRequest } from 'next'
export default function handler(
_req: NextApiRequest,
res: NextApiResponse<{ hello: string }>
) {
return res.status(200).json({ hello: 'world' })
}
export const maxDuration = 1
export default function Page({ data }) {
;<p>hello {data}</p>
}
export const maxDuration = 3
export async function getServerSideProps() {
return { props: { data: 'world' } }
}
export default function Page() {
;<p>hello world</p>
}
export const maxDuration = 2
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'with-exported-function-config',
{
files: __dirname,
},
({ next, isNextStart }) => {
it('should have correct values in function config manifest', async () => {
if (isNextStart) {
const functionsConfigManifest = JSON.parse(
await next.readFile('.next/server/functions-config-manifest.json')
)
expect(functionsConfigManifest).toMatchInlineSnapshot(`
Object {
"/api/page-route": Object {
"maxDuration": 1,
},
"/app-route": Object {
"maxDuration": 1,
},
"/app-route-edge": Object {
"maxDuration": 2,
},
"/app-ssr": Object {
"maxDuration": 3,
},
"/app-ssr-edge": Object {
"maxDuration": 4,
},
"/page": Object {
"maxDuration": 2,
},
"/page-ssr": Object {
"maxDuration": 3,
},
}
`)
}
})
}
)
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