Unverified Commit ac86a613 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Refactor extractExportedConstValue to return { value } | null instead of throwing (#90510)

## Summary

Refactors `extractExportedConstValue` and the internal `extractValue` function to use return values instead of exception-based control flow, improving performance during build analysis.

### Commit 1: Refactor `extractExportedConstValue`
- Returns `{ value: any } | null` instead of throwing `NoSuchDeclarationError`
- `null` when the exported const declaration is not found, `{ value }` when found
- Removes `NoSuchDeclarationError` class

### Commit 2: Refactor `extractValue`
- Returns `ExtractValueResult` (`{ value: any } | { unsupported: string; path?: string }`) instead of throwing `UnsupportedValueError`
- Extracts path-formatting logic from `UnsupportedValueError` constructor into a standalone `formatCodePath` helper
- All 6 throw sites become return statements; 3 recursive call sites propagate unsupported results
- Removes `UnsupportedValueError` class entirely
- Removes all try/catch blocks from the 4 callsites in `get-page-static-info.ts`
- Updates `warnAboutUnsupportedValue` to accept the result type directly

## Motivation

Both `extractExportedConstValue` and `extractValue` used throw/catch for expected control flow — a missing declaration and unsupported AST node types are normal cases during build analysis, not exceptional errors. Every page/route processed during build hits these functions multiple times. Constructing `Error` objects (which capture stack traces) and unwinding the stack is expensive in V8. Returning discriminated result types avoids this overhead entirely.

## Test Plan

- Existing unit tests pass (`test/unit/parse-page-static-info.test.ts` — 5/5)
- No behavioral change: callsites produce identical warnings/errors for unsupported values and silently skip missing declarations, same as before
parent 01d75f69
...@@ -16,8 +16,6 @@ import type { ...@@ -16,8 +16,6 @@ import type {
VariableDeclaration, VariableDeclaration,
} from '@swc/core' } from '@swc/core'
export class NoSuchDeclarationError extends Error {}
function isExportDeclaration(node: Node): node is ExportDeclaration { function isExportDeclaration(node: Node): node is ExportDeclaration {
return node.type === 'ExportDeclaration' return node.type === 'ExportDeclaration'
} }
...@@ -70,60 +68,52 @@ function isTsSatisfiesExpression(node: Node): node is TsSatisfiesExpression { ...@@ -70,60 +68,52 @@ function isTsSatisfiesExpression(node: Node): node is TsSatisfiesExpression {
return node.type === 'TsSatisfiesExpression' return node.type === 'TsSatisfiesExpression'
} }
export class UnsupportedValueError extends Error { export type ExtractValueResult =
/** @example `config.runtime[0].value` */ | { value: any }
path?: string | { unsupported: string; path?: string }
constructor(message: string, paths?: string[]) {
super(message)
// Generating "path" that looks like "config.runtime[0].value" /** Formats a path array like `["config", "runtime", "[0]", "value"]` → `"config.runtime[0].value"` */
let codePath: string | undefined function formatCodePath(paths?: string[]): string | undefined {
if (paths) { if (!paths) return undefined
codePath = '' let codePath = ''
for (const path of paths) { for (const path of paths) {
if (path[0] === '[') { if (path[0] === '[') {
// "array" + "[0]" // "array" + "[0]"
codePath += path codePath += path
} else { } else if (codePath === '') {
if (codePath === '') {
codePath = path codePath = path
} else { } else {
// "object" + ".key" // "object" + ".key"
codePath += `.${path}` codePath += `.${path}`
} }
} }
} return codePath
}
this.path = codePath
}
} }
function extractValue(node: Node, path?: string[]): any { function extractValue(node: Node, path?: string[]): ExtractValueResult {
if (isNullLiteral(node)) { if (isNullLiteral(node)) {
return null return { value: null }
} else if (isBooleanLiteral(node)) { } else if (isBooleanLiteral(node)) {
// e.g. true / false // e.g. true / false
return node.value return { value: node.value }
} else if (isStringLiteral(node)) { } else if (isStringLiteral(node)) {
// e.g. "abc" // e.g. "abc"
return node.value return { value: node.value }
} else if (isNumericLiteral(node)) { } else if (isNumericLiteral(node)) {
// e.g. 123 // e.g. 123
return node.value return { value: node.value }
} else if (isRegExpLiteral(node)) { } else if (isRegExpLiteral(node)) {
// e.g. /abc/i // e.g. /abc/i
return new RegExp(node.pattern, node.flags) return { value: new RegExp(node.pattern, node.flags) }
} else if (isIdentifier(node)) { } else if (isIdentifier(node)) {
switch (node.value) { switch (node.value) {
case 'undefined': case 'undefined':
return undefined return { value: undefined }
default: default:
throw new UnsupportedValueError( return {
`Unknown identifier "${node.value}"`, unsupported: `Unknown identifier "${node.value}"`,
path path: formatCodePath(path),
) }
} }
} else if (isArrayExpression(node)) { } else if (isArrayExpression(node)) {
// e.g. [1, 2, 3] // e.g. [1, 2, 3]
...@@ -133,30 +123,35 @@ function extractValue(node: Node, path?: string[]): any { ...@@ -133,30 +123,35 @@ function extractValue(node: Node, path?: string[]): any {
if (elem) { if (elem) {
if (elem.spread) { if (elem.spread) {
// e.g. [ ...a ] // e.g. [ ...a ]
throw new UnsupportedValueError( return {
'Unsupported spread operator in the Array Expression', unsupported: 'Unsupported spread operator in the Array Expression',
path path: formatCodePath(path),
) }
} }
arr.push(extractValue(elem.expression, path && [...path, `[${i}]`])) const result = extractValue(
elem.expression,
path && [...path, `[${i}]`]
)
if ('unsupported' in result) return result
arr.push(result.value)
} else { } else {
// e.g. [1, , 2] // e.g. [1, , 2]
// ^^ // ^^
arr.push(undefined) arr.push(undefined)
} }
} }
return arr return { value: arr }
} else if (isObjectExpression(node)) { } else if (isObjectExpression(node)) {
// e.g. { a: 1, b: 2 } // e.g. { a: 1, b: 2 }
const obj: any = {} const obj: any = {}
for (const prop of node.properties) { for (const prop of node.properties) {
if (!isKeyValueProperty(prop)) { if (!isKeyValueProperty(prop)) {
// e.g. { ...a } // e.g. { ...a }
throw new UnsupportedValueError( return {
'Unsupported spread operator in the Object Expression', unsupported: 'Unsupported spread operator in the Object Expression',
path path: formatCodePath(path),
) }
} }
let key let key
...@@ -167,24 +162,26 @@ function extractValue(node: Node, path?: string[]): any { ...@@ -167,24 +162,26 @@ function extractValue(node: Node, path?: string[]): any {
// e.g. { "a": 1, "b": 2 } // e.g. { "a": 1, "b": 2 }
key = prop.key.value key = prop.key.value
} else { } else {
throw new UnsupportedValueError( return {
`Unsupported key type "${prop.key.type}" in the Object Expression`, unsupported: `Unsupported key type "${prop.key.type}" in the Object Expression`,
path path: formatCodePath(path),
) }
} }
obj[key] = extractValue(prop.value, path && [...path, key]) const result = extractValue(prop.value, path && [...path, key])
if ('unsupported' in result) return result
obj[key] = result.value
} }
return obj return { value: obj }
} else if (isTemplateLiteral(node)) { } else if (isTemplateLiteral(node)) {
// e.g. `abc` // e.g. `abc`
if (node.expressions.length !== 0) { if (node.expressions.length !== 0) {
// TODO: should we add support for `${'e'}d${'g'}'e'`? // TODO: should we add support for `${'e'}d${'g'}'e'`?
throw new UnsupportedValueError( return {
'Unsupported template literal with expressions', unsupported: 'Unsupported template literal with expressions',
path path: formatCodePath(path),
) }
} }
// When TemplateLiteral has 0 expressions, the length of quasis is always 1. // When TemplateLiteral has 0 expressions, the length of quasis is always 1.
...@@ -198,21 +195,21 @@ function extractValue(node: Node, path?: string[]): any { ...@@ -198,21 +195,21 @@ function extractValue(node: Node, path?: string[]): any {
// https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw
const [{ cooked, raw }] = node.quasis const [{ cooked, raw }] = node.quasis
return cooked ?? raw return { value: cooked ?? raw }
} else if (isTsSatisfiesExpression(node)) { } else if (isTsSatisfiesExpression(node)) {
return extractValue(node.expression) return extractValue(node.expression)
} else { } else {
throw new UnsupportedValueError( return {
`Unsupported node type "${node.type}"`, unsupported: `Unsupported node type "${node.type}"`,
path path: formatCodePath(path),
) }
} }
} }
/** /**
* Extracts the value of an exported const variable named `exportedName` * Extracts the value of an exported const variable named `exportedName`
* (e.g. "export const config = { runtime: 'edge' }") from swc's AST. * (e.g. "export const config = { runtime: 'edge' }") from swc's AST.
* The value must be one of (or throws UnsupportedValueError): * The value must be one of (or returns unsupported):
* - string * - string
* - boolean * - boolean
* - number * - number
...@@ -221,12 +218,14 @@ function extractValue(node: Node, path?: string[]): any { ...@@ -221,12 +218,14 @@ function extractValue(node: Node, path?: string[]): any {
* - array containing values listed in this list * - array containing values listed in this list
* - object containing values listed in this list * - object containing values listed in this list
* *
* Throws NoSuchDeclarationError if the declaration is not found. * Returns null if the declaration is not found.
* Returns { unsupported, path? } if the value contains unsupported nodes.
*/ */
export function extractExportedConstValue( export function extractExportedConstValue(
module: Module, module: Module | null,
exportedName: string exportedName: string
): any { ): ExtractValueResult | null {
if (!module) return null
for (const moduleItem of module.body) { for (const moduleItem of module.body) {
if (!isExportDeclaration(moduleItem)) { if (!isExportDeclaration(moduleItem)) {
continue continue
...@@ -252,5 +251,5 @@ export function extractExportedConstValue( ...@@ -252,5 +251,5 @@ export function extractExportedConstValue(
} }
} }
throw new NoSuchDeclarationError() return null
} }
...@@ -4,10 +4,7 @@ import type { RouteHas } from '../../lib/load-custom-routes' ...@@ -4,10 +4,7 @@ import type { RouteHas } from '../../lib/load-custom-routes'
import { readFileSync } from 'fs' import { readFileSync } from 'fs'
import { relative } from 'path' import { relative } from 'path'
import { LRUCache } from '../../server/lib/lru-cache' import { LRUCache } from '../../server/lib/lru-cache'
import { import { extractExportedConstValue } from './extract-const-value'
extractExportedConstValue,
UnsupportedValueError,
} from './extract-const-value'
import { parseModule } from './parse-module' import { parseModule } from './parse-module'
import * as Log from '../output/log' import * as Log from '../output/log'
import { import {
...@@ -568,7 +565,7 @@ const warnedUnsupportedValueMap = new LRUCache<boolean>(250, () => 1) ...@@ -568,7 +565,7 @@ const warnedUnsupportedValueMap = new LRUCache<boolean>(250, () => 1)
function warnAboutUnsupportedValue( function warnAboutUnsupportedValue(
pageFilePath: string, pageFilePath: string,
page: string | undefined, page: string | undefined,
error: UnsupportedValueError result: { unsupported: string; path?: string }
) { ) {
hadUnsupportedValue = true hadUnsupportedValue = true
const isProductionBuild = process.env.NODE_ENV === 'production' const isProductionBuild = process.env.NODE_ENV === 'production'
...@@ -587,8 +584,8 @@ function warnAboutUnsupportedValue( ...@@ -587,8 +584,8 @@ function warnAboutUnsupportedValue(
`Next.js can't recognize the exported \`config\` field in ` + `Next.js can't recognize the exported \`config\` field in ` +
(page ? `route "${page}"` : `"${pageFilePath}"`) + (page ? `route "${page}"` : `"${pageFilePath}"`) +
':\n' + ':\n' +
error.message + result.unsupported +
(error.path ? ` at "${error.path}"` : '') + (result.path ? ` at "${result.path}"` : '') +
'.\n' + '.\n' +
'Read More - https://nextjs.org/docs/messages/invalid-page-config' 'Read More - https://nextjs.org/docs/messages/invalid-page-config'
...@@ -648,23 +645,20 @@ export async function getAppPageStaticInfo({ ...@@ -648,23 +645,20 @@ export async function getAppPageStaticInfo({
const exportedConfig: Record<string, unknown> = {} const exportedConfig: Record<string, unknown> = {}
if (exports) { if (exports) {
for (const property of exports) { for (const property of exports) {
try { const result = extractExportedConstValue(ast, property)
exportedConfig[property] = extractExportedConstValue(ast, property) if (result !== null && 'unsupported' in result) {
} catch (e) { warnAboutUnsupportedValue(pageFilePath, page, result)
if (e instanceof UnsupportedValueError) { } else if (result !== null) {
warnAboutUnsupportedValue(pageFilePath, page, e) exportedConfig[property] = result.value
}
} }
} }
} }
try { const configResult = extractExportedConstValue(ast, 'config')
exportedConfig.config = extractExportedConstValue(ast, 'config') if (configResult !== null && 'unsupported' in configResult) {
} catch (e) { warnAboutUnsupportedValue(pageFilePath, page, configResult)
if (e instanceof UnsupportedValueError) { } else if (configResult !== null) {
warnAboutUnsupportedValue(pageFilePath, page, e) exportedConfig.config = configResult.value
}
// `export config` doesn't exist, or other unknown error thrown by swc, silence them
} }
const route = normalizeAppPath(page) const route = normalizeAppPath(page)
...@@ -749,23 +743,20 @@ export async function getPagesPageStaticInfo({ ...@@ -749,23 +743,20 @@ export async function getPagesPageStaticInfo({
const exportedConfig: Record<string, unknown> = {} const exportedConfig: Record<string, unknown> = {}
if (exports) { if (exports) {
for (const property of exports) { for (const property of exports) {
try { const result = extractExportedConstValue(ast, property)
exportedConfig[property] = extractExportedConstValue(ast, property) if (result !== null && 'unsupported' in result) {
} catch (e) { warnAboutUnsupportedValue(pageFilePath, page, result)
if (e instanceof UnsupportedValueError) { } else if (result !== null) {
warnAboutUnsupportedValue(pageFilePath, page, e) exportedConfig[property] = result.value
}
} }
} }
} }
try { const configResult = extractExportedConstValue(ast, 'config')
exportedConfig.config = extractExportedConstValue(ast, 'config') if (configResult !== null && 'unsupported' in configResult) {
} catch (e) { warnAboutUnsupportedValue(pageFilePath, page, configResult)
if (e instanceof UnsupportedValueError) { } else if (configResult !== null) {
warnAboutUnsupportedValue(pageFilePath, page, e) exportedConfig.config = configResult.value
}
// `export config` doesn't exist, or other unknown error thrown by swc, silence them
} }
// Validate the config. // Validate the config.
......
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