/
files-property.ts
61 lines (52 loc) · 1.91 KB
/
files-property.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import * as path from 'path';
import * as fs from 'fs';
import * as globby from 'globby';
import {Context, Diagnostic} from '../interfaces';
import {getJSONPropertyPosition} from '../utils';
/**
* Rule which enforces the typings file to be present in the `files` list in `package.json`.
*
* @param context - The context object.
* @returns A list of custom diagnostics.
*/
export default (context: Context): Diagnostic[] => {
const {pkg, typingsFile} = context;
const packageFiles = pkg.files;
if (!Array.isArray(packageFiles)) {
return [];
}
const normalizedTypingsFile = path.normalize(typingsFile);
const patternProcessedPackageFiles = processGitIgnoreStylePatterns(packageFiles);
const normalizedFiles = globby.sync(patternProcessedPackageFiles, {cwd: context.cwd}).map(path.normalize);
if (normalizedFiles.includes(normalizedTypingsFile)) {
return [];
}
const packageJsonFullPath = path.join(context.cwd, 'package.json');
const content = fs.readFileSync(packageJsonFullPath, 'utf8');
return [
{
fileName: packageJsonFullPath,
message: `TypeScript type definition \`${normalizedTypingsFile}\` is not part of the \`files\` list.`,
severity: 'error',
...getJSONPropertyPosition(content, 'files')
}
];
};
function processGitIgnoreStylePatterns(patterns: string[]): string[] {
const processedPatterns = patterns
.map(pattern => {
const [negatePatternMatch] = pattern.match(/^!+/) || [];
const negationMarkersCount = negatePatternMatch ? negatePatternMatch.length : 0;
return [
pattern
.slice(negationMarkersCount)
// Strip off `/` from the start of the pattern
.replace(/^\/+/, ''),
negationMarkersCount % 2 === 0
] as const;
})
// Only include pattern if it has an even count of negation markers
.filter(([, hasEvenCountOfNegationMarkers]) => hasEvenCountOfNegationMarkers)
.map(([processedPattern]) => processedPattern);
return [...new Set(processedPatterns)];
}