94 lines
4.3 KiB
JavaScript
94 lines
4.3 KiB
JavaScript
'use strict';
|
||||
|
|
// 生成 eslint.browser-globals.js:列出 public/index.html 按顺序加载的每个经典脚本在全局作用域声明的名字,
|
|||
|
|
// 供 ESLint 把它们作为其他脚本的全局变量:const 为 readonly,let/var/function/class 及属性赋值为 writable
|
|||
|
|
// (其他脚本确实会给 let 变量重新赋值,如 tab、currentOrder)。脚本改动顶层声明后重新运行:node scripts/gen-browser-globals.js
|
|||
|
|
// 收集范围:顶层 function/const/let/var/class,以及 UMD 写法 root.X=…(root 为传入 globalThis 的立即执行函数参数)
|
|||
|
|
// 与 window.X=…/globalThis.X=… 的赋值。
|
|||
|
|
const fs = require('fs');
|
|||
|
|
const path = require('path');
|
|||
|
|
const { Linter } = require('eslint');
|
|||
|
|
const prettier = require('prettier');
|
|||
|
|
|
|||
|
|
const APP = path.join(__dirname, '..');
|
|||
|
|
const OUTPUT = path.join(APP, 'eslint.browser-globals.js');
|
|||
|
|
|
|||
|
|
function scriptOrder() {
|
|||
|
|
const html = fs.readFileSync(path.join(APP, 'public/index.html'), 'utf8');
|
|||
|
|
return [...html.matchAll(/<script\s+src="\/([^"]+\.js)"/g)].map(match => 'public/' + match[1]);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function isGlobalRootParam(identifier, ancestors) {
|
|||
|
|
for (let i = ancestors.length - 1; i >= 0; i--) {
|
|||
|
|
const fn = ancestors[i];
|
|||
|
|
if (fn.type !== 'FunctionExpression' && fn.type !== 'ArrowFunctionExpression') continue;
|
|||
|
|
const index = fn.params.findIndex(param => param.type === 'Identifier' && param.name === identifier.name);
|
|||
|
|
if (index < 0) continue;
|
|||
|
|
const call = ancestors[i - 1];
|
|||
|
|
if (!call || call.type !== 'CallExpression' || call.callee !== fn) return false;
|
|||
|
|
const argument = call.arguments[index];
|
|||
|
|
return !!argument && /globalThis/.test(sourceText(argument));
|
|||
|
|
}
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
let currentSource = '';
|
|||
|
|
const sourceText = node => currentSource.slice(node.range[0], node.range[1]);
|
|||
|
|
|
|||
|
|
function declaredNames(file) {
|
|||
|
|
const code = fs.readFileSync(path.join(APP, file), 'utf8');
|
|||
|
|
currentSource = code;
|
|||
|
|
const names = new Map();
|
|||
|
|
const collector = {
|
|||
|
|
create(context) {
|
|||
|
|
const sourceCode = context.sourceCode;
|
|||
|
|
return {
|
|||
|
|
AssignmentExpression(node) {
|
|||
|
|
const left = node.left;
|
|||
|
|
if (left.type !== 'MemberExpression' || left.computed || left.object.type !== 'Identifier') return;
|
|||
|
|
const owner = left.object.name;
|
|||
|
|
if (owner === 'window' || owner === 'globalThis') names.set(left.property.name, 'writable');
|
|||
|
|
else if (owner === 'root' && isGlobalRootParam(left.object, sourceCode.getAncestors(node)))
|
|||
|
|
names.set(left.property.name, 'writable');
|
|||
|
|
},
|
|||
|
|
'Program:exit'(node) {
|
|||
|
|
for (const variable of sourceCode.getScope(node).variables) {
|
|||
|
|
if (!variable.defs.length) continue;
|
|||
|
|
const constant = variable.defs.every(def => def.type === 'Variable' && def.parent.kind === 'const');
|
|||
|
|
names.set(variable.name, constant ? 'readonly' : 'writable');
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
};
|
|||
|
|
},
|
|||
|
|
};
|
|||
|
|
const linter = new Linter({ configType: 'flat' });
|
|||
|
|
const messages = linter.verify(code, {
|
|||
|
|
files: ['**/*.js'],
|
|||
|
|
languageOptions: { ecmaVersion: 'latest', sourceType: 'script' },
|
|||
|
|
plugins: { gen: { rules: { collect: collector } } },
|
|||
|
|
rules: { 'gen/collect': 'error' },
|
|||
|
|
});
|
|||
|
|
const fatal = messages.filter(message => message.fatal);
|
|||
|
|
if (fatal.length) throw new Error(file + ': ' + fatal.map(message => message.message).join('; '));
|
|||
|
|
return Object.fromEntries([...names].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
async function main() {
|
|||
|
|
const files = {};
|
|||
|
|
for (const file of scriptOrder()) files[file] = declaredNames(file);
|
|||
|
|
const body =
|
|||
|
|
"'use strict';\n" +
|
|||
|
|
'// 由 scripts/gen-browser-globals.js 生成,请勿手改;public 脚本顶层声明变化后重新运行该脚本。\n' +
|
|||
|
|
'// 键为 public/index.html 中按加载顺序排列的脚本,值为该脚本声明到全局作用域的名字及可写性。\n' +
|
|||
|
|
'module.exports = ' +
|
|||
|
|
JSON.stringify(files, null, 2) +
|
|||
|
|
';\n';
|
|||
|
|
const options = (await prettier.resolveConfig(OUTPUT)) || {};
|
|||
|
|
fs.writeFileSync(OUTPUT, await prettier.format(body, { ...options, filepath: OUTPUT }));
|
|||
|
|
const total = Object.values(files).reduce((sum, names) => sum + Object.keys(names).length, 0);
|
|||
|
|
console.log(`已写入 ${path.relative(APP, OUTPUT)}:${Object.keys(files).length} 个脚本,${total} 个全局名字`);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
main().catch(error => {
|
|||
|
|
console.error(error);
|
|||
|
|
process.exit(1);
|
|||
|
|
});
|