Unverified Commit e9a8ee50 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Update codemod ESLint template to Flat config (#84919)

Stacked on https://github.com/vercel/next.js/pull/84874

### Why?

As `eslint-config-next` supports Flat config since PR
https://github.com/vercel/next.js/pull/84874, Release
[v16.0.0-canary.6](https://github.com/vercel/next.js/releases/tag/v16.0.0-canary.6),
update codemod to use Flat config. Since `eslint-config-next` version
and this codemod's version will match, no need to gate the version, as
by the time this change is released, the same `eslint-config-next`
version will support Flat config.

### How?

Updated to handle the three cases:

- Legacy config
- Flat config with FlatCompat (Which we used to recommend for v15)
- Flat config with no FlatCompat (Which means the app does not use
`eslint-config-next`)

For the Legacy config, ESLint provides a [Migration
tool](https://eslint.org/docs/latest/use/configure/migration-guide), so
use that to convert to Flat config. It will include FlatCompat, so the
rest of the process is the same as Flat config with FlatCompat.

For the Flat config with FlatCompat, the codemod will remove FlatCompat
and map the `eslint-config-next` imports directly to the export.

For the Flat config with no FlatCompat, the codemod will import
`eslint-config-next` and map the imports directly to the export.

Tested on
[shadcn/ui](https://github.com/shadcn-ui/ui/blob/cb769b7059b50b5dca033a6eb57bb8ecde69fc87/.eslintrc.json)
and other large legacy ESLint configs.
parent c525e139
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"next": "15.0.0"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19"
}
}
\ No newline at end of file
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint ."
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"next": "15.0.0"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "15.0.0",
"@eslint/eslintrc": "^3"
}
}
\ No newline at end of file
module.exports = [
{
rules: {
"quotes": ["error", "double"],
"indent": ["error", 2]
}
}
]
\ No newline at end of file
{
"name": "complex-scripts-app",
"version": "1.0.0",
"scripts": {
"lint": "eslint --fix src pages",
"lint:strict": "eslint --max-warnings 0 .",
"lint:ci": "eslint --quiet --output-file lint-results.json .",
"precommit": "eslint --fix . && npm test",
"test": "jest && eslint .",
"complex": "npm run build && eslint . 2>/dev/null",
"pipe": "eslint . | tee lint.log",
"redirect": "eslint . > output.txt 2>&1",
"multi": "eslint .; next build; eslint --fix ."
},
"dependencies": {
"next": "15.0.0"
},
"devDependencies": {
"eslint": "^9",
"eslint-config-next": "15.0.0",
"@eslint/eslintrc": "^3"
}
}
\ No newline at end of file
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"next": "15.0.0"
},
"devDependencies": {
"eslint": "^8.0.0",
"eslint-config-next": "15.0.0"
}
}
\ No newline at end of file
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint ."
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"next": "15.0.0"
},
"devDependencies": {
"eslint": "^8.0.0",
"eslint-config-next": "15.0.0",
"@eslint/eslintrc": "^3"
}
}
\ No newline at end of file
export default [
{
rules: {
"no-console": "warn",
"semi": ["error", "always"]
}
},
{
files: ["**/*.test.js"],
rules: {
"no-console": "off"
}
}
]
\ No newline at end of file
{
"name": "app-with-flat-config",
"version": "1.0.0",
"scripts": {
"lint": "next lint",
"lint:fix": "next lint --fix"
},
"dependencies": {
"next": "15.0.0"
}
}
\ No newline at end of file
{
"name": "app-with-flat-config",
"version": "1.0.0",
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint --fix ."
},
"dependencies": {
"next": "15.0.0"
},
"devDependencies": {
"eslint": "^9",
"eslint-config-next": "15.0.0",
"@eslint/eslintrc": "^3"
}
}
\ No newline at end of file
export default [
{
ignores: ["dist/**", "coverage/**"]
},
{
rules: {
"no-unused-vars": "warn"
}
}
]
\ No newline at end of file
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { FlatCompat } from '@eslint/eslintrc'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const compat = new FlatCompat({
baseDirectory: __dirname,
})
const eslintConfig = [
...compat.extends('next/core-web-vitals', 'next/typescript'),
{
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
},
]
export default eslintConfig
{
"name": "complex-scripts-app",
"version": "1.0.0",
"scripts": {
"lint": "next lint --fix --dir src --dir pages",
"lint:strict": "next lint --strict",
......@@ -13,6 +11,16 @@
"multi": "next lint; next build; next lint --fix"
},
"dependencies": {
"next": "15.0.0"
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
\ No newline at end of file
}
import { defineConfig } from 'eslint/config'
import foo from 'foo'
import bar from 'bar'
const eslintConfig = defineConfig([
foo,
bar,
{
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
},
])
export default eslintConfig
{
"scripts": {
"lint": "next lint --fix --dir src --dir pages",
"lint:strict": "next lint --strict",
"lint:ci": "next lint --quiet --output-file lint-results.json",
"precommit": "next lint --fix && npm test",
"test": "jest && next lint",
"complex": "npm run build && next lint --dir . --ext .js,.jsx,.ts,.tsx 2>/dev/null",
"pipe": "next lint | tee lint.log",
"redirect": "next lint > output.txt 2>&1",
"multi": "next lint; next build; next lint --fix"
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
node_modules/**
.next/**
out/**
build/**
next-env.d.ts
**/*.md
\ No newline at end of file
{
"$schema": "https://json.schemastore.org/eslintrc",
"root": true,
"extends": [
"next/core-web-vitals",
"turbo",
"prettier",
"plugin:tailwindcss/recommended"
],
"plugins": ["tailwindcss"],
"ignorePatterns": ["**/fixtures/**"],
"rules": {
"@next/next/no-html-link-for-pages": "off",
"tailwindcss/no-custom-classname": "off",
"tailwindcss/classnames-order": "error"
},
"settings": {
"tailwindcss": {
"callees": ["cn", "cva"],
"config": "tailwind.config.cjs"
},
"next": {
"rootDir": ["apps/*/"]
}
},
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"parser": "@typescript-eslint/parser"
}
]
}
\ No newline at end of file
{
"scripts": {
"lint": "next lint --fix --dir src --dir pages",
"lint:strict": "next lint --strict",
"lint:ci": "next lint --quiet --output-file lint-results.json",
"precommit": "next lint --fix && npm test",
"test": "jest && next lint",
"complex": "npm run build && next lint --dir . --ext .js,.jsx,.ts,.tsx 2>/dev/null",
"pipe": "next lint | tee lint.log",
"redirect": "next lint > output.txt 2>&1",
"multi": "next lint; next build; next lint --fix"
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
{
"name": "app-without-scripts",
"version": "1.0.0",
"dependencies": {
"next": "15.0.0"
}
}
\ No newline at end of file
{
"name": "app-without-scripts",
"version": "1.0.0",
"scripts": {},
"dependencies": {
"next": "15.0.0"
},
"devDependencies": {
"eslint": "^9",
"eslint-config-next": "15.0.0",
"@eslint/eslintrc": "^3"
}
}
\ No newline at end of file
/* global jest */
jest.autoMockOff()
const fs = require('fs')
const path = require('path')
const { tmpdir } = require('os')
const transformer = require('../next-lint-to-eslint-cli').default
const os = require('os')
describe('next-lint-to-eslint-cli', () => {
let tempDir
beforeEach(() => {
// Create a unique temp directory for each test
tempDir = fs.mkdtempSync(path.join(tmpdir(), 'codemod-test-'))
})
afterEach(() => {
// Clean up temp directory
if (tempDir && fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true })
}
})
test('transforms correctly using basic data', () => {
// Read input fixture
const inputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/basic.input.json')
const expectedOutputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/basic.output.json')
const inputContent = fs.readFileSync(inputPath, 'utf8')
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf8')
// Set up test project
const packageJsonPath = path.join(tempDir, 'package.json')
const tsConfigPath = path.join(tempDir, 'tsconfig.json')
fs.writeFileSync(packageJsonPath, inputContent)
fs.writeFileSync(tsConfigPath, '{}') // Create tsconfig.json to indicate TypeScript project
// Run transformer
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Check package.json was updated correctly
const actualPackageJson = fs.readFileSync(packageJsonPath, 'utf8')
expect(JSON.parse(actualPackageJson)).toEqual(JSON.parse(expectedOutput))
// Check eslint.config.mjs was created
const eslintConfigPath = path.join(tempDir, 'eslint.config.mjs')
expect(fs.existsSync(eslintConfigPath)).toBe(true)
const eslintConfig = fs.readFileSync(eslintConfigPath, 'utf8')
expect(eslintConfig).toContain('next/core-web-vitals')
expect(eslintConfig).toContain('next/typescript')
expect(eslintConfig).toContain('ignores:')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('transforms correctly using existing-eslint data', () => {
// Read input fixture
const inputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-eslint.input.json')
const expectedOutputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-eslint.output.json')
const inputContent = fs.readFileSync(inputPath, 'utf8')
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf8')
// Set up test project
const packageJsonPath = path.join(tempDir, 'package.json')
const existingEslintPath = path.join(tempDir, '.eslintrc.json')
fs.writeFileSync(packageJsonPath, inputContent)
fs.writeFileSync(existingEslintPath, '{"extends": ["next"]}') // Create existing ESLint config
// Run transformer
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Check package.json was updated correctly
const actualPackageJson = fs.readFileSync(packageJsonPath, 'utf8')
expect(JSON.parse(actualPackageJson)).toEqual(JSON.parse(expectedOutput))
// Check that no new eslint.config.mjs was created (existing config should be preserved)
const eslintConfigPath = path.join(tempDir, 'eslint.config.mjs')
expect(fs.existsSync(eslintConfigPath)).toBe(false)
// Check that existing config still exists
expect(fs.existsSync(existingEslintPath)).toBe(true)
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('handles complex script patterns correctly', () => {
const inputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/complex-scripts.input.json')
const expectedOutputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/complex-scripts.output.json')
const inputContent = fs.readFileSync(inputPath, 'utf8')
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf8')
const packageJsonPath = path.join(tempDir, 'package.json')
fs.writeFileSync(packageJsonPath, inputContent)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
const actualPackageJson = fs.readFileSync(packageJsonPath, 'utf8')
expect(JSON.parse(actualPackageJson)).toEqual(JSON.parse(expectedOutput))
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('updates existing ES module flat config with AST manipulation', () => {
const inputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-flat-config.input.json')
const expectedOutputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-flat-config.output.json')
const eslintConfigFixture = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-flat-config.eslint.js')
const inputContent = fs.readFileSync(inputPath, 'utf8')
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf8')
const eslintConfigContent = fs.readFileSync(eslintConfigFixture, 'utf8')
const packageJsonPath = path.join(tempDir, 'package.json')
const eslintConfigPath = path.join(tempDir, 'eslint.config.js')
fs.writeFileSync(packageJsonPath, inputContent)
fs.writeFileSync(eslintConfigPath, eslintConfigContent)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Check package.json was updated
const actualPackageJson = fs.readFileSync(packageJsonPath, 'utf8')
expect(JSON.parse(actualPackageJson)).toEqual(JSON.parse(expectedOutput))
// Check that existing config was updated with Next.js configs
const updatedConfig = fs.readFileSync(eslintConfigPath, 'utf8')
expect(updatedConfig).toContain('FlatCompat')
expect(updatedConfig).toContain('next/core-web-vitals')
expect(updatedConfig).toContain('no-console') // Original rule should be preserved
expect(updatedConfig).toContain('semi') // Original rule should be preserved
expect(updatedConfig).toContain('ignores') // Should add ignores section
expect(updatedConfig).toContain('.next/**') // Should include Next.js build directory
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('updates existing CommonJS flat config with AST manipulation', () => {
const inputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-flat-config.input.json')
const expectedOutputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/existing-flat-config.output.json')
const eslintConfigFixture = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/cjs-flat-config.eslint.cjs')
const inputContent = fs.readFileSync(inputPath, 'utf8')
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf8')
const eslintConfigContent = fs.readFileSync(eslintConfigFixture, 'utf8')
const packageJsonPath = path.join(tempDir, 'package.json')
const eslintConfigPath = path.join(tempDir, 'eslint.config.cjs')
fs.writeFileSync(packageJsonPath, inputContent)
fs.writeFileSync(eslintConfigPath, eslintConfigContent)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Check package.json was updated
const actualPackageJson = fs.readFileSync(packageJsonPath, 'utf8')
expect(JSON.parse(actualPackageJson)).toEqual(JSON.parse(expectedOutput))
// Check that existing config was updated with Next.js configs
const updatedConfig = fs.readFileSync(eslintConfigPath, 'utf8')
expect(updatedConfig).toContain('FlatCompat')
expect(updatedConfig).toContain('require')
expect(updatedConfig).toContain('next/core-web-vitals')
expect(updatedConfig).toContain('quotes') // Original rule should be preserved
expect(updatedConfig).toContain('indent') // Original rule should be preserved
expect(updatedConfig).toContain('ignores') // Should add ignores section
expect(updatedConfig).toContain('node_modules/**') // Should include common ignores
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('handles package.json without scripts section', () => {
const inputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/no-scripts.input.json')
const expectedOutputPath = path.join(__dirname, '../__testfixtures__/next-lint-to-eslint-cli/no-scripts.output.json')
const inputContent = fs.readFileSync(inputPath, 'utf8')
const expectedOutput = fs.readFileSync(expectedOutputPath, 'utf8')
const packageJsonPath = path.join(tempDir, 'package.json')
fs.writeFileSync(packageJsonPath, inputContent)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Check package.json was updated with dependencies only
const actualPackageJson = fs.readFileSync(packageJsonPath, 'utf8')
expect(JSON.parse(actualPackageJson)).toEqual(JSON.parse(expectedOutput))
// Check that eslint.config.mjs was created
const eslintConfigPath = path.join(tempDir, 'eslint.config.mjs')
expect(fs.existsSync(eslintConfigPath)).toBe(true)
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('preserves existing eslint dependencies', () => {
const packageJson = {
name: 'app-with-eslint',
scripts: {
lint: 'next lint'
},
dependencies: {
next: '15.0.0'
},
devDependencies: {
eslint: '^8.57.0',
'eslint-config-next': '14.2.0'
}
}
const packageJsonPath = path.join(tempDir, 'package.json')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
const actualPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
// Should preserve existing eslint versions
expect(actualPackageJson.devDependencies.eslint).toBe('^8.57.0')
expect(actualPackageJson.devDependencies['eslint-config-next']).toBe('14.2.0')
// Should add missing @eslint/eslintrc
expect(actualPackageJson.devDependencies['@eslint/eslintrc']).toBe('^3')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('handles TypeScript config files', () => {
const packageJson = {
name: 'app-with-ts-config',
scripts: {
lint: 'next lint'
},
dependencies: {
next: '15.0.0'
}
}
const packageJsonPath = path.join(tempDir, 'package.json')
const eslintConfigPath = path.join(tempDir, 'eslint.config.ts')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
fs.writeFileSync(eslintConfigPath, 'export default []')
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Should log that TypeScript configs require manual migration
expect(consoleWarnSpy).toHaveBeenCalledWith(
expect.anything(),
expect.stringContaining('TypeScript config files require manual migration')
let isolatedDir
let transformer
let fixturesDir
beforeAll(() => {
// Create isolated directory ONCE
const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir()
isolatedDir = path.join(
tmpBase,
`next-lint-to-eslint-cli-test-${Date.now()}-${(Math.random() * 1000) | 0}`
)
fs.mkdirSync(isolatedDir, { recursive: true })
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
consoleWarnSpy.mockRestore()
})
test('handles missing package.json gracefully', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
expect(consoleErrorSpy).toHaveBeenCalledWith('Error: package.json not found in the specified directory')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('handles missing directory argument', () => {
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([], { skipInstall: true })
expect(consoleErrorSpy).toHaveBeenCalledWith('Error: Please specify a directory path')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('creates JavaScript config for non-TypeScript projects', () => {
const packageJson = {
name: 'js-app',
scripts: {
lint: 'next lint'
},
dependencies: {
next: '15.0.0',
react: '^18.0.0'
}
}
const packageJsonPath = path.join(tempDir, 'package.json')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Check that eslint.config.mjs was created without TypeScript config
const eslintConfigPath = path.join(tempDir, 'eslint.config.mjs')
const eslintConfig = fs.readFileSync(eslintConfigPath, 'utf8')
expect(eslintConfig).toContain('next/core-web-vitals')
expect(eslintConfig).not.toContain('next/typescript')
// Copy all fixtures ONCE
fixturesDir = path.join(isolatedDir, 'fixtures')
const fixturesSrc = path.join(
__dirname,
'../__testfixtures__/next-lint-to-eslint-cli'
)
fs.cpSync(fixturesSrc, fixturesDir, { recursive: true })
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
// Load transformer from original location (has all dependencies)
transformer = require('../next-lint-to-eslint-cli.js').default
})
test('adds ignores even when Next.js configs are already present', () => {
const existingConfig = `
import { FlatCompat } from "@eslint/eslintrc"
const compat = new FlatCompat({ baseDirectory: __dirname })
export default [
...compat.extends("next/core-web-vitals"),
{ rules: { "no-console": "warn" } }
]`
const packageJson = {
name: 'app-with-next-config',
scripts: {
lint: 'next lint'
},
dependencies: {
next: '15.0.0'
}
afterAll(() => {
// Clean up ONCE after all tests
if (isolatedDir && fs.existsSync(isolatedDir)) {
fs.rmSync(isolatedDir, { recursive: true, force: true })
}
const packageJsonPath = path.join(tempDir, 'package.json')
const eslintConfigPath = path.join(tempDir, 'eslint.config.js')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
fs.writeFileSync(eslintConfigPath, existingConfig)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Should still add ignores even though Next.js configs are present
const updatedConfig = fs.readFileSync(eslintConfigPath, 'utf8')
expect(updatedConfig).toContain('ignores')
expect(updatedConfig).toContain('.next/**')
expect(updatedConfig).toContain('node_modules/**')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
})
test('handles scripts with paths containing spaces', () => {
const packageJson = {
name: 'app-with-spaces',
scripts: {
lint: 'next lint --dir "src/my components" --file "test file.js"'
},
dependencies: {
next: '15.0.0'
}
}
const packageJsonPath = path.join(tempDir, 'package.json')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
const actualPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
expect(actualPackageJson.scripts.lint).toBe('eslint "src/my components" "test file.js"')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
describe('flat-config', () => {
it('should keep config unchanged and transform package.json', () => {
const testDir = path.join(fixturesDir, 'flat-config')
// Check BEFORE state
const beforeConfig = fs.readFileSync(
path.join(testDir, 'eslint.config.mjs'),
'utf8'
)
const beforePackage = fs.readFileSync(
path.join(testDir, 'package.json'),
'utf8'
)
expect(beforeConfig).toMatchInlineSnapshot(`
"import { defineConfig } from 'eslint/config'
import foo from 'foo'
import bar from 'bar'
const eslintConfig = defineConfig([
foo,
bar,
{
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
},
])
export default eslintConfig
"
`)
expect(beforePackage).toMatchInlineSnapshot(`
"{
"scripts": {
"lint": "next lint --fix --dir src --dir pages",
"lint:strict": "next lint --strict",
"lint:ci": "next lint --quiet --output-file lint-results.json",
"precommit": "next lint --fix && npm test",
"test": "jest && next lint",
"complex": "npm run build && next lint --dir . --ext .js,.jsx,.ts,.tsx 2>/dev/null",
"pipe": "next lint | tee lint.log",
"redirect": "next lint > output.txt 2>&1",
"multi": "next lint; next build; next lint --fix"
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
"
`)
// Run transformer
transformer([testDir], { skipInstall: true })
// Check AFTER state
const actualConfig = fs.readFileSync(
path.join(testDir, 'eslint.config.mjs'),
'utf8'
)
expect(actualConfig).toMatchInlineSnapshot(`
"import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypescript from "eslint-config-next/typescript";
import { defineConfig } from 'eslint/config'
import foo from 'foo'
import bar from 'bar'
const eslintConfig = defineConfig([...nextCoreWebVitals, ...nextTypescript, foo, bar, {
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
}])
export default eslintConfig
"
`)
// Check package.json transformed
const actualPackage = fs.readFileSync(
path.join(testDir, 'package.json'),
'utf8'
)
expect(actualPackage).toMatchInlineSnapshot(`
"{
"scripts": {
"lint": "eslint --fix src pages",
"lint:strict": "eslint --max-warnings 0 .",
"lint:ci": "eslint --quiet --output-file lint-results.json .",
"precommit": "eslint --fix . && npm test",
"test": "jest && eslint .",
"complex": "npm run build && eslint . 2>/dev/null",
"pipe": "eslint . | tee lint.log",
"redirect": "eslint . > output.txt 2>&1",
"multi": "eslint .; next build; eslint --fix ."
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
"
`)
})
})
test('does not duplicate ignores if already present', () => {
const packageJson = {
name: 'app-with-existing-ignores',
scripts: {
lint: 'next lint'
},
dependencies: {
next: '15.0.0'
}
}
const existingConfig = `export default [
{
ignores: ["dist/**", "coverage/**"]
},
{
rules: {
"no-unused-vars": "warn"
}
}
]`
const packageJsonPath = path.join(tempDir, 'package.json')
const eslintConfigPath = path.join(tempDir, 'eslint.config.js')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
fs.writeFileSync(eslintConfigPath, existingConfig)
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
const updatedConfig = fs.readFileSync(eslintConfigPath, 'utf8')
// Should add Next.js extends
expect(updatedConfig).toContain('next/core-web-vitals')
// Should preserve existing ignores
expect(updatedConfig).toContain('dist/**')
expect(updatedConfig).toContain('coverage/**')
// Check that Next.js ignores are added to existing ignores
expect(updatedConfig).toContain('.next/**') // Next.js build dir added
expect(updatedConfig).toContain('node_modules/**') // Common ignore added
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
describe('flat-config-flat-compat', () => {
it('should replace FlatCompat with direct imports and transform package.json', () => {
const testDir = path.join(fixturesDir, 'flat-config-flat-compat')
// Check BEFORE state
const beforeConfig = fs.readFileSync(
path.join(testDir, 'eslint.config.mjs'),
'utf8'
)
const beforePackage = fs.readFileSync(
path.join(testDir, 'package.json'),
'utf8'
)
expect(beforeConfig).toMatchInlineSnapshot(`
"import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { FlatCompat } from '@eslint/eslintrc'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const compat = new FlatCompat({
baseDirectory: __dirname,
})
const eslintConfig = [
...compat.extends('next/core-web-vitals', 'next/typescript'),
{
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
},
]
export default eslintConfig
"
`)
expect(beforePackage).toMatchInlineSnapshot(`
"{
"scripts": {
"lint": "next lint --fix --dir src --dir pages",
"lint:strict": "next lint --strict",
"lint:ci": "next lint --quiet --output-file lint-results.json",
"precommit": "next lint --fix && npm test",
"test": "jest && next lint",
"complex": "npm run build && next lint --dir . --ext .js,.jsx,.ts,.tsx 2>/dev/null",
"pipe": "next lint | tee lint.log",
"redirect": "next lint > output.txt 2>&1",
"multi": "next lint; next build; next lint --fix"
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
"
`)
// Run transformer
transformer([testDir], { skipInstall: true })
// Check AFTER state
const actualConfig = fs.readFileSync(
path.join(testDir, 'eslint.config.mjs'),
'utf8'
)
expect(actualConfig).toMatchInlineSnapshot(`
"import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypescript from "eslint-config-next/typescript";
import { dirname } from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const eslintConfig = [...nextCoreWebVitals, ...nextTypescript, {
ignores: [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
],
}]
export default eslintConfig
"
`)
// Check package.json transformed
const actualPackage = fs.readFileSync(
path.join(testDir, 'package.json'),
'utf8'
)
expect(actualPackage).toMatchInlineSnapshot(`
"{
"scripts": {
"lint": "eslint --fix src pages",
"lint:strict": "eslint --max-warnings 0 .",
"lint:ci": "eslint --quiet --output-file lint-results.json .",
"precommit": "eslint --fix . && npm test",
"test": "jest && eslint .",
"complex": "npm run build && eslint . 2>/dev/null",
"pipe": "eslint . | tee lint.log",
"redirect": "eslint . > output.txt 2>&1",
"multi": "eslint .; next build; eslint --fix ."
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
"
`)
})
})
test('handles unsupported flags with warnings', () => {
const packageJson = {
name: 'app-with-unsupported-flags',
scripts: {
lint: 'next lint --rulesdir ./custom-rules --ext .js,.jsx'
},
dependencies: {
next: '15.0.0'
}
}
const packageJsonPath = path.join(tempDir, 'package.json')
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {})
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
transformer([tempDir], { skipInstall: true })
// Should show warnings about unsupported flags
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('--rulesdir is not supported in ESLint v9'))
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('--ext is not needed in ESLint v9'))
// Script should be updated without the unsupported flags
const actualPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
expect(actualPackageJson.scripts.lint).toBe('eslint .')
consoleSpy.mockRestore()
consoleErrorSpy.mockRestore()
describe('legacy-config', () => {
it('should migrate legacy config to flat config and transform package.json', async () => {
const testDir = path.join(fixturesDir, 'legacy-config')
// Check BEFORE state
const beforeEslintrc = fs.readFileSync(
path.join(testDir, '.eslintrc.json'),
'utf8'
)
const beforeEslintignore = fs.readFileSync(
path.join(testDir, '.eslintignore'),
'utf8'
)
const beforePackage = fs.readFileSync(
path.join(testDir, 'package.json'),
'utf8'
)
expect(beforeEslintrc).toMatchInlineSnapshot(`
"{
"$schema": "https://json.schemastore.org/eslintrc",
"root": true,
"extends": [
"next/core-web-vitals",
"turbo",
"prettier",
"plugin:tailwindcss/recommended"
],
"plugins": ["tailwindcss"],
"ignorePatterns": ["**/fixtures/**"],
"rules": {
"@next/next/no-html-link-for-pages": "off",
"tailwindcss/no-custom-classname": "off",
"tailwindcss/classnames-order": "error"
},
"settings": {
"tailwindcss": {
"callees": ["cn", "cva"],
"config": "tailwind.config.cjs"
},
"next": {
"rootDir": ["apps/*/"]
}
},
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"parser": "@typescript-eslint/parser"
}
]
}"
`)
expect(beforeEslintignore).toMatchInlineSnapshot(`
"node_modules/**
.next/**
out/**
build/**
next-env.d.ts
**/*.md"
`)
expect(beforePackage).toMatchInlineSnapshot(`
"{
"scripts": {
"lint": "next lint --fix --dir src --dir pages",
"lint:strict": "next lint --strict",
"lint:ci": "next lint --quiet --output-file lint-results.json",
"precommit": "next lint --fix && npm test",
"test": "jest && next lint",
"complex": "npm run build && next lint --dir . --ext .js,.jsx,.ts,.tsx 2>/dev/null",
"pipe": "next lint | tee lint.log",
"redirect": "next lint > output.txt 2>&1",
"multi": "next lint; next build; next lint --fix"
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
"
`)
// Run transformer (now async)
await transformer([testDir], { skipInstall: true })
// Check AFTER state - eslint.config.mjs was created and transformed
const actualConfig = fs.readFileSync(
path.join(testDir, 'eslint.config.mjs'),
'utf8'
)
expect(actualConfig).toMatchInlineSnapshot(`
"import { defineConfig, globalIgnores } from "eslint/config";
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import tailwindcss from "eslint-plugin-tailwindcss";
import tsParser from "@typescript-eslint/parser";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
export default defineConfig([globalIgnores([
"**/fixtures/**/*",
"node_modules/**/*",
".next/**/*",
"out/**/*",
"build/**/*",
"**/next-env.d.ts",
"**/*.md",
]), {
extends: [
...nextCoreWebVitals,
...compat.extends("turbo"),
...compat.extends("prettier"),
...compat.extends("plugin:tailwindcss/recommended")
],
plugins: {
tailwindcss,
},
settings: {
tailwindcss: {
callees: ["cn", "cva"],
config: "tailwind.config.cjs",
},
next: {
rootDir: ["apps/*/"],
},
},
rules: {
"@next/next/no-html-link-for-pages": "off",
"tailwindcss/no-custom-classname": "off",
"tailwindcss/classnames-order": "error",
},
}, {
files: ["**/*.ts", "**/*.tsx"],
languageOptions: {
parser: tsParser,
},
}]);"
`)
// Check package.json transformed
const actualPackage = fs.readFileSync(
path.join(testDir, 'package.json'),
'utf8'
)
expect(actualPackage).toMatchInlineSnapshot(`
"{
"scripts": {
"lint": "eslint --fix src pages",
"lint:strict": "eslint --max-warnings 0 .",
"lint:ci": "eslint --quiet --output-file lint-results.json .",
"precommit": "eslint --fix . && npm test",
"test": "jest && eslint .",
"complex": "npm run build && eslint . 2>/dev/null",
"pipe": "eslint . | tee lint.log",
"redirect": "eslint . > output.txt 2>&1",
"multi": "eslint .; next build; eslint --fix ."
},
"dependencies": {
"react": "^19",
"react-dom": "^19",
"next": "^16"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "^16"
}
}
"
`)
})
})
})
\ No newline at end of file
})
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs'
import path from 'node:path'
import { execSync } from 'node:child_process'
import { getPkgManager, installPackages } from '../lib/handle-package'
import { createParserFromPath } from '../lib/parser'
import { white, bold, red, yellow, green, magenta } from 'picocolors'
......@@ -19,20 +20,12 @@ interface TransformerOptions {
[key: string]: unknown
}
const ESLINT_CONFIG_TEMPLATE_TYPESCRIPT = `\
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const ESLINT_CONFIG_TEMPLATE_TYPESCRIPT = `import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypescript from "eslint-config-next/typescript";
const eslintConfig = [
...compat.extends("next/core-web-vitals", "next/typescript"),
...nextCoreWebVitals,
...nextTypescript,
{
ignores: [
"node_modules/**",
......@@ -47,19 +40,10 @@ const eslintConfig = [
export default eslintConfig;
`
const ESLINT_CONFIG_TEMPLATE_JAVASCRIPT = `import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const ESLINT_CONFIG_TEMPLATE_JAVASCRIPT = `import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
const eslintConfig = [
...compat.extends("next/core-web-vitals"),
...nextCoreWebVitals,
{
ignores: [
"node_modules/**",
......@@ -80,8 +64,8 @@ function detectTypeScript(projectRoot: string): boolean {
function findExistingEslintConfig(projectRoot: string): {
exists: boolean
path?: string
isFlat?: boolean
path: string | null
isLegacy: boolean | null
} {
const flatConfigs = [
'eslint.config.js',
......@@ -105,7 +89,7 @@ function findExistingEslintConfig(projectRoot: string): {
for (const config of flatConfigs) {
const configPath = path.join(projectRoot, config)
if (existsSync(configPath)) {
return { exists: true, path: configPath, isFlat: true }
return { exists: true, path: configPath, isLegacy: false }
}
}
......@@ -113,17 +97,14 @@ function findExistingEslintConfig(projectRoot: string): {
for (const config of legacyConfigs) {
const configPath = path.join(projectRoot, config)
if (existsSync(configPath)) {
return { exists: true, path: configPath, isFlat: false }
return { exists: true, path: configPath, isLegacy: true }
}
}
return { exists: false }
return { exists: false, path: null, isLegacy: null }
}
function updateExistingFlatConfig(
configPath: string,
isTypeScript: boolean
): boolean {
function replaceFlatCompatInConfig(configPath: string): boolean {
let configContent: string
try {
configContent = readFileSync(configPath, 'utf8')
......@@ -132,28 +113,13 @@ function updateExistingFlatConfig(
return false
}
// Check if Next.js configs are already imported
const hasNextConfigs =
configContent.includes('next/core-web-vitals') ||
configContent.includes('next/typescript')
// TypeScript config files need special handling
if (
configPath.endsWith('.ts') ||
configPath.endsWith('.mts') ||
configPath.endsWith('.cts')
) {
console.warn(
prefixes.warn,
' TypeScript config files require manual migration'
)
console.log(' Please add the following to your config:')
console.log(' - Import: import { FlatCompat } from "@eslint/eslintrc"')
console.log(
' - Extend: ...compat.extends("next/core-web-vitals"' +
(isTypeScript ? ', "next/typescript"' : '') +
')'
)
// Check if FlatCompat is used
const hasFlatCompat =
configContent.includes('FlatCompat') ||
configContent.includes('@eslint/eslintrc')
if (!hasFlatCompat) {
console.log(' No FlatCompat usage found, no changes needed')
return false
}
......@@ -161,100 +127,339 @@ function updateExistingFlatConfig(
const j = createParserFromPath(configPath)
const root = j(configContent)
// Determine if it's CommonJS or ES modules
let isCommonJS = false
// Track if we need to add imports and preserve other configs
let needsNextVitals = false
let needsNextTs = false
let otherConfigs: string[] = []
if (configPath.endsWith('.cjs')) {
isCommonJS = true
} else if (configPath.endsWith('.mjs')) {
isCommonJS = false
} else if (configPath.endsWith('.js')) {
// For .js files, check package.json type field
const projectRoot = path.dirname(configPath)
const packageJsonPath = path.join(projectRoot, 'package.json')
// Look for FlatCompat extends usage and identify which configs are being used
root.find(j.CallExpression).forEach((astPath) => {
const node = astPath.value
try {
if (existsSync(packageJsonPath)) {
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'))
isCommonJS = packageJson.type !== 'module'
} else {
// Default to CommonJS if no package.json found
isCommonJS = true
}
} catch {
// Default to CommonJS if package.json can't be read
isCommonJS = true
if (
node.callee.type === 'MemberExpression' &&
(node.callee as any).object.type === 'Identifier' &&
(node.callee as any).object.name === 'compat' &&
(node.callee as any).property.type === 'Identifier' &&
(node.callee as any).property.name === 'extends'
) {
// Check arguments for all configs
node.arguments.forEach((arg: any) => {
if (arg.type === 'Literal' || arg.type === 'StringLiteral') {
if (arg.value === 'next/core-web-vitals') {
needsNextVitals = true
} else if (arg.value === 'next/typescript') {
needsNextTs = true
} else if (typeof arg.value === 'string') {
// Preserve other configs (non-Next.js or other Next.js variants)
otherConfigs.push(arg.value)
}
}
})
}
})
if (!needsNextVitals && !needsNextTs && otherConfigs.length === 0) {
console.warn(
prefixes.warn,
' No ESLint configs found in FlatCompat usage'
)
return false
}
// Always check file syntax to override package.json detection if needed
// This handles cases where package.json doesn't specify type but file uses ES modules
const hasESModuleSyntax =
root.find(j.ExportDefaultDeclaration).size() > 0 ||
root.find(j.ExportNamedDeclaration).size() > 0 ||
root.find(j.ImportDeclaration).size() > 0
const hasCommonJSSyntax =
root
.find(j.AssignmentExpression, {
left: {
type: 'MemberExpression',
object: { name: 'module' },
property: { name: 'exports' },
},
if (!needsNextVitals && !needsNextTs) {
console.log(' No Next.js configs found, but preserving other configs')
}
// Only remove FlatCompat setup if no other configs need it
if (otherConfigs.length === 0) {
// Remove FlatCompat imports and setup
root.find(j.ImportDeclaration).forEach((astPath) => {
const node = astPath.value
if (
node.source.value === '@eslint/eslintrc' ||
node.source.value === '@eslint/js'
) {
// Only remove FlatCompat-specific imports
j(astPath).remove()
}
// Leave path/url imports alone - they might be used elsewhere
})
// Remove only the compat variable - keep __dirname and __filename
root.find(j.VariableDeclaration).forEach((astPath) => {
const node = astPath.value
if (node.declarations) {
// Filter out only the compat variable
const filteredDeclarations = node.declarations.filter((decl: any) => {
if (decl && decl.id && decl.id.type === 'Identifier') {
return decl.id.name !== 'compat'
}
return true
})
.size() > 0
// Override package.json detection based on actual syntax
if (hasESModuleSyntax && !hasCommonJSSyntax) {
isCommonJS = false
} else if (hasCommonJSSyntax && !hasESModuleSyntax) {
isCommonJS = true
}
// If both or neither are found, keep the package.json-based detection
if (filteredDeclarations.length === 0) {
// Remove entire declaration if no declarations left
j(astPath).remove()
} else if (filteredDeclarations.length < node.declarations.length) {
// Update declaration with filtered declarations
node.declarations = filteredDeclarations
}
}
})
} else {
// For other extensions (.ts, .mts, .cts), assume based on extension
isCommonJS = configPath.endsWith('.cts')
console.log(' Preserving FlatCompat setup for other ESLint configs')
}
// Find the exported array
let exportedArray = null
let exportNode = null
if (isCommonJS) {
// Look for module.exports = [...]
const moduleExports = root.find(j.AssignmentExpression, {
left: {
type: 'MemberExpression',
object: { name: 'module' },
property: { name: 'exports' },
},
right: { type: 'ArrayExpression' },
})
// Add new imports after the eslint/config import
const imports = []
// Add imports in correct order: core-web-vitals first, then typescript
if (needsNextVitals) {
imports.push(
j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('nextCoreWebVitals'))],
j.literal('eslint-config-next/core-web-vitals')
)
)
}
if (moduleExports.size() > 0) {
exportNode = moduleExports.at(0)
exportedArray = exportNode.get('right')
if (needsNextTs) {
imports.push(
j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('nextTypescript'))],
j.literal('eslint-config-next/typescript')
)
)
}
// Find the eslint/config import and insert our imports after it
let eslintConfigImportPath = null
root.find(j.ImportDeclaration).forEach((astPath) => {
if (astPath.value.source.value === 'eslint/config') {
eslintConfigImportPath = astPath
}
})
// Insert imports after eslint/config import (or at beginning if not found)
if (eslintConfigImportPath) {
// Insert after the eslint/config import in correct order
for (let i = imports.length - 1; i >= 0; i--) {
eslintConfigImportPath.insertAfter(imports[i])
}
} else {
// Look for export default [...]
const defaultExports = root.find(j.ExportDefaultDeclaration, {
declaration: { type: 'ArrayExpression' },
})
// Fallback: insert at the beginning in correct order
const program = root.find(j.Program)
for (let i = imports.length - 1; i >= 0; i--) {
program.get('body', 0).insertBefore(imports[i])
}
}
if (defaultExports.size() > 0) {
exportNode = defaultExports.at(0)
exportedArray = exportNode.get('declaration')
} else {
// Look for const variable = [...]; export default variable
const defaultExportIdentifier = root.find(j.ExportDefaultDeclaration, {
declaration: { type: 'Identifier' },
// Replace FlatCompat extends with spread imports
root.find(j.SpreadElement).forEach((astPath) => {
const node = astPath.value
if (
node.argument.type === 'CallExpression' &&
node.argument.callee.type === 'MemberExpression' &&
node.argument.callee.object.type === 'Identifier' &&
node.argument.callee.object.name === 'compat' &&
node.argument.callee.property.type === 'Identifier' &&
node.argument.callee.property.name === 'extends'
) {
// Replace with spread of direct imports and preserve other configs
const replacements = []
node.argument.arguments.forEach((arg: any) => {
if (arg.type === 'Literal' || arg.type === 'StringLiteral') {
if (arg.value === 'next/core-web-vitals') {
replacements.push(
j.spreadElement(j.identifier('nextCoreWebVitals'))
)
} else if (arg.value === 'next/typescript') {
replacements.push(j.spreadElement(j.identifier('nextTypescript')))
} else if (typeof arg.value === 'string') {
// Preserve other configs as compat.extends() calls
replacements.push(
j.spreadElement(
j.callExpression(
j.memberExpression(
j.identifier('compat'),
j.identifier('extends')
),
[j.literal(arg.value)]
)
)
)
}
}
})
if (defaultExportIdentifier.size() > 0) {
const declarationNode = defaultExportIdentifier.at(0).get('declaration')
if (!declarationNode.value) {
return false
if (replacements.length > 0) {
// Replace the current spread element with multiple spread elements
const parent = astPath.parent
if (parent.value.type === 'ArrayExpression') {
const index = parent.value.elements.indexOf(node)
if (index !== -1) {
parent.value.elements.splice(index, 1, ...replacements)
}
}
}
}
})
// Also handle the case where extends is used as a property value (not spread)
root.find(j.ObjectExpression).forEach((astPath) => {
const objectNode = astPath.value
objectNode.properties?.forEach((prop: any) => {
if (
prop.type === 'ObjectProperty' &&
prop.key.type === 'Identifier' &&
prop.key.name === 'extends' &&
prop.value.type === 'CallExpression' &&
prop.value.callee.type === 'MemberExpression' &&
prop.value.callee.object.type === 'Identifier' &&
prop.value.callee.object.name === 'compat' &&
prop.value.callee.property.type === 'Identifier' &&
prop.value.callee.property.name === 'extends'
) {
// Replace with array of spread imports and preserve other configs
const replacements = []
prop.value.arguments.forEach((arg: any) => {
if (arg.type === 'Literal' || arg.type === 'StringLiteral') {
if (arg.value === 'next/core-web-vitals') {
replacements.push(
j.spreadElement(j.identifier('nextCoreWebVitals'))
)
} else if (arg.value === 'next/typescript') {
replacements.push(j.spreadElement(j.identifier('nextTypescript')))
} else if (typeof arg.value === 'string') {
// Preserve other configs as compat.extends() calls
replacements.push(
j.spreadElement(
j.callExpression(
j.memberExpression(
j.identifier('compat'),
j.identifier('extends')
),
[j.literal(arg.value)]
)
)
)
}
}
})
if (replacements.length > 0) {
// Replace the property value with an array of spreads
prop.value = j.arrayExpression(replacements)
}
}
})
})
// Generate the updated code
const updatedContent = root.toSource()
if (updatedContent !== configContent) {
// Validate the generated code by parsing it
try {
const validateJ = createParserFromPath(configPath)
validateJ(updatedContent) // This will throw if the syntax is invalid
} catch (parseError) {
console.error(
` Generated code has invalid syntax: ${parseError instanceof Error ? parseError.message : parseError}`
)
console.error(' Skipping update to prevent breaking the config file')
return false
}
// Create backup of original file
const backupPath = `${configPath}.backup-${Date.now()}`
try {
writeFileSync(backupPath, configContent)
} catch (backupError) {
console.warn(` Warning: Could not create backup file: ${backupError}`)
}
try {
writeFileSync(configPath, updatedContent)
console.log(
` Updated ${path.basename(configPath)} to use direct eslint-config-next imports`
)
// Remove backup on success
try {
if (existsSync(backupPath)) {
unlinkSync(backupPath)
}
} catch (cleanupError) {
console.warn(
` Warning: Could not remove backup file ${backupPath}: ${cleanupError}`
)
}
return true
} catch (error) {
console.error(` Error writing config file: ${error}`)
// Restore from backup on failure
try {
if (existsSync(backupPath)) {
writeFileSync(configPath, readFileSync(backupPath, 'utf8'))
console.log(' Restored original config from backup')
}
} catch (restoreError) {
console.error(` Error restoring backup: ${restoreError}`)
}
return false
}
}
return true
}
function updateExistingFlatConfig(
configPath: string,
isTypeScript: boolean = false
): boolean {
let configContent: string
try {
configContent = readFileSync(configPath, 'utf8')
} catch (error) {
console.error(` Error reading config file: ${error}`)
return false
}
// Check if Next.js configs are already imported directly
const hasNextVitals = configContent.includes(
'eslint-config-next/core-web-vitals'
)
const hasNextTs = configContent.includes('eslint-config-next/typescript')
const hasNextConfigs = hasNextVitals || hasNextTs
// Parse the file using jscodeshift
const j = createParserFromPath(configPath)
const root = j(configContent)
// Find the exported array - support different export patterns
let exportedArray = null
// Pattern 1: export default [...]
const directArrayExports = root.find(j.ExportDefaultDeclaration, {
declaration: { type: 'ArrayExpression' },
})
if (directArrayExports.size() > 0) {
exportedArray = directArrayExports.at(0).get('declaration')
} else {
// Pattern 2: const config = [...]; export default config
const defaultExportIdentifier = root.find(j.ExportDefaultDeclaration, {
declaration: { type: 'Identifier' },
})
if (defaultExportIdentifier.size() > 0) {
const declarationNode = defaultExportIdentifier.at(0).get('declaration')
if (declarationNode.value) {
const varName = declarationNode.value.name
const varDeclaration = root.find(j.VariableDeclarator, {
id: { name: varName },
......@@ -263,6 +468,28 @@ function updateExistingFlatConfig(
if (varDeclaration.size() > 0) {
exportedArray = varDeclaration.at(0).get('init')
} else {
// Pattern 3: defineConfig([...]) or similar wrapper function
const callDeclaration = root.find(j.VariableDeclarator, {
id: { name: varName },
init: { type: 'CallExpression' },
})
if (callDeclaration.size() > 0) {
const callExpression = callDeclaration.at(0).get('init')
if (
callExpression.value.arguments.length > 0 &&
callExpression.value.arguments[0].type === 'ArrayExpression'
) {
exportedArray = callExpression.get('arguments', 0)
} else {
console.warn(
prefixes.warn,
' Wrapper function does not have an array parameter. Manual migration required.'
)
return false
}
}
}
}
}
......@@ -271,286 +498,154 @@ function updateExistingFlatConfig(
if (!exportedArray) {
console.warn(
prefixes.warn,
' Config does not export an array. Manual migration required.'
)
console.warn(
prefixes.warn,
' ESLint flat configs must export an array of configuration objects.'
' Config does not export an array or supported pattern. Manual migration required.'
)
return false
}
// Check if FlatCompat is already imported
const hasFlatCompat = isCommonJS
? root
.find(j.CallExpression, {
callee: { name: 'require' },
arguments: [{ value: '@eslint/eslintrc' }],
})
.size() > 0
: root
.find(j.ImportDeclaration, {
source: { value: '@eslint/eslintrc' },
})
.size() > 0
// Add necessary imports if not present and if we're adding Next.js extends
if (!hasFlatCompat && !hasNextConfigs) {
if (isCommonJS) {
// Add CommonJS requires at the top
const firstNode = root.find(j.Program).get('body', 0)
const compatRequire = j.variableDeclaration('const', [
j.variableDeclarator(
j.objectPattern([
j.property(
'init',
j.identifier('FlatCompat'),
j.identifier('FlatCompat')
),
]),
j.callExpression(j.identifier('require'), [
j.literal('@eslint/eslintrc'),
])
),
])
const pathRequire = j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('path'),
j.callExpression(j.identifier('require'), [j.literal('path')])
),
])
const compatNew = j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('compat'),
j.newExpression(j.identifier('FlatCompat'), [
j.objectExpression([
j.property(
'init',
j.identifier('baseDirectory'),
j.identifier('__dirname')
),
]),
])
),
])
j(firstNode).insertBefore(compatRequire)
j(firstNode).insertBefore(pathRequire)
j(firstNode).insertBefore(compatNew)
} else {
// Add ES module imports
const firstImport = root.find(j.ImportDeclaration).at(0)
const insertPoint =
firstImport.size() > 0
? firstImport
: root.find(j.Program).get('body', 0)
const imports = [
j.importDeclaration(
[j.importSpecifier(j.identifier('dirname'))],
j.literal('path')
),
j.importDeclaration(
[j.importSpecifier(j.identifier('fileURLToPath'))],
j.literal('url')
),
j.importDeclaration(
[j.importSpecifier(j.identifier('FlatCompat'))],
j.literal('@eslint/eslintrc')
),
]
const setupVars = [
j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('__filename'),
j.callExpression(j.identifier('fileURLToPath'), [
j.memberExpression(
j.memberExpression(
j.identifier('import'),
j.identifier('meta')
),
j.identifier('url')
),
])
),
]),
j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('__dirname'),
j.callExpression(j.identifier('dirname'), [
j.identifier('__filename'),
])
),
]),
j.variableDeclaration('const', [
j.variableDeclarator(
j.identifier('compat'),
j.newExpression(j.identifier('FlatCompat'), [
j.objectExpression([
j.property(
'init',
j.identifier('baseDirectory'),
j.identifier('__dirname')
),
]),
])
),
]),
]
if (firstImport.size() > 0) {
// Insert after the last import
const lastImportPath = root.find(j.ImportDeclaration).at(-1).get()
if (!lastImportPath) {
// Fallback to inserting at the beginning
const fallbackInsertPoint = root.find(j.Program).get('body', 0)
imports.forEach((imp) => j(fallbackInsertPoint).insertBefore(imp))
setupVars.forEach((v) => j(fallbackInsertPoint).insertBefore(v))
} else {
imports.forEach((imp) => j(lastImportPath).insertAfter(imp))
setupVars.forEach((v) => j(lastImportPath).insertAfter(v))
}
} else {
// Insert at the beginning
imports.forEach((imp) => j(insertPoint).insertBefore(imp))
setupVars.forEach((v) => j(insertPoint).insertBefore(v))
}
}
// Add Next.js imports if not present
const program = root.find(j.Program)
const imports = []
if (!hasNextVitals) {
imports.push(
j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('nextCoreWebVitals'))],
j.literal('eslint-config-next/core-web-vitals')
)
)
}
// Create ignores configuration object
const ignoresConfig = j.objectExpression([
j.property(
'init',
j.identifier('ignores'),
j.arrayExpression([
j.literal('node_modules/**'),
j.literal('.next/**'),
j.literal('out/**'),
j.literal('build/**'),
j.literal('next-env.d.ts'),
])
),
])
// Only add Next.js extends if they're not already present
if (!hasNextConfigs) {
// Add Next.js configs to the array
const nextExtends = isTypeScript
? ['next/core-web-vitals', 'next/typescript']
: ['next/core-web-vitals']
const spreadElement = j.spreadElement(
j.callExpression(
j.memberExpression(j.identifier('compat'), j.identifier('extends')),
nextExtends.map((ext) => j.literal(ext))
if (!hasNextTs && isTypeScript) {
imports.push(
j.importDeclaration(
[j.importDefaultSpecifier(j.identifier('nextTypescript'))],
j.literal('eslint-config-next/typescript')
)
)
}
// Insert Next.js extends at the beginning of the array
if (!exportedArray.value.elements) {
exportedArray.value.elements = []
}
exportedArray.value.elements.unshift(spreadElement)
// Insert imports at the beginning in correct order
for (let i = imports.length - 1; i >= 0; i--) {
program.get('body', 0).insertBefore(imports[i])
}
// Check if ignores already exist in the config and merge if needed
let existingIgnoresIndex = -1
if (exportedArray.value.elements) {
for (let i = 0; i < exportedArray.value.elements.length; i++) {
const element = exportedArray.value.elements[i]
if (
element &&
element.type === 'ObjectExpression' &&
element.properties &&
element.properties.some(
(prop) =>
prop.type === 'Property' &&
prop.key &&
prop.key.type === 'Identifier' &&
prop.key.name === 'ignores'
)
) {
existingIgnoresIndex = i
break
}
}
// Add spread elements to config array if not already present
if (!exportedArray.value.elements) {
exportedArray.value.elements = []
}
if (existingIgnoresIndex === -1) {
// No existing ignores, add our own at appropriate position
const insertIndex = hasNextConfigs ? 0 : 1
exportedArray.value.elements.splice(insertIndex, 0, ignoresConfig)
} else {
// Merge with existing ignores
const existingIgnoresArr =
exportedArray.value.elements[existingIgnoresIndex]?.properties ?? []
const ignoresProp = existingIgnoresArr.find(
(prop) =>
prop.type === 'Property' &&
prop.key &&
prop.key.type === 'Identifier' &&
prop.key.name === 'ignores'
)
const spreadsToAdd = []
if (!hasNextVitals) {
spreadsToAdd.push(j.spreadElement(j.identifier('nextCoreWebVitals')))
}
if (!hasNextTs && isTypeScript) {
spreadsToAdd.push(j.spreadElement(j.identifier('nextTypescript')))
}
if (
ignoresProp &&
ignoresProp.value &&
ignoresProp.value.type === 'ArrayExpression'
) {
// Add our ignores to the existing array if they're not already there
const nextIgnores = [
'node_modules/**',
'.next/**',
'out/**',
'build/**',
'next-env.d.ts',
]
const existingIgnores = ignoresProp.value.elements
.map((el) => (el.type === 'Literal' ? el.value : null))
.filter(Boolean)
for (const ignore of nextIgnores) {
if (!existingIgnores.includes(ignore)) {
ignoresProp.value.elements.push(j.literal(ignore))
}
}
}
// Insert at the beginning of array in correct order
for (let i = spreadsToAdd.length - 1; i >= 0; i--) {
exportedArray.value.elements.unshift(spreadsToAdd[i])
}
// Add ignores config if not already present
const hasIgnores = exportedArray.value.elements.some(
(element) =>
element &&
element.type === 'ObjectExpression' &&
element.properties &&
element.properties.some(
(prop) =>
prop.type === 'ObjectProperty' &&
prop.key &&
prop.key.type === 'Identifier' &&
prop.key.name === 'ignores'
)
)
if (!hasIgnores) {
const ignoresConfig = j.objectExpression([
j.property(
'init',
j.identifier('ignores'),
j.arrayExpression([
j.literal('node_modules/**'),
j.literal('.next/**'),
j.literal('out/**'),
j.literal('build/**'),
j.literal('next-env.d.ts'),
])
),
])
exportedArray.value.elements.push(ignoresConfig)
}
// Generate the updated code
const updatedContent = root.toSource()
if (updatedContent !== configContent) {
// Validate the generated code by parsing it
try {
writeFileSync(configPath, updatedContent)
} catch (error) {
console.error(` Error writing config file: ${error}`)
const validateJ = createParserFromPath(configPath)
validateJ(updatedContent) // This will throw if the syntax is invalid
} catch (parseError) {
console.error(
` Generated code has invalid syntax: ${parseError instanceof Error ? parseError.message : parseError}`
)
console.error(' Skipping update to prevent breaking the config file')
return false
}
if (hasNextConfigs) {
console.log(
` Updated ${path.basename(configPath)} with Next.js ignores configuration`
)
} else {
// Create backup of original file
const backupPath = `${configPath}.backup-${Date.now()}`
try {
writeFileSync(backupPath, configContent)
} catch (backupError) {
console.warn(` Warning: Could not create backup file: ${backupError}`)
}
try {
writeFileSync(configPath, updatedContent)
console.log(
` Updated ${path.basename(configPath)} with Next.js ESLint configs`
` Updated ${path.basename(configPath)} with Next.js configurations`
)
// Remove backup on success
try {
if (existsSync(backupPath)) {
unlinkSync(backupPath)
}
} catch (cleanupError) {
console.warn(
` Warning: Could not remove backup file ${backupPath}: ${cleanupError}`
)
}
return true
} catch (error) {
console.error(` Error writing config file: ${error}`)
// Restore from backup on failure
try {
if (existsSync(backupPath)) {
writeFileSync(configPath, readFileSync(backupPath, 'utf8'))
console.log(' Restored original config from backup')
}
} catch (restoreError) {
console.error(` Error restoring backup: ${restoreError}`)
}
return false
}
return true
}
// If nothing changed but Next.js configs were already present, that's still success
// If nothing changed but configs are present, that's still success
if (hasNextConfigs) {
console.log(' Next.js ESLint configs already present in flat config')
return true
}
return false
return true
}
function updatePackageJsonScripts(packageJsonContent: string): {
......@@ -728,12 +823,13 @@ function updatePackageJsonScripts(packageJsonContent: string): {
needsUpdate = true
}
// Check if @eslint/eslintrc exists in either dependencies or devDependencies
if (
!packageJson.devDependencies['@eslint/eslintrc'] &&
!packageJson.dependencies?.['@eslint/eslintrc']
) {
packageJson.devDependencies['@eslint/eslintrc'] = '^3'
// Remove @eslint/eslintrc if it exists since we no longer use FlatCompat
if (packageJson.devDependencies?.['@eslint/eslintrc']) {
delete packageJson.devDependencies['@eslint/eslintrc']
needsUpdate = true
}
if (packageJson.dependencies?.['@eslint/eslintrc']) {
delete packageJson.dependencies['@eslint/eslintrc']
needsUpdate = true
}
......@@ -776,52 +872,8 @@ export default function transformer(
// Check for existing ESLint config
const existingConfig = findExistingEslintConfig(projectRoot)
if (existingConfig.exists) {
if (existingConfig.isFlat) {
// Try to update existing flat config
if (existingConfig.path) {
console.log(
` Found existing flat config: ${path.basename(existingConfig.path)}`
)
const updated = updateExistingFlatConfig(
existingConfig.path,
isTypeScript
)
if (!updated) {
console.log(
' Could not automatically update the existing flat config.'
)
console.log(
' Please manually ensure your ESLint config extends "next/core-web-vitals"'
)
if (isTypeScript) {
console.log(' and "next/typescript" for TypeScript projects.')
}
}
}
} else {
// Legacy config exists
if (existingConfig.path) {
console.log(
` Found legacy ESLint config: ${path.basename(existingConfig.path)}`
)
console.log(
' Legacy .eslintrc configs are not automatically migrated.'
)
console.log(
' Please migrate to flat config format (eslint.config.js) and ensure it extends:'
)
console.log(' - "next/core-web-vitals"')
if (isTypeScript) {
console.log(' - "next/typescript"')
}
console.log(
' Learn more: https://eslint.org/docs/latest/use/configure/migration-guide'
)
}
}
} else {
// If no existing ESLint config found, create a new one.
if (existingConfig.exists === false) {
// Create new ESLint flat config
const eslintConfigPath = path.join(projectRoot, 'eslint.config.mjs')
const template = isTypeScript
......@@ -834,9 +886,63 @@ export default function transformer(
} catch (error) {
console.error(' Error creating ESLint config:', error)
}
} else {
let eslintConfigFilename = path.basename(existingConfig.path)
let eslintConfigPath = existingConfig.path
// If legacy config found, run ESLint migration tool first. It will
// use FlatCompat, so will continue to migrate using Flat config format.
if (existingConfig.isLegacy && existingConfig.path) {
console.log(` Found legacy ESLint config: ${eslintConfigFilename}`)
// Run npx @eslint/migrate-config
const command = `npx @eslint/migrate-config ${existingConfig.path}`
console.log(` Running "${command}" to convert legacy config...`)
try {
execSync(command, {
cwd: projectRoot,
stdio: 'pipe',
})
// The migration tool creates eslint.config.mjs by default
const outputPath = path.join(projectRoot, 'eslint.config.mjs')
if (!existsSync(outputPath)) {
throw new Error(
`Failed to find the expected output file "${outputPath}" generated by the migration tool.`
)
}
// Use generated config will have FlatCompat, so continue to apply
// the next steps to it.
eslintConfigPath = outputPath
eslintConfigFilename = path.basename(eslintConfigPath)
} catch (cause) {
throw new Error(
`Failed to run "${command}" to migrate the legacy ESLint config "${eslintConfigFilename}".\n` +
`Please try the migration to Flat config manually.\n` +
`Learn more: https://eslint.org/docs/latest/use/configure/migration-guide`,
{ cause }
)
}
}
console.log(` Found existing ESLint Flat config: ${eslintConfigFilename}`)
// First try to replace FlatCompat usage if present
replaceFlatCompatInConfig(eslintConfigPath)
// Always try to update flat config with Next.js configurations
// regardless of whether FlatCompat was found
const updated = updateExistingFlatConfig(eslintConfigPath, isTypeScript)
if (!updated) {
console.log(' Could not automatically update the existing flat config.')
console.log(
' Please manually ensure your ESLint config includes the Next.js configurations'
)
}
}
// Update package.json
const packageJsonContent = readFileSync(packageJsonPath, 'utf8')
const result = updatePackageJsonScripts(packageJsonContent)
......
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