-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
no-extraneous-dependencies.js
227 lines (201 loc) · 6.72 KB
/
no-extraneous-dependencies.js
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import path from 'path'
import fs from 'fs'
import readPkgUp from 'read-pkg-up'
import minimatch from 'minimatch'
import resolve from 'eslint-module-utils/resolve'
import importType from '../core/importType'
import isStaticRequire from '../core/staticRequire'
import docsUrl from '../docsUrl'
function hasKeys(obj = {}) {
return Object.keys(obj).length > 0
}
function arrayOrKeys(arrayOrObject) {
return Array.isArray(arrayOrObject) ? arrayOrObject : Object.keys(arrayOrObject)
}
function extractDepFields(pkg) {
return {
dependencies: pkg.dependencies || {},
devDependencies: pkg.devDependencies || {},
optionalDependencies: pkg.optionalDependencies || {},
peerDependencies: pkg.peerDependencies || {},
// BundledDeps should be in the form of an array, but object notation is also supported by
// `npm`, so we convert it to an array if it is an object
bundledDependencies: arrayOrKeys(pkg.bundleDependencies || pkg.bundledDependencies || []),
}
}
function getDependencies(context, packageDir) {
let paths = []
try {
const packageContent = {
dependencies: {},
devDependencies: {},
optionalDependencies: {},
peerDependencies: {},
bundledDependencies: [],
}
if (packageDir && packageDir.length > 0) {
if (!Array.isArray(packageDir)) {
paths = [path.resolve(packageDir)]
} else {
paths = packageDir.map(dir => path.resolve(dir))
}
}
if (paths.length > 0) {
// use rule config to find package.json
paths.forEach(dir => {
const _packageContent = extractDepFields(
JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))
)
Object.keys(packageContent).forEach(depsKey =>
Object.assign(packageContent[depsKey], _packageContent[depsKey])
)
})
} else {
// use closest package.json
Object.assign(
packageContent,
extractDepFields(
readPkgUp.sync({cwd: context.getFilename(), normalize: false}).pkg
)
)
}
if (![
packageContent.dependencies,
packageContent.devDependencies,
packageContent.optionalDependencies,
packageContent.peerDependencies,
packageContent.bundledDependencies,
].some(hasKeys)) {
return null
}
return packageContent
} catch (e) {
if (paths.length > 0 && e.code === 'ENOENT') {
context.report({
message: 'The package.json file could not be found.',
loc: { line: 0, column: 0 },
})
}
if (e.name === 'JSONError' || e instanceof SyntaxError) {
context.report({
message: 'The package.json file could not be parsed: ' + e.message,
loc: { line: 0, column: 0 },
})
}
return null
}
}
function missingErrorMessage(packageName) {
return `'${packageName}' should be listed in the project's dependencies. ` +
`Run 'npm i -S ${packageName}' to add it`
}
function devDepErrorMessage(packageName) {
return `'${packageName}' should be listed in the project's dependencies, not devDependencies.`
}
function optDepErrorMessage(packageName) {
return `'${packageName}' should be listed in the project's dependencies, ` +
`not optionalDependencies.`
}
function reportIfMissing(context, deps, depsOptions, node, name) {
// Do not report when importing types
if (node.importKind === 'type') {
return
}
if (importType(name, context) !== 'external') {
return
}
const resolved = resolve(name, context)
if (!resolved) { return }
const splitName = name.split('/')
const packageName = splitName[0][0] === '@'
? splitName.slice(0, 2).join('/')
: splitName[0]
const isInDeps = deps.dependencies[packageName] !== undefined
const isInDevDeps = deps.devDependencies[packageName] !== undefined
const isInOptDeps = deps.optionalDependencies[packageName] !== undefined
const isInPeerDeps = deps.peerDependencies[packageName] !== undefined
const isInBundledDeps = deps.bundledDependencies.indexOf(packageName) !== -1
if (isInDeps ||
(depsOptions.allowDevDeps && isInDevDeps) ||
(depsOptions.allowPeerDeps && isInPeerDeps) ||
(depsOptions.allowOptDeps && isInOptDeps) ||
(depsOptions.allowBundledDeps && isInBundledDeps)
) {
return
}
if (isInDevDeps && !depsOptions.allowDevDeps) {
context.report(node, devDepErrorMessage(packageName))
return
}
if (isInOptDeps && !depsOptions.allowOptDeps) {
context.report(node, optDepErrorMessage(packageName))
return
}
context.report(node, missingErrorMessage(packageName))
}
function testConfig(config, filename) {
// Simplest configuration first, either a boolean or nothing.
if (typeof config === 'boolean' || typeof config === 'undefined') {
return config
}
// Array of globs.
return config.some(c => (
minimatch(filename, c) ||
minimatch(filename, path.join(process.cwd(), c))
))
}
module.exports = {
meta: {
type: 'problem',
docs: {
url: docsUrl('no-extraneous-dependencies'),
},
schema: [
{
'type': 'object',
'properties': {
'devDependencies': { 'type': ['boolean', 'array'] },
'optionalDependencies': { 'type': ['boolean', 'array'] },
'peerDependencies': { 'type': ['boolean', 'array'] },
'bundledDependencies': { 'type': ['boolean', 'array'] },
'packageDir': { 'type': ['string', 'array'] },
},
'additionalProperties': false,
},
],
},
create: function (context) {
const options = context.options[0] || {}
const filename = context.getFilename()
const deps = getDependencies(context, options.packageDir) || extractDepFields({})
const depsOptions = {
allowDevDeps: testConfig(options.devDependencies, filename) !== false,
allowOptDeps: testConfig(options.optionalDependencies, filename) !== false,
allowPeerDeps: testConfig(options.peerDependencies, filename) !== false,
allowBundledDeps: testConfig(options.bundledDependencies, filename) !== false,
}
// todo: use module visitor from module-utils core
return {
ImportDeclaration: function (node) {
if (node.source) {
reportIfMissing(context, deps, depsOptions, node, node.source.value)
}
},
ExportNamedDeclaration: function (node) {
if (node.source) {
reportIfMissing(context, deps, depsOptions, node, node.source.value)
}
},
ExportAllDeclaration: function (node) {
if (node.source) {
reportIfMissing(context, deps, depsOptions, node, node.source.value)
}
},
CallExpression: function handleRequires(node) {
if (isStaticRequire(node)) {
reportIfMissing(context, deps, depsOptions, node, node.arguments[0].value)
}
},
}
},
}