#!/usr/bin/env node /** * Harness: 检查插件是否符合规范 * - 检查插件入口文件是否存在 * - 检查插件是否有正确的 package.json * - 检查插件是否使用了正确的导入路径 * - 检查插件是否有测试文件 * - 检查 plugins/ 下公开插件的市场元数据(zhin.metadata 的 descriptionI18n / category、 * author、有信息量的 keywords),插件市场直接展示这些字段 * - 官方插件页面的 UI 门禁(ADR 0063 D19):zhin plugin check 第 1–6 条,门禁名单 * scripts/plugin-ui-gate.json 中 gated 的插件违规即失败,pending 的只出报告;摘要列出所有豁免 */ import * as fs from 'node:fs'; import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { PLUGIN_CATEGORIES, informativeKeywords, packageAuthorName, } from './lib/plugin-marketplace.mjs'; import { evaluateStaticUiGate, formatUiGateSummary, listOfficialPluginsWithPages, loadPageChecks, OFFICIAL_PLUGIN_ROOTS, readUiGate, validateUiGate, writeStepSummary, } from './lib/plugin-ui-gate.mjs'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(__dirname, '..'); const pluginDirs = OFFICIAL_PLUGIN_ROOTS; /** 非插件目录(共享代码、工具文件夹) */ const SKIP_PLUGIN_NAMES = new Set(['common']); const violations = []; /** * 检查单个插件目录 * @param {string} pluginPath - 插件目录路径 * @param {string} pluginName - 插件名称 */ function checkPlugin(pluginPath, pluginName) { const relativePath = path.relative(repoRoot, pluginPath); // 检查 package.json 是否存在 const packageJsonPath = path.join(pluginPath, 'package.json'); if (!fs.existsSync(packageJsonPath)) { violations.push({ plugin: relativePath, issue: 'Missing package.json', }); return; } // 读取 package.json let packageJson; try { const content = fs.readFileSync(packageJsonPath, 'utf8'); packageJson = JSON.parse(content); } catch (error) { violations.push({ plugin: relativePath, issue: `Invalid package.json: ${error.message}`, }); return; } // 检查是否有 name 字段 if (!packageJson.name) { violations.push({ plugin: relativePath, issue: 'Missing "name" field in package.json', }); } if (!packageJson.private && packageJson.zhin?.type === 'plugin') { const runtimeEntry = packageJson.zhin.entry; const exportsEntry = packageJson.exports && typeof packageJson.exports === 'object' && !Array.isArray(packageJson.exports) && Object.hasOwn(packageJson.exports, './zhin'); // An entry-less Plugin (neither zhin.entry nor exports["./zhin"]) has no runtime entry to publish. const entryless = runtimeEntry === undefined && !exportsEntry; if (!entryless && (typeof runtimeEntry !== 'string' || !/\.[cm]?js$/u.test(runtimeEntry))) { violations.push({ plugin: relativePath, issue: 'Published Plugin Runtime entry must be compiled JavaScript', }); } const publishedFiles = Array.isArray(packageJson.files) ? packageJson.files : []; if (typeof runtimeEntry === 'string' && !publishedFiles.includes(runtimeEntry.replace(/^\.\//u, ''))) { violations.push({ plugin: relativePath, issue: `Runtime entry is missing from files: ${runtimeEntry}`, }); } if (!packageJson.scripts?.prepack?.includes('build-plugin-runtime-entries.mjs')) { violations.push({ plugin: relativePath, issue: 'Prepack script does not emit Plugin Runtime JavaScript entries', }); } if (!packageJson.scripts?.postpack?.includes('build-plugin-runtime-entries.mjs --clean')) { violations.push({ plugin: relativePath, issue: 'Postpack script does not clean generated Plugin Runtime JavaScript entries', }); } } if (!packageJson.private && packageJson.zhin?.type === 'plugin' && relativePath.startsWith('plugins')) { for (const issue of marketplaceMetadataIssues(packageJson)) { violations.push({ plugin: relativePath, issue }); } } // 检查是否有 main 或 exports 字段 if (!packageJson.main && !packageJson.exports) { violations.push({ plugin: relativePath, issue: 'Missing "main" or "exports" field in package.json', }); } // 检查 src 目录是否存在 const srcDir = path.join(pluginPath, 'src'); if (!fs.existsSync(srcDir)) { violations.push({ plugin: relativePath, issue: 'Missing src/ directory', }); return; } // 检查入口文件是否存在 const entryFile = packageJson.main ? path.join(pluginPath, packageJson.main.replace('./lib/', './src/').replace('.js', '.ts')) : path.join(srcDir, 'index.ts'); // Accept both .ts and .tsx entry files (common for JSX-rendering plugins) const entryFileTsx = entryFile.replace(/\.ts$/, '.tsx'); if (!fs.existsSync(entryFile) && !fs.existsSync(entryFileTsx)) { violations.push({ plugin: relativePath, issue: `Entry file not found: ${path.relative(repoRoot, entryFile)}`, }); } // 检查是否有测试文件 const testsDir = path.join(pluginPath, 'tests'); const hasTests = fs.existsSync(testsDir) && fs.readdirSync(testsDir).some(f => f.endsWith('.test.ts')); if (!hasTests) { violations.push({ plugin: relativePath, issue: 'No test files found (tests/*.test.ts)', }); } // 检查是否有 README const readmePath = path.join(pluginPath, 'README.md'); if (!fs.existsSync(readmePath)) { violations.push({ plugin: relativePath, issue: 'Missing README.md', }); } } /** Release bot accounts that must never appear as a package author. */ const BOT_AUTHORS = /github[- ]actions|\[bot\]/iu; /** * 插件市场展示的字段:本地化描述与分类(zhin.metadata)、作者、有信息量的 keywords。 * @param {Record} packageJson * @returns {string[]} */ function marketplaceMetadataIssues(packageJson) { const issues = []; const metadata = packageJson.zhin?.metadata ?? {}; for (const locale of ['zh-CN', 'en']) { const text = metadata.descriptionI18n?.[locale]; if (typeof text !== 'string' || !text.trim()) { issues.push(`zhin.metadata.descriptionI18n["${locale}"] is required for the plugin market`); } } if (!PLUGIN_CATEGORIES.includes(metadata.category)) { issues.push(`zhin.metadata.category must be one of ${PLUGIN_CATEGORIES.join(', ')}`); } const author = packageAuthorName(packageJson); if (!author || BOT_AUTHORS.test(author)) { issues.push('author must name the maintainer ({ "name", "url" }), not a release bot'); } if (packageJson.author && typeof packageJson.author === 'object' && 'email' in packageJson.author) { issues.push('author must not publish an email address; use { "name", "url" }'); } const keywords = informativeKeywords(packageJson.keywords); if (keywords.length < 3 || keywords.length > 6) { issues.push(`keywords need 3–6 informative entries besides zhin / zhin.js / bot (found ${keywords.length})`); } return issues; } /** * 扫描插件目录 * @param {string} dir - 要扫描的目录 */ function shouldCheckPlugin(pluginPath) { if (SKIP_PLUGIN_NAMES.has(path.basename(pluginPath))) return false; const hasPackageJson = fs.existsSync(path.join(pluginPath, 'package.json')); const hasSrc = fs.existsSync(path.join(pluginPath, 'src')); // 仅校验有意图的插件目录(含 package.json 或 src/);跳过 lib 残留等 return hasPackageJson || hasSrc; } function scanPluginDir(dir) { const absPath = path.join(repoRoot, dir); if (!fs.existsSync(absPath)) return; for (const name of fs.readdirSync(absPath)) { const pluginPath = path.join(absPath, name); const stat = fs.statSync(pluginPath); if (stat.isDirectory() && !name.startsWith('.') && name !== 'node_modules') { if (!shouldCheckPlugin(pluginPath)) continue; checkPlugin(pluginPath, name); } } } // 扫描所有插件目录 for (const dir of pluginDirs) { scanPluginDir(dir); } // 官方插件页面 UI 门禁(ADR 0063 D19 / D20) const uiGate = readUiGate(repoRoot); for (const problem of uiGate.problems) violations.push({ plugin: 'scripts/plugin-ui-gate.json', issue: problem }); const pluginsWithPages = listOfficialPluginsWithPages(repoRoot); for (const { plugin, message } of validateUiGate(uiGate.gate, pluginsWithPages)) { violations.push({ plugin, issue: `UI gate: ${message}` }); } const { checkPluginPageUi, formatPageUiFinding } = await loadPageChecks(repoRoot); const uiReports = new Map(pluginsWithPages.map((plugin) => [plugin, checkPluginPageUi(path.join(repoRoot, plugin))])); const uiResult = evaluateStaticUiGate(uiGate.gate, uiReports, formatPageUiFinding); for (const { plugin, message } of uiResult.errors) violations.push({ plugin, issue: `UI gate (ADR 0063): ${message}` }); writeStepSummary(formatUiGateSummary('官方插件页面 UI(zhin plugin check 第 1–6 条)', uiResult)); const uiReportedByPlugin = new Map(); for (const { plugin } of uiResult.reported) uiReportedByPlugin.set(plugin, (uiReportedByPlugin.get(plugin) ?? 0) + 1); console.log(`Plugin UI gate: ${uiGate.gate.gated.length} gated, ${uiGate.gate.pending.length} pending, ${uiResult.exemptions.length + uiResult.auditExemptions.length} exemption(s).`); for (const [plugin, count] of uiReportedByPlugin) console.log(` report only (pending): ${plugin}: ${count} finding(s)`); for (const exemption of uiResult.exemptions) { console.log(` exemption: ${exemption.plugin} ${exemption.file}:${exemption.line} rule ${exemption.rules.join(',')}: ${exemption.reason}`); } for (const exemption of uiResult.auditExemptions) { console.log(` audit exemption: ${exemption.plugin} ${exemption.file}:${exemption.line} ${exemption.check}: ${exemption.reason}`); } if (violations.length) { console.error('Harness plugin spec check: FAILED\n'); for (const v of violations) { console.error(` ${v.plugin}: ${v.issue}`); } console.error('\nPlugins must follow the standard structure. See docs/authoring/ for details.\n'); process.exit(1); } console.log('Harness plugin spec check: OK (all plugins follow the spec).');