|
| 1 | +import * as fs from 'fs' |
| 2 | +import * as path from 'path' |
| 3 | + |
| 4 | +/** |
| 5 | + * To limit the risk of making the `inferTsConfig` run for a very long time, we |
| 6 | + * stop the file traversal after visiting this number of files. |
| 7 | + */ |
| 8 | +const maximumFileTraversalCount = 1_000 |
| 9 | + |
| 10 | +/** The TS config we use to index JavaScript files. */ |
| 11 | +export const allowJsConfig = '{"compilerOptions":{"allowJs":true}}' |
| 12 | + |
| 13 | +/** The TS config we use to index only TypeScript files. */ |
| 14 | +export const noJsConfig = '{}' |
| 15 | + |
| 16 | +/** |
| 17 | + * Returns the configuration that should be used for tsconfig.json in the provided path. |
| 18 | + * |
| 19 | + * If the directory contains at least one `*.{ts,tsx}` file then the config will be empty (`{}`). |
| 20 | + * If the directory doesn't contains one `*.{ts,tsx}` file then the config will |
| 21 | + */ |
| 22 | +export function inferTsConfig(projectPath: string): string { |
| 23 | + let hasTypeScriptFile = false |
| 24 | + let hasJavaScriptFile = false |
| 25 | + let visitedFileCount = 0 |
| 26 | + const visitPath = (directory: string): { stop: boolean } => { |
| 27 | + if (directory.endsWith('.ts') || directory.endsWith('.tsx')) { |
| 28 | + hasTypeScriptFile = true |
| 29 | + return { stop: true } |
| 30 | + } |
| 31 | + if (directory.endsWith('.js') || directory.endsWith('.jsx')) { |
| 32 | + hasJavaScriptFile = true |
| 33 | + } |
| 34 | + if (!fs.statSync(directory).isDirectory()) { |
| 35 | + return { stop: false } |
| 36 | + } |
| 37 | + for (const child of fs.readdirSync(directory)) { |
| 38 | + visitedFileCount++ |
| 39 | + if (visitedFileCount > maximumFileTraversalCount) { |
| 40 | + return { stop: true } |
| 41 | + } |
| 42 | + const fullPath = path.resolve(directory, child) |
| 43 | + const recursiveWalk = visitPath(fullPath) |
| 44 | + if (recursiveWalk.stop) { |
| 45 | + return recursiveWalk |
| 46 | + } |
| 47 | + } |
| 48 | + return { stop: false } |
| 49 | + } |
| 50 | + visitPath(projectPath) |
| 51 | + if (hasTypeScriptFile || !hasJavaScriptFile) { |
| 52 | + return noJsConfig |
| 53 | + } |
| 54 | + return allowJsConfig |
| 55 | +} |
0 commit comments