-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathknip.js
More file actions
254 lines (208 loc) · 8.91 KB
/
knip.js
File metadata and controls
254 lines (208 loc) · 8.91 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
const fs = require('fs')
const path = require('path')
const { glob } = require('glob')
function _extractPackageInfo (packageJsonPath) {
const pkgInfo = JSON.parse(fs.readFileSync(packageJsonPath).toString())
return {
devDependencies: pkgInfo.devDependencies || {},
dependencies: pkgInfo.dependencies || {},
name: pkgInfo.name,
}
}
function hasDependency (packageJsonPath, dependency) {
const { dependencies, devDependencies } = _extractPackageInfo(packageJsonPath)
return Object.keys(dependencies).includes(dependency) || Object.keys(devDependencies).includes(dependency)
}
function hasPath (packageJsonPath, relativePath) {
const packageDir = path.dirname(packageJsonPath)
const files = glob.sync(relativePath, {
cwd: packageDir,
ignore: ['**/node_modules/**'],
})
return Boolean(files.length)
}
function getMajorRequirement (packageJsonPath, depName) {
const { dependencies, devDependencies } = _extractPackageInfo(packageJsonPath)
if (!dependencies[depName] && !devDependencies[depName]) return null
const requirement = dependencies[depName] || devDependencies[depName]
const majorPart = requirement.split('.')[0]
const clearedPart = majorPart.replace(/\D+/g, '')
const majorVersion = parseInt(clearedPart)
return Number.isNaN(majorVersion) ? null : majorVersion
}
function isApp (packageJsonPath) {
const packageDir = path.dirname(packageJsonPath)
const parentDir = path.dirname(packageDir)
return path.basename(parentDir) === 'apps'
}
function isKSApp (packageJsonPath) {
return isApp(packageJsonPath) && hasDependency(packageJsonPath, '@open-condo/keystone')
}
function getPackageDir (packageJsonPath) {
return path.dirname(path.relative(__dirname, packageJsonPath))
}
function hasName (packageJsonPath, packageName) {
const { name } = _extractPackageInfo(packageJsonPath)
return name === packageName
}
function isFileContains (packageJsonPath, filePath, searchContent) {
// NOTE: controlled environment
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
const combinedPath = path.join(path.dirname(packageJsonPath), filePath)
if (!fs.existsSync(combinedPath)) return false
const content = fs.readFileSync(combinedPath).toString()
return content.includes(searchContent)
}
function _arrayMerge (base, addition) {
if (Array.isArray(base)) {
if (Array.isArray(addition)) {
return [...new Set([...base, ...addition])]
}
return base
}
return addition
}
/**
* @param {Array<import('knip').KnipConfig['workspaces']>} configs
*/
function mergeWorkspaceConfigs (...configs) {
/** @type import('knip').KnipConfig['workspaces'] */
const mergedConfig = {}
for (const combinedConfig of configs) {
for (const [appPath, packageConfig] of Object.entries(combinedConfig)) {
if (!mergedConfig[appPath]) {
mergedConfig[appPath] = packageConfig
} else {
const existingConfig = mergedConfig[appPath]
mergedConfig[appPath] = {
...existingConfig,
...packageConfig,
entry: _arrayMerge(existingConfig.entry, packageConfig.entry),
ignoreDependencies: _arrayMerge(existingConfig.ignoreDependencies, packageConfig.ignoreDependencies),
}
}
}
}
return mergedConfig
}
async function config () {
const allPackagesPaths = await glob('{apps,packages}/*/package.json', {
ignore: ['**/node_modules/**'],
absolute: true,
})
/** @type import('knip').KnipConfig['workspaces'] */
const staticWorkspaces = {
'.': {
entry: ['bin/**/*.js'],
ignoreDependencies: [/commitlint/],
},
'apps/insurance': {
ignoreDependencies: ['@graphql-codegen/typescript'],
},
'apps/resident-app': {
entry: ['domains/common/utils/sw.ts', 'domains/telegram-bot/utils/bot.js' ],
},
'packages/icons': {
ignoreDependencies: ['@svgr/plugin-svgo', '@svgr/plugin-prettier', '@svgr/plugin-jsx'],
},
'packages/keystone': {
entry: ['**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx}'],
},
'packages/ui': {
ignoreDependencies: [
/storybook/,
'style-loader',
'chromatic',
'token-transformer',
],
webpack: {
config: [
'webpack.common.js',
'webpack.dev.js',
'webpack.prod.js',
],
},
},
}
/** @type import('knip').KnipConfig['workspaces'] */
const dynamicWorkspaces = Object.fromEntries(allPackagesPaths.map(packageJsonPath => {
/** @type {import('knip').KnipConfig['workspaces'][string] & { entry: Array<string> }} */
const packageConfig = {
entry: [],
ignoreDependencies: [],
}
// bin scripts entry point
if (isApp(packageJsonPath) && hasPath(packageJsonPath, './bin')) {
packageConfig.entry.push('bin/**/*.js')
}
// KS app entry points
if (isKSApp(packageJsonPath)) {
packageConfig.entry.push('index.js', 'admin-ui/index.js')
}
// Telegram bot packages
if (hasPath(packageJsonPath, './domains/*/scenes')) {
packageConfig.ignoreDependencies.push('telegraf', 'telegraf-i18n', 'graphql-tag', 'express', 'express-session', 'express-pino-logger', 'openid-client', 'uuid', 'jsonwebtoken')
}
// Jest-specific packages
if (hasDependency(packageJsonPath, 'jest')) {
if (hasPath(packageJsonPath, 'jest.config.js') && hasDependency(packageJsonPath, 'jest-jasmine2')) {
packageConfig.ignoreDependencies.push('jest-jasmine2')
}
if (hasDependency(packageJsonPath, '@types/jest') && (hasPath(packageJsonPath, 'tsconfig.json') || hasDependency(packageJsonPath, 'typescript'))) {
packageConfig.ignoreDependencies.push('@types/jest')
}
}
// typescript packages with modern exports
// TODO: make check more strict by reading package.json exports fields
if (!isApp(packageJsonPath) && hasPath(packageJsonPath, 'tsconfig.json') && hasPath(packageJsonPath, 'src')) {
packageConfig.entry.push('src/**/*.ts')
}
// Ignore-loader, currently used only for billing legacy (require.resolve)
if (isApp(packageJsonPath) && hasDependency(packageJsonPath, 'ignore-loader')) {
// TODO: clean raw-loader from unused apps
// if (hasPath(packageJsonPath, 'lang/**/*.njk')) {
packageConfig.ignoreDependencies.push('ignore-loader')
// }
}
// old Next.js apps requires webpack4 not to compete with webpack5 from UI-kit
if (hasDependency(packageJsonPath, 'webpack') && hasDependency(packageJsonPath, 'next')) {
if (getMajorRequirement(packageJsonPath, 'next') <= 9) {
packageConfig.ignoreDependencies.push('webpack')
}
}
// apollo uses rollup + babel to build
// TODO: think about migrating to zero-config tsup
if (hasName(packageJsonPath, '@open-condo/apollo') && hasPath(packageJsonPath, 'rollup.config.mjs')) {
for (const depName of ['@babel/preset-react', 'babel-core', 'babel-loader']) {
if (hasDependency(packageJsonPath, depName)) {
packageConfig.ignoreDependencies.push(depName)
}
}
}
// icons / ui kit uses babel + webpack to build
if (
(hasName(packageJsonPath, '@open-condo/icons') || hasName(packageJsonPath, '@open-condo/ui')) &&
hasPath(packageJsonPath, '.babelrc')
) {
if (hasDependency(packageJsonPath, 'babel')) {
packageConfig.ignoreDependencies.push('babel')
}
}
// webpack-cli required for libs built with webpack
if (hasDependency(packageJsonPath, 'webpack-cli') && hasPath(packageJsonPath, 'webpack.*.js')) {
packageConfig.ignoreDependencies.push('webpack-cli')
}
// ts-node is required for some GQL-codegen
if (isApp(packageJsonPath) && hasDependency(packageJsonPath, 'ts-node') && hasDependency(packageJsonPath, 'next') && isFileContains(packageJsonPath, 'codegen.ts', 'ts-node/register')) {
packageConfig.ignoreDependencies.push('ts-node')
}
return [getPackageDir(packageJsonPath), packageConfig]
}))
/** @type {import('knip').KnipConfig} */
const mergedConfig = {
include: ['dependencies'],
workspaces: mergeWorkspaceConfigs(dynamicWorkspaces, staticWorkspaces),
}
return mergedConfig
}
module.exports = config