check-main-package-js-usage.mjs
8.8 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
/**
* @file 检查分包是否把仅供分包使用的 JavaScript 依赖留在主包根目录。
* 只分析静态 import/export-from/require;微信运行时动态路径不属于本门禁范围。
*/
import {
existsSync,
readFileSync,
readdirSync,
statSync
} from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { parse } from '@babel/parser'
const defaultProjectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const ALWAYS_IGNORED_DIRECTORIES = new Set(['.git', 'miniprogram_npm', 'node_modules'])
/**
* 把路径统一为仓库相对 POSIX 格式,便于跨平台比较。
* @param {string} projectRoot 项目绝对路径。
* @param {string} absolutePath 文件绝对路径。
* @returns {string} 仓库相对路径。
*/
function toProjectRelative(projectRoot, absolutePath) {
return path.relative(projectRoot, absolutePath).replaceAll('\\', '/')
}
/**
* 读取微信上传忽略配置,避免把测试、脚本和权威生成源当作运行时代码。
* @param {string} projectRoot 项目绝对路径。
* @returns {Array<{value: string, type: 'file'|'folder'}>} 规范化忽略项。
*/
function readUploadIgnores(projectRoot) {
const configPath = path.join(projectRoot, 'project.config.json')
if (!existsSync(configPath)) return []
const config = JSON.parse(readFileSync(configPath, 'utf8'))
return (config.packOptions?.ignore || [])
.filter(item => item && typeof item.value === 'string')
.map(item => ({
value: item.value.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, ''),
type: item.type === 'file' ? 'file' : 'folder'
}))
}
/**
* 判断文件是否被上传配置排除。
* @param {string} relativePath 仓库相对路径。
* @param {Array<{value: string, type: 'file'|'folder'}>} ignores 忽略项。
* @returns {boolean} 是否忽略。
*/
function isUploadIgnored(relativePath, ignores) {
const pathSegments = relativePath.split('/')
if (pathSegments.some(segment => ALWAYS_IGNORED_DIRECTORIES.has(segment))) return true
return ignores.some(item =>
item.type === 'file'
? relativePath === item.value
: relativePath === item.value || relativePath.startsWith(`${item.value}/`)
)
}
/**
* 收集参与上传的 JavaScript 文件。
* @param {string} projectRoot 项目绝对路径。
* @param {Array<{value: string, type: 'file'|'folder'}>} ignores 忽略项。
* @param {string} [directory] 当前扫描目录。
* @returns {string[]} JavaScript 文件绝对路径。
*/
function listRuntimeJavaScript(projectRoot, ignores, directory = projectRoot) {
return readdirSync(directory, { withFileTypes: true })
.sort((left, right) => left.name.localeCompare(right.name))
.flatMap(entry => {
const absolutePath = path.join(directory, entry.name)
const relativePath = toProjectRelative(projectRoot, absolutePath)
if (isUploadIgnored(relativePath, ignores)) return []
if (entry.isDirectory()) return listRuntimeJavaScript(projectRoot, ignores, absolutePath)
if (entry.isFile() && /\.(?:cjs|js|mjs)$/.test(entry.name)) return [absolutePath]
return []
})
}
/**
* 递归提取 AST 中的静态模块路径。
* @param {unknown} node Babel AST 节点。
* @param {string[]} sources 收集结果。
* @returns {void}
*/
function collectStaticModuleSources(node, sources) {
if (!node || typeof node !== 'object') return
if (
(node.type === 'ImportDeclaration' ||
node.type === 'ExportNamedDeclaration' ||
node.type === 'ExportAllDeclaration') &&
typeof node.source?.value === 'string'
) {
sources.push(node.source.value)
}
if (
node.type === 'CallExpression' &&
(node.callee?.name === 'require' || node.callee?.type === 'Import') &&
node.arguments?.[0]?.type === 'StringLiteral'
) {
sources.push(node.arguments[0].value)
}
if (node.type === 'ImportExpression' && node.source?.type === 'StringLiteral') {
sources.push(node.source.value)
}
for (const [key, value] of Object.entries(node)) {
if (['comments', 'end', 'extra', 'loc', 'start'].includes(key)) continue
if (Array.isArray(value)) {
for (const child of value) collectStaticModuleSources(child, sources)
} else {
collectStaticModuleSources(value, sources)
}
}
}
/**
* 解析本地模块路径;第三方包和无法静态解析的路径返回 null。
* @param {string} projectRoot 项目绝对路径。
* @param {string} importerPath 引用方绝对路径。
* @param {string} source import/require 源字符串。
* @returns {string|null} 已存在模块的绝对路径。
*/
function resolveLocalModule(projectRoot, importerPath, source) {
let basePath
if (source.startsWith('~/')) {
basePath = path.resolve(projectRoot, source.slice(2))
} else if (source.startsWith('/')) {
basePath = path.resolve(projectRoot, source.slice(1))
} else if (source.startsWith('.')) {
basePath = path.resolve(path.dirname(importerPath), source)
} else {
return null
}
const relativeBase = path.relative(projectRoot, basePath)
if (relativeBase === '..' || relativeBase.startsWith(`..${path.sep}`)) return null
const candidates = [
basePath,
`${basePath}.js`,
`${basePath}.mjs`,
`${basePath}.cjs`,
path.join(basePath, 'index.js'),
path.join(basePath, 'index.mjs'),
path.join(basePath, 'index.cjs')
]
return candidates.find(candidate => existsSync(candidate) && statSync(candidate).isFile()) || null
}
/**
* 找出“由分包直接引用、但没有任何主包运行时代码直接引用”的根目录 JS。
* 这类文件会被跨包引用拉进主包,并触发微信开发者工具的主包未使用 JS 提示。
*
* @param {{projectRoot?: string}} [options] 检查选项。
* @returns {Array<{target: string, importers: string[], packages: string[]}>} 违规列表。
*/
export function findSubpackageOnlyRootJavaScriptImports({
projectRoot = defaultProjectRoot
} = {}) {
const absoluteRoot = path.resolve(projectRoot)
const appConfig = JSON.parse(readFileSync(path.join(absoluteRoot, 'app.json'), 'utf8'))
const packageRoots = (appConfig.subPackages || appConfig.subpackages || [])
.map(item => item.root?.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, ''))
.filter(Boolean)
.sort((left, right) => right.length - left.length)
const ignores = readUploadIgnores(absoluteRoot)
const inbound = new Map()
/** @param {string} relativePath 仓库相对路径。 @returns {string|null} 所属分包根。 */
const getPackageRoot = relativePath =>
packageRoots.find(root => relativePath === root || relativePath.startsWith(`${root}/`)) || null
for (const importerPath of listRuntimeJavaScript(absoluteRoot, ignores)) {
const importer = toProjectRelative(absoluteRoot, importerPath)
const ast = parse(readFileSync(importerPath, 'utf8'), {
sourceType: 'unambiguous',
plugins: [
'classProperties',
'dynamicImport',
'nullishCoalescingOperator',
'objectRestSpread',
'optionalChaining'
]
})
const sources = []
collectStaticModuleSources(ast, sources)
for (const source of new Set(sources)) {
const targetPath = resolveLocalModule(absoluteRoot, importerPath, source)
if (!targetPath || !/\.(?:cjs|js|mjs)$/.test(targetPath)) continue
const target = toProjectRelative(absoluteRoot, targetPath)
if (!inbound.has(target)) inbound.set(target, [])
inbound.get(target).push({ importer, packageRoot: getPackageRoot(importer) })
}
}
return [...inbound.entries()]
.filter(([target]) => !getPackageRoot(target))
.map(([target, importRecords]) => {
const subpackageImports = importRecords.filter(record => record.packageRoot)
const mainImports = importRecords.filter(record => !record.packageRoot)
return { target, subpackageImports, mainImports }
})
.filter(item => item.subpackageImports.length > 0 && item.mainImports.length === 0)
.map(item => ({
target: item.target,
importers: [...new Set(item.subpackageImports.map(record => record.importer))].sort(),
packages: [...new Set(item.subpackageImports.map(record => record.packageRoot))].sort()
}))
.sort((left, right) => left.target.localeCompare(right.target))
}
const isCommandLine =
process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url
if (isCommandLine) {
const violations = findSubpackageOnlyRootJavaScriptImports()
if (violations.length === 0) {
console.log('No subpackage-only JavaScript imports remain in the main package.')
} else {
console.error('Subpackage-only JavaScript imports found in the main package:')
for (const violation of violations) {
console.error(`- ${violation.target}`)
for (const importer of violation.importers) console.error(` <- ${importer}`)
}
process.exitCode = 1
}
}