Unverified Commit a7ae54d7 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

refactor(typescript): extract preflight functions (#13510)

This pull request refactors our TypeScript preflight check in preparation for dropping the `fork-ts-checker-webpack-plugin` plugin.

This will make reviewing the subsequent PR much easier.

---

There is no behavior change, so the existing test should cover this adequately.
parent 44a65a5e
export function getOxfordCommaList(items: string[]): string {
return items
.map(
(v, index, { length }) =>
(index > 0
? index === length - 1
? length > 2
? ', and '
: ' and '
: ', '
: '') + v
)
.join('')
}
export class FatalTypeScriptError extends Error {}
import chalk from 'next/dist/compiled/chalk'
import os from 'os'
import path from 'path'
import { FatalTypeScriptError } from './FatalTypeScriptError'
export async function getTypeScriptConfiguration(
ts: typeof import('typescript'),
tsConfigPath: string
): Promise<import('typescript').ParsedCommandLine> {
try {
const formatDiagnosticsHost: import('typescript').FormatDiagnosticsHost = {
getCanonicalFileName: (fileName: string) => fileName,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => os.EOL,
}
const { config, error } = ts.readConfigFile(tsConfigPath, ts.sys.readFile)
if (error) {
throw new FatalTypeScriptError(
ts.formatDiagnostic(error, formatDiagnosticsHost)
)
}
const result = ts.parseJsonConfigFileContent(
config,
ts.sys,
path.dirname(tsConfigPath)
)
if (result.errors) {
result.errors = result.errors.filter(
({ code }) =>
// No inputs were found in config file
code !== 18003
)
}
if (result.errors?.length) {
throw new FatalTypeScriptError(
ts.formatDiagnostic(result.errors[0], formatDiagnosticsHost)
)
}
return result
} catch (err) {
if (err?.name === 'SyntaxError') {
const reason = '\n' + (err?.message ?? '')
throw new FatalTypeScriptError(
chalk.red.bold(
'Could not parse',
chalk.cyan('tsconfig.json') +
'.' +
' Please make sure it contains syntactically correct JSON.'
) + reason
)
}
throw err
}
}
import { promises as fs } from 'fs'
import path from 'path'
import { fileExists } from '../file-exists'
import { recursiveReadDir } from '../recursive-readdir'
export type TypeScriptIntent = { firstTimeSetup: boolean }
export async function getTypeScriptIntent(
baseDir: string,
pagesDir: string
): Promise<TypeScriptIntent | false> {
const tsConfigPath = path.join(baseDir, 'tsconfig.json')
// The integration turns on if we find a `tsconfig.json` in the user's
// project.
const hasTypeScriptConfiguration = await fileExists(tsConfigPath)
if (hasTypeScriptConfiguration) {
const content = await fs.readFile(tsConfigPath, { encoding: 'utf8' }).then(
(content) => content.trim(),
() => null
)
return { firstTimeSetup: content === '' || content === '{}' }
}
// Next.js also offers a friendly setup mode that bootstraps a TypeScript
// project for the user when we detect TypeScript files. So, we need to check
// the `pages/` directory for a TypeScript file.
// Checking all directories is too slow, so this is a happy medium.
const typescriptFiles = await recursiveReadDir(
pagesDir,
/.*\.(ts|tsx)$/,
/(node_modules|.*\.d\.ts)/
)
if (typescriptFiles.length) {
return { firstTimeSetup: true }
}
return false
}
import chalk from 'next/dist/compiled/chalk'
import path from 'path'
import { fileExists } from '../file-exists'
import { getOxfordCommaList } from '../oxford-comma-list'
import { resolveRequest } from '../resolve-request'
import { FatalTypeScriptError } from './FatalTypeScriptError'
const requiredPackages = [
{ file: 'typescript', pkg: 'typescript' },
{ file: '@types/react/index.d.ts', pkg: '@types/react' },
{ file: '@types/node/index.d.ts', pkg: '@types/node' },
]
export type NecessaryDependencies = {
resolvedTypeScript: string
}
export async function hasNecessaryDependencies(
baseDir: string
): Promise<NecessaryDependencies> {
let resolutions = new Map<string, string>()
const missingPackages = requiredPackages.filter((p) => {
try {
resolutions.set(p.pkg, resolveRequest(p.file, path.join(baseDir, '/')))
return false
} catch (_) {
return true
}
})
if (missingPackages.length < 1) {
return { resolvedTypeScript: resolutions.get('typescript')! }
}
const packagesHuman = getOxfordCommaList(missingPackages.map((p) => p.pkg))
const packagesCli = missingPackages.map((p) => p.pkg).join(' ')
const yarnLockFile = path.join(baseDir, 'yarn.lock')
const isYarn = await fileExists(yarnLockFile).catch(() => false)
throw new FatalTypeScriptError(
chalk.bold.red(
`It looks like you're trying to use TypeScript but do not have the required package(s) installed.`
) +
'\n\n' +
chalk.bold(`Please install ${chalk.bold(packagesHuman)} by running:`) +
'\n\n' +
`\t${chalk.bold.cyan(
(isYarn ? 'yarn add --dev' : 'npm install --save-dev') +
' ' +
packagesCli
)}` +
'\n\n' +
chalk.bold(
'If you are not trying to use TypeScript, please remove the ' +
chalk.cyan('tsconfig.json') +
' file from your package root (and any TypeScript files in your pages directory).'
) +
'\n'
)
}
import { promises as fs } from 'fs'
import os from 'os'
import path from 'path'
import { fileExists } from '../file-exists'
export async function writeAppTypeDeclarations(baseDir: string): Promise<void> {
// Reference `next` types
const appTypeDeclarations = path.join(baseDir, 'next-env.d.ts')
const hasAppTypeDeclarations = await fileExists(appTypeDeclarations)
if (!hasAppTypeDeclarations) {
await fs.writeFile(
appTypeDeclarations,
'/// <reference types="next" />' +
os.EOL +
'/// <reference types="next/types/global" />' +
os.EOL
)
}
}
import { promises as fs } from 'fs'
import chalk from 'next/dist/compiled/chalk'
import * as CommentJson from 'next/dist/compiled/comment-json'
import os from 'os'
import { getTypeScriptConfiguration } from './getTypeScriptConfiguration'
type DesiredCompilerOptionsShape = {
[key: string]:
| { suggested: any }
| { parsedValue?: any; value: any; reason: string }
}
function getDesiredCompilerOptions(
ts: typeof import('typescript')
): DesiredCompilerOptionsShape {
const o: DesiredCompilerOptionsShape = {
// These are suggested values and will be set when not present in the
// tsconfig.json
target: { suggested: 'es5' },
lib: { suggested: ['dom', 'dom.iterable', 'esnext'] },
allowJs: { suggested: true },
skipLibCheck: { suggested: true },
strict: { suggested: false },
forceConsistentCasingInFileNames: { suggested: true },
noEmit: { suggested: true },
// These values are required and cannot be changed by the user
// Keep this in sync with the webpack config
// 'parsedValue' matches the output value from ts.parseJsonConfigFileContent()
esModuleInterop: {
value: true,
reason: 'requirement for babel',
},
module: {
parsedValue: ts.ModuleKind.ESNext,
value: 'esnext',
reason: 'for dynamic import() support',
},
moduleResolution: {
parsedValue: ts.ModuleResolutionKind.NodeJs,
value: 'node',
reason: 'to match webpack resolution',
},
resolveJsonModule: { value: true, reason: 'to match webpack resolution' },
isolatedModules: {
value: true,
reason: 'requirement for babel',
},
jsx: {
parsedValue: ts.JsxEmit.Preserve,
value: 'preserve',
reason: 'next.js implements its own optimized jsx transform',
},
}
return o
}
export async function writeConfigurationDefaults(
ts: typeof import('typescript'),
tsConfigPath: string,
isFirstTimeSetup: boolean
): Promise<void> {
if (isFirstTimeSetup) {
await fs.writeFile(tsConfigPath, '{}' + os.EOL)
}
const desiredCompilerOptions = getDesiredCompilerOptions(ts)
const effectiveConfiguration = await getTypeScriptConfiguration(
ts,
tsConfigPath
)
const userTsConfigContent = await fs.readFile(tsConfigPath, {
encoding: 'utf8',
})
const userTsConfig = CommentJson.parse(userTsConfigContent)
if (userTsConfig.compilerOptions == null) {
userTsConfig.compilerOptions = {}
isFirstTimeSetup = true
}
const suggestedActions: string[] = []
const requiredActions: string[] = []
for (const optionKey of Object.keys(desiredCompilerOptions)) {
const check = desiredCompilerOptions[optionKey]
if ('suggested' in check) {
if (!(optionKey in effectiveConfiguration.options)) {
userTsConfig.compilerOptions[optionKey] = check.suggested
suggestedActions.push(
chalk.cyan(optionKey) + ' was set to ' + chalk.bold(check.suggested)
)
}
} else if ('value' in check) {
const ev = effectiveConfiguration.options[optionKey]
if (
!('parsedValue' in check
? check.parsedValue === ev
: check.value === ev)
) {
userTsConfig.compilerOptions[optionKey] = check.value
requiredActions.push(
chalk.cyan(optionKey) +
' was set to ' +
chalk.bold(check.value) +
` (${check.reason})`
)
}
} else {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = check
}
}
if (userTsConfig.include == null) {
userTsConfig.include = ['next-env.d.ts', '**/*.ts', '**/*.tsx']
suggestedActions.push(
chalk.cyan('include') +
' was set to ' +
chalk.bold(`['next-env.d.ts', '**/*.ts', '**/*.tsx']`)
)
}
if (userTsConfig.exclude == null) {
userTsConfig.exclude = ['node_modules']
suggestedActions.push(
chalk.cyan('exclude') + ' was set to ' + chalk.bold(`['node_modules']`)
)
}
if (suggestedActions.length < 1 && requiredActions.length < 1) {
return
}
await fs.writeFile(
tsConfigPath,
CommentJson.stringify(userTsConfig, null, 2) + os.EOL
)
if (isFirstTimeSetup) {
console.log(
chalk.green(
`We detected TypeScript in your project and created a ${chalk.bold(
'tsconfig.json'
)} file for you.`
) + '\n'
)
return
}
console.log(
chalk.green(
`We detected TypeScript in your project and reconfigured your ${chalk.bold(
'tsconfig.json'
)} file for you.`
) + '\n'
)
if (suggestedActions.length) {
console.log(
`The following suggested values were added to your ${chalk.cyan(
'tsconfig.json'
)}. These values ${chalk.bold(
'can be changed'
)} to fit your project's needs:\n`
)
suggestedActions.forEach((action) => console.log(`\t- ${action}`))
console.log('')
}
if (requiredActions.length) {
console.log(
`The following ${chalk.bold(
'mandatory changes'
)} were made to your ${chalk.cyan('tsconfig.json')}:\n`
)
requiredActions.forEach((action) => console.log(`\t- ${action}`))
console.log('')
}
}
This diff is collapsed.
...@@ -44,13 +44,13 @@ describe('tsconfig.json verifier', () => { ...@@ -44,13 +44,13 @@ describe('tsconfig.json verifier', () => {
\\"isolatedModules\\": true, \\"isolatedModules\\": true,
\\"jsx\\": \\"preserve\\" \\"jsx\\": \\"preserve\\"
}, },
\\"exclude\\": [
\\"node_modules\\"
],
\\"include\\": [ \\"include\\": [
\\"next-env.d.ts\\", \\"next-env.d.ts\\",
\\"**/*.ts\\", \\"**/*.ts\\",
\\"**/*.tsx\\" \\"**/*.tsx\\"
],
\\"exclude\\": [
\\"node_modules\\"
] ]
} }
" "
...@@ -88,13 +88,13 @@ describe('tsconfig.json verifier', () => { ...@@ -88,13 +88,13 @@ describe('tsconfig.json verifier', () => {
\\"isolatedModules\\": true, \\"isolatedModules\\": true,
\\"jsx\\": \\"preserve\\" \\"jsx\\": \\"preserve\\"
}, },
\\"exclude\\": [
\\"node_modules\\"
],
\\"include\\": [ \\"include\\": [
\\"next-env.d.ts\\", \\"next-env.d.ts\\",
\\"**/*.ts\\", \\"**/*.ts\\",
\\"**/*.tsx\\" \\"**/*.tsx\\"
],
\\"exclude\\": [
\\"node_modules\\"
] ]
} }
" "
...@@ -155,13 +155,13 @@ describe('tsconfig.json verifier', () => { ...@@ -155,13 +155,13 @@ describe('tsconfig.json verifier', () => {
} }
// in-object comment 2 // in-object comment 2
, ,
\\"exclude\\": [
\\"node_modules\\"
],
\\"include\\": [ \\"include\\": [
\\"next-env.d.ts\\", \\"next-env.d.ts\\",
\\"**/*.ts\\", \\"**/*.ts\\",
\\"**/*.tsx\\" \\"**/*.tsx\\"
],
\\"exclude\\": [
\\"node_modules\\"
] ]
} }
// end comment // end comment
......
/* eslint-env jest */
import { getOxfordCommaList } from 'next/dist/lib/oxford-comma-list'
describe('oxford-comma-list', () => {
test('empty array', () => {
expect(getOxfordCommaList([])).toMatchInlineSnapshot(`""`)
})
test('single item array', () => {
expect(getOxfordCommaList(['apples'])).toMatchInlineSnapshot(`"apples"`)
})
test('two item array', () => {
expect(
getOxfordCommaList(['apples', 'strawberries'])
).toMatchInlineSnapshot(`"apples and strawberries"`)
})
test('three item array', () => {
expect(
getOxfordCommaList(['apples', 'strawberries', 'blueberries'])
).toMatchInlineSnapshot(`"apples, strawberries, and blueberries"`)
})
test('four item array', () => {
expect(getOxfordCommaList(['1', '2', '3', '4'])).toMatchInlineSnapshot(
`"1, 2, 3, and 4"`
)
})
test('five item array', () => {
expect(getOxfordCommaList(['1', '2', '3', '4', '5'])).toMatchInlineSnapshot(
`"1, 2, 3, 4, and 5"`
)
})
})
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