Skip to content

fix: gracefully handle missing static analysis tools #1691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 18, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions packages/runtime/src/helpers/analysis.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import fs, { existsSync } from 'fs'

import { extractExportedConstValue, UnsupportedValueError } from 'next/dist/build/analysis/extract-const-value'
import { parseModule } from 'next/dist/build/analysis/parse-module'
import { relative } from 'pathe'

// I have no idea what eslint is up to here but it gives an error
Expand Down Expand Up @@ -81,13 +79,39 @@ export const validateConfigValue = (config: ApiConfig, apiFilePath: string): con
return false
}

let extractConstValue
let parseModule
let hasWarnedAboutNextVersion = false
/**
* Uses Next's swc static analysis to extract the config values from a file.
*/
export const extractConfigFromFile = async (apiFilePath: string): Promise<ApiConfig> => {
if (!apiFilePath || !existsSync(apiFilePath)) {
return {}
}

try {
if (!extractConstValue) {
extractConstValue = require('next/dist/build/analysis/extract-const-value')
}
if (!parseModule) {
// eslint-disable-next-line prefer-destructuring, @typescript-eslint/no-var-requires
parseModule = require('next/dist/build/analysis/parse-module').parseModule
}
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
if (!hasWarnedAboutNextVersion) {
console.log("This version of Next.js doesn't support advanced API routes. Skipping...")
hasWarnedAboutNextVersion = true
}
// Old Next.js version
return {}
}
throw error
}

const { extractExportedConstValue, UnsupportedValueError } = extractConstValue

const fileContent = await fs.promises.readFile(apiFilePath, 'utf8')
// No need to parse if there's no "config"
if (!fileContent.includes('config')) {
Expand All @@ -99,7 +123,7 @@ export const extractConfigFromFile = async (apiFilePath: string): Promise<ApiCon
try {
config = extractExportedConstValue(ast, 'config')
} catch (error) {
if (error instanceof UnsupportedValueError) {
if (UnsupportedValueError && error instanceof UnsupportedValueError) {
console.warn(`Unsupported config value in ${relative(process.cwd(), apiFilePath)}`)
}
return {}
Expand Down