1
1
import fs , { existsSync } from 'fs'
2
2
3
- import { extractExportedConstValue , UnsupportedValueError } from 'next/dist/build/analysis/extract-const-value'
4
- import { parseModule } from 'next/dist/build/analysis/parse-module'
5
3
import { relative } from 'pathe'
6
4
7
5
// I have no idea what eslint is up to here but it gives an error
@@ -81,13 +79,39 @@ export const validateConfigValue = (config: ApiConfig, apiFilePath: string): con
81
79
return false
82
80
}
83
81
82
+ let extractConstValue
83
+ let parseModule
84
+ let hasWarnedAboutNextVersion = false
84
85
/**
85
86
* Uses Next's swc static analysis to extract the config values from a file.
86
87
*/
87
88
export const extractConfigFromFile = async ( apiFilePath : string ) : Promise < ApiConfig > => {
88
89
if ( ! apiFilePath || ! existsSync ( apiFilePath ) ) {
89
90
return { }
90
91
}
92
+
93
+ try {
94
+ if ( ! extractConstValue ) {
95
+ extractConstValue = require ( 'next/dist/build/analysis/extract-const-value' )
96
+ }
97
+ if ( ! parseModule ) {
98
+ // eslint-disable-next-line prefer-destructuring, @typescript-eslint/no-var-requires
99
+ parseModule = require ( 'next/dist/build/analysis/parse-module' ) . parseModule
100
+ }
101
+ } catch ( error ) {
102
+ if ( error . code === 'MODULE_NOT_FOUND' ) {
103
+ if ( ! hasWarnedAboutNextVersion ) {
104
+ console . log ( "This version of Next.js doesn't support advanced API routes. Skipping..." )
105
+ hasWarnedAboutNextVersion = true
106
+ }
107
+ // Old Next.js version
108
+ return { }
109
+ }
110
+ throw error
111
+ }
112
+
113
+ const { extractExportedConstValue, UnsupportedValueError } = extractConstValue
114
+
91
115
const fileContent = await fs . promises . readFile ( apiFilePath , 'utf8' )
92
116
// No need to parse if there's no "config"
93
117
if ( ! fileContent . includes ( 'config' ) ) {
@@ -99,7 +123,7 @@ export const extractConfigFromFile = async (apiFilePath: string): Promise<ApiCon
99
123
try {
100
124
config = extractExportedConstValue ( ast , 'config' )
101
125
} catch ( error ) {
102
- if ( error instanceof UnsupportedValueError ) {
126
+ if ( UnsupportedValueError && error instanceof UnsupportedValueError ) {
103
127
console . warn ( `Unsupported config value in ${ relative ( process . cwd ( ) , apiFilePath ) } ` )
104
128
}
105
129
return { }
0 commit comments