chore: initialize Reims-Go plugin market and add official.lang.zh-tw v1.0.0

This commit is contained in:
千川白浪 committed 2026-11-30 01:57:13 -07:00
commit 7ad21f30cd
10 files changed
+915

No files matched your search

+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env node
/**
* Reims-Go Plugin Market validator & index builder.
*
* Usage:
* node scripts/build-index.mjs [--check] [--out-dir dist] [--reims-bin ./reims-go] [--report pr-report.md]
*
* Zero third-party npm dependencies (Node 20+).
*/
import crypto from 'node:crypto'
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import zlib from 'node:zlib'
const RE_ID = /^[a-z0-9][a-z0-9_-]*(\.[a-z0-9][a-z0-9_-]*)+$/
const RE_SHA256 = /^[0-9a-f]{64}$/
const ALLOWED_CHANNELS = new Set(['stable', 'alpha'])
const ALLOWED_TRUST = new Set(['official', 'verified', 'community'])
const ALLOWED_KINDS = new Set(['theme', 'locale', 'driver', 'tool', 'template', 'runtime'])
const MAX_ZIP_BYTES = 256 * 1024 * 1024 // 256 MiB
function parseArgs(argv) {
const opts = {
checkOnly: false,
outDir: 'dist',
reimsBin: '',
reportPath: '',
}
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (a === '--check') opts.checkOnly = true
else if (a === '--out-dir' && i + 1 < argv.length) opts.outDir = argv[++i]
else if (a === '--reims-bin' && i + 1 < argv.length) opts.reimsBin = argv[++i]
else if (a === '--report' && i + 1 < argv.length) opts.reportPath = argv[++i]
else throw new Error(`Unknown argument: ${a}`)
}
return opts
}
function readJSON(filePath) {
return JSON.parse(fs.readFileSync(filePath, 'utf8'))
}
function normalizeLocalized(val) {
if (!val) return undefined
if (typeof val === 'string') {
const s = val.trim()
return s ? { 'zh-CN': s, 'en-US': s } : undefined
}
if (typeof val === 'object') {
const out = {}
for (const [k, v] of Object.entries(val)) {
if (typeof v === 'string' && v.trim()) out[k] = v.trim()
}
return Object.keys(out).length > 0 ? out : undefined
}
return undefined
}
/**
* Pure-Node ZIP reader to extract a single entry (plugin.json) without external tools.
*/
function readFileFromZipBuffer(buf, targetName) {
// Locate End of Central Directory (EOCD) signature 0x06054b50 from end of buffer.
let eocdOffset = -1
const minPos = Math.max(0, buf.length - 65557)
for (let pos = buf.length - 22; pos >= minPos; pos--) {
if (buf.readUInt32LE(pos) === 0x06054b50) {
eocdOffset = pos
break
}
}
if (eocdOffset < 0) throw new Error('Invalid ZIP archive: EOCD not found')
const totalEntries = buf.readUInt16LE(eocdOffset + 10)
let cdOffset = buf.readUInt32LE(eocdOffset + 16)
for (let i = 0; i < totalEntries; i++) {
if (buf.readUInt32LE(cdOffset) !== 0x02014b50) {
throw new Error('Invalid ZIP central directory header')
}
const method = buf.readUInt16LE(cdOffset + 10)
const compSize = buf.readUInt32LE(cdOffset + 20)
const nameLen = buf.readUInt16LE(cdOffset + 28)
const extraLen = buf.readUInt16LE(cdOffset + 30)
const commentLen = buf.readUInt16LE(cdOffset + 32)
const localHeaderOffset = buf.readUInt32LE(cdOffset + 42)
const name = buf.subarray(cdOffset + 46, cdOffset + 46 + nameLen).toString('utf8')
if (name === targetName || name === `./${targetName}`) {
if (buf.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
throw new Error('Invalid ZIP local file header')
}
const lNameLen = buf.readUInt16LE(localHeaderOffset + 26)
const lExtraLen = buf.readUInt16LE(localHeaderOffset + 28)
const dataStart = localHeaderOffset + 30 + lNameLen + lExtraLen
const compData = buf.subarray(dataStart, dataStart + compSize)
if (method === 0) return compData
if (method === 8) return zlib.inflateRawSync(compData)
throw new Error(`Unsupported ZIP compression method ${method} for ${targetName}`)
}
cdOffset += 46 + nameLen + extraLen + commentLen
}
throw new Error(`ZIP archive is missing ${targetName}`)
}
async function downloadBuffer(url) {
const headers = { 'User-Agent': 'reims-go-plugins-ci' }
if (process.env.GITHUB_TOKEN && url.includes('github.com')) {
headers.Authorization = `Bearer ${process.env.GITHUB_TOKEN}`
}
const resp = await fetch(url, { headers, redirect: 'follow' })
if (!resp.ok) {
throw new Error(`HTTP ${resp.status} downloading ${url}`)
}
const chunks = []
let total = 0
for await (const chunk of resp.body) {
total += chunk.length
if (total > MAX_ZIP_BYTES) {
throw new Error(`Archive exceeds ${MAX_ZIP_BYTES} byte limit`)
}
chunks.push(chunk)
}
return Buffer.concat(chunks)
}
function runDoctor(reimsBin, zipPath) {
const proc = spawnSync(reimsBin, ['plugin', 'doctor', '--json', zipPath], {
encoding: 'utf8',
maxBuffer: 8 * 1024 * 1024,
})
if (proc.error) {
throw new Error(`Failed to execute ${reimsBin}: ${proc.error.message}`)
}
const raw = (proc.stdout || '').trim()
if (!raw) {
throw new Error(`reims-go plugin doctor produced empty output (exit=${proc.status}): ${proc.stderr}`)
}
const report = JSON.parse(raw)
return { exitCode: proc.status, report }
}
function validateWithdrawn(withdrawnDoc) {
if (!withdrawnDoc || withdrawnDoc.schema !== 1 || !Array.isArray(withdrawnDoc.withdrawn)) {
throw new Error('withdrawn.json must have {"schema": 1, "withdrawn": [...]}')
}
const ids = new Set()
const out = []
for (const w of withdrawnDoc.withdrawn) {
if (!w || typeof w.id !== 'string' || !RE_ID.test(w.id)) {
throw new Error(`Invalid withdrawn plugin id: ${JSON.stringify(w?.id)}`)
}
if (ids.has(w.id)) throw new Error(`Duplicate withdrawn id: ${w.id}`)
ids.add(w.id)
const reason = normalizeLocalized(w.reason)
if (!reason) throw new Error(`Withdrawn entry ${w.id} is missing reason`)
const item = { id: w.id, reason }
if (w.instead_id) {
if (!RE_ID.test(w.instead_id)) throw new Error(`Invalid instead_id for ${w.id}: ${w.instead_id}`)
item.instead_id = w.instead_id
}
if (w.instead_name) item.instead_name = String(w.instead_name)
if (w.withdrawn_at) item.withdrawn_at = String(w.withdrawn_at)
out.push(item)
}
return { ids, list: out }
}
async function main() {
const opts = parseArgs(process.argv.slice(2))
const rootDir = process.cwd()
const registryDoc = readJSON(path.join(rootDir, 'registry.json'))
const withdrawnDoc = readJSON(path.join(rootDir, 'withdrawn.json'))
if (!registryDoc || registryDoc.schema !== 1 || !Array.isArray(registryDoc.plugins)) {
throw new Error('registry.json must have {"schema": 1, "plugins": [...]}')
}
const { ids: withdrawnIDs, list: withdrawnList } = validateWithdrawn(withdrawnDoc)
const seenKey = new Set()
const marketPlugins = []
const reportRows = []
const errors = []
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'reims-plugins-build-'))
try {
for (const entry of registryDoc.plugins) {
const label = `${entry?.id || '<missing-id>'}@${entry?.version || '<missing-version>'}`
try {
if (!entry || typeof entry.id !== 'string' || !RE_ID.test(entry.id)) {
throw new Error(`invalid plugin id ${JSON.stringify(entry?.id)}`)
}
if (withdrawnIDs.has(entry.id)) {
throw new Error(`plugin ${entry.id} is listed in withdrawn.json and must be removed from registry.json`)
}
if (typeof entry.version !== 'string' || !entry.version.trim()) {
throw new Error('missing version')
}
const channel = (entry.channel || 'stable').toLowerCase()
if (!ALLOWED_CHANNELS.has(channel)) throw new Error(`invalid channel ${JSON.stringify(channel)}`)
const key = `${entry.id}:${channel}`
if (seenKey.has(key)) throw new Error(`duplicate registry entry for ${key}`)
seenKey.add(key)
const kind = (entry.kind || '').toLowerCase()
if (!ALLOWED_KINDS.has(kind)) throw new Error(`invalid kind ${JSON.stringify(kind)}`)
const trust = (entry.trust || 'community').toLowerCase()
if (!ALLOWED_TRUST.has(trust)) throw new Error(`invalid trust ${JSON.stringify(trust)}`)
const sha256 = String(entry.sha256 || '').toLowerCase().trim()
if (!RE_SHA256.test(sha256)) throw new Error('sha256 must be a 64-character lowercase hex string')
let downloadURL = String(entry.download_url || '').trim()
if (!downloadURL) {
if (!entry.repo || !entry.asset) {
throw new Error('either download_url or (repo + asset) must be specified')
}
const tag = entry.tag || `v${entry.version}`
downloadURL = `https://github.com/${entry.repo}/releases/download/${tag}/${entry.asset}`
}
const parsedURL = new URL(downloadURL)
if (parsedURL.protocol !== 'https:') {
throw new Error(`download_url must use https:// (got ${downloadURL})`)
}
const buf = await downloadBuffer(downloadURL)
const gotSum = crypto.createHash('sha256').update(buf).digest('hex')
if (gotSum !== sha256) {
throw new Error(`SHA-256 mismatch: registry=${sha256}, actual=${gotSum}`)
}
const manifestRaw = readFileFromZipBuffer(buf, 'plugin.json')
const manifest = JSON.parse(manifestRaw.toString('utf8'))
if (manifest.id !== entry.id) {
throw new Error(`anti-swap id mismatch: registry=${entry.id}, plugin.json=${manifest.id}`)
}
if (manifest.version !== entry.version) {
throw new Error(`anti-swap version mismatch: registry=${entry.version}, plugin.json=${manifest.version}`)
}
let scanReport = null
if (opts.reimsBin) {
const zipPath = path.join(tmpRoot, `${entry.id}-${entry.version}.zip`)
fs.writeFileSync(zipPath, buf)
const { report } = runDoctor(opts.reimsBin, zipPath)
scanReport = report
if (report.hard_blocked) {
const reasons = (report.hard_findings || [])
.map((f) => `[${f.check}] ${f.target ? `${f.target}: ` : ''}${f.message}`)
.join('; ')
throw new Error(`static security gate blocked: ${reasons}`)
}
}
const tier = scanReport?.tier || (manifest.entry?.sidecar ? 'L3' : manifest.entry?.panelDir ? 'L4' : 'L1')
const effectiveTrust = trust === 'official' || trust === 'verified' ? trust : 'community'
const marketItem = {
id: manifest.id,
version: manifest.version,
name: normalizeLocalized(manifest.name) || { 'en-US': manifest.id },
description: normalizeLocalized(manifest.description) || { 'en-US': '' },
publisher: manifest.publisher || (entry.repo ? entry.repo.split('/')[0] : 'community'),
license: manifest.license || '',
channel,
trust: effectiveTrust,
kind,
tier,
homepage: manifest.homepage || (entry.repo ? `https://github.com/${entry.repo}` : undefined),
readme_url: entry.readme_url || (entry.repo ? `https://github.com/${entry.repo}#readme` : undefined),
engines: manifest.engines || {},
platforms: Array.isArray(manifest.platforms) ? manifest.platforms : undefined,
permissions: Array.isArray(manifest.permissions) ? manifest.permissions : undefined,
download_url: downloadURL,
sha256: gotSum,
size_bytes: buf.length,
changelog: normalizeLocalized(entry.changelog),
tags: Array.isArray(entry.tags) ? entry.tags : undefined,
updated_at: entry.updated_at || new Date().toISOString(),
}
// Strip undefined fields for clean JSON output.
for (const k of Object.keys(marketItem)) {
if (marketItem[k] === undefined) delete marketItem[k]
}
marketPlugins.push(marketItem)
reportRows.push({
status: 'PASS',
id: marketItem.id,
version: marketItem.version,
tier,
trust: effectiveTrust,
sizeBytes: buf.length,
sha256: gotSum,
capabilities: scanReport?.capabilities || [],
executables: scanReport?.executables || [],
pending: scanReport?.pending_findings || [],
})
} catch (err) {
errors.push(`${label}: ${err.message}`)
reportRows.push({
status: 'FAIL',
id: entry?.id || 'unknown',
version: entry?.version || 'unknown',
error: err.message,
})
}
}
} finally {
fs.rmSync(tmpRoot, { recursive: true, force: true })
}
// Generate human-readable Markdown review summary for PR comments & workflow logs.
const mdLines = [
'## Reims-Go Plugin Market Gate Report',
'',
`- **Entries checked**: ${registryDoc.plugins.length}`,
`- **Withdrawn entries**: ${withdrawnList.length}`,
`- **Result**: ${errors.length === 0 ? 'PASS' : `BLOCKED (${errors.length} error(s))`}`,
'',
]
if (reportRows.length === 0) {
mdLines.push('_No active plugins in `registry.json` yet — schema and `withdrawn.json` validated cleanly._')
} else {
for (const r of reportRows) {
if (r.status === 'FAIL') {
mdLines.push(`### ❌ \`${r.id}@${r.version}\``)
mdLines.push(`- **Error**: ${r.error}`)
mdLines.push('')
continue
}
mdLines.push(`### ✅ \`${r.id}@${r.version}\` (\`${r.tier}\` · \`${r.trust}\`)`)
mdLines.push(`- Archive: \`${r.sizeBytes}\` bytes · SHA-256: \`${r.sha256}\``)
if (r.capabilities.length > 0) {
mdLines.push('- **Capabilities**:')
for (const c of r.capabilities) {
mdLines.push(` - \`[${String(c.level || '').toUpperCase()}]\` \`${c.id}\`: ${c.summary?.['zh-CN'] || c.summary?.['en-US'] || ''}`)
}
}
if (r.executables.length > 0) {
mdLines.push('- **Executables (SHA-256)**:')
for (const ex of r.executables) {
mdLines.push(` - \`${ex.path}\` — \`${ex.sha256}\``)
}
}
mdLines.push('')
}
}
const reportMarkdown = mdLines.join('\n') + '\n'
if (opts.reportPath) {
fs.mkdirSync(path.dirname(path.resolve(opts.reportPath)), { recursive: true })
fs.writeFileSync(opts.reportPath, reportMarkdown, 'utf8')
}
if (errors.length > 0) {
console.error(reportMarkdown)
for (const e of errors) console.error('ERROR:', e)
process.exit(1)
}
if (!opts.checkOnly) {
const now = new Date().toISOString()
const indexObj = {
schema: 1,
updated_at: now,
plugins: marketPlugins,
withdrawn: withdrawnList,
}
fs.mkdirSync(opts.outDir, { recursive: true })
fs.writeFileSync(path.join(opts.outDir, 'index.json'), JSON.stringify(indexObj, null, 2) + '\n', 'utf8')
const changesObj = {
schema: 1,
updated_at: now,
plugin_count: marketPlugins.length,
withdrawn_count: withdrawnList.length,
entries: marketPlugins.map((p) => ({ id: p.id, version: p.version, channel: p.channel, sha256: p.sha256 })),
}
fs.writeFileSync(path.join(opts.outDir, 'changes.json'), JSON.stringify(changesObj, null, 2) + '\n', 'utf8')
console.log(`Built ${path.join(opts.outDir, 'index.json')} (${marketPlugins.length} plugin(s), ${withdrawnList.length} withdrawn)`)
} else {
console.log(`Validated registry cleanly (${marketPlugins.length} plugin(s), ${withdrawnList.length} withdrawn)`)
}
}
main().catch((err) => {
console.error('Fatal:', err)
process.exit(1)
})