* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 * fix: preserve download recovery and bound PBZX decoding Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
430 lines
13 KiB
JavaScript
430 lines
13 KiB
JavaScript
// Guards the AGENTS.md rule forbidding empty catch blocks that silently turn
|
|
// failures into successes. Covers JS/TS/JSX/TSX/MJS/CJS via the TypeScript AST
|
|
// and PowerShell (.ps1/.psm1/.psd1) via a comment- and string-aware lexer.
|
|
import test from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
import ts from 'typescript'
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
const repoRoot = path.resolve(__dirname, '..', '..')
|
|
|
|
const JS_TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'])
|
|
const PS_EXTS = new Set(['.ps1', '.psm1', '.psd1'])
|
|
const SKIP_DIRS = new Set(['.git', '.debug', 'node_modules', 'dist', 'build', 'wailsjs'])
|
|
|
|
function scriptKindFor(filePath) {
|
|
switch (path.extname(filePath).toLowerCase()) {
|
|
case '.tsx': return ts.ScriptKind.TSX
|
|
case '.ts':
|
|
case '.mts':
|
|
case '.cts': return ts.ScriptKind.TS
|
|
case '.jsx': return ts.ScriptKind.JSX
|
|
default: return ts.ScriptKind.JS
|
|
}
|
|
}
|
|
|
|
function isEmptyBlock(block) {
|
|
return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt))
|
|
}
|
|
|
|
function isSilentLiteralExpr(expr) {
|
|
let current = expr
|
|
while (ts.isParenthesizedExpression(current)) current = current.expression
|
|
if (
|
|
current.kind === ts.SyntaxKind.NullKeyword ||
|
|
current.kind === ts.SyntaxKind.TrueKeyword ||
|
|
current.kind === ts.SyntaxKind.FalseKeyword ||
|
|
ts.isStringLiteralLike(current) ||
|
|
ts.isNumericLiteral(current) ||
|
|
ts.isVoidExpression(current)
|
|
) {
|
|
return true
|
|
}
|
|
if (ts.isIdentifier(current) && current.text === 'undefined') return true
|
|
if (ts.isArrayLiteralExpression(current) && current.elements.length === 0) return true
|
|
if (ts.isObjectLiteralExpression(current) && current.properties.length === 0) return true
|
|
return false
|
|
}
|
|
|
|
function isSilentFunctionBody(expr) {
|
|
let current = expr
|
|
while (ts.isParenthesizedExpression(current)) current = current.expression
|
|
if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) {
|
|
if (isEmptyBlock(current.body)) return true
|
|
if (!ts.isBlock(current.body) && isSilentLiteralExpr(current.body)) return true
|
|
if (
|
|
ts.isBlock(current.body) &&
|
|
current.body.statements.length === 1 &&
|
|
ts.isReturnStatement(current.body.statements[0]) &&
|
|
(!current.body.statements[0].expression || isSilentLiteralExpr(current.body.statements[0].expression))
|
|
) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
function getCalleeMethodName(callee) {
|
|
if (ts.isPropertyAccessExpression(callee)) return callee.name.text
|
|
if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
|
|
return callee.argumentExpression.text
|
|
}
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Finds empty `catch` clauses and empty Promise `.catch(...)` / `.then(_, ...)`
|
|
* rejection callbacks in a JS/TS source string using the TypeScript AST.
|
|
*/
|
|
export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') {
|
|
const sf = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, scriptKindFor(filePath))
|
|
const findings = []
|
|
|
|
const record = (node, kind) => {
|
|
const pos = sf.getLineAndCharacterOfPosition(node.getStart(sf))
|
|
findings.push({
|
|
file: filePath,
|
|
line: pos.line + 1,
|
|
column: pos.character + 1,
|
|
kind,
|
|
})
|
|
}
|
|
|
|
function visit(node) {
|
|
if (ts.isCatchClause(node) && isEmptyBlock(node.block)) {
|
|
record(node, 'empty-catch-clause')
|
|
} else if (ts.isCallExpression(node)) {
|
|
const method = getCalleeMethodName(node.expression)
|
|
if (method === 'catch' && node.arguments.length >= 1 && isSilentFunctionBody(node.arguments[0])) {
|
|
record(node.arguments[0], 'empty-promise-catch')
|
|
} else if (method === 'then' && node.arguments.length >= 2 && isSilentFunctionBody(node.arguments[1])) {
|
|
record(node.arguments[1], 'empty-promise-then-reject')
|
|
}
|
|
}
|
|
ts.forEachChild(node, visit)
|
|
}
|
|
|
|
visit(sf)
|
|
return findings
|
|
}
|
|
|
|
function tokenizePowerShell(sourceText) {
|
|
const tokens = []
|
|
let i = 0
|
|
let line = 1
|
|
let col = 1
|
|
const len = sourceText.length
|
|
|
|
const advance = () => {
|
|
const ch = sourceText[i++]
|
|
if (ch === '\n') {
|
|
line += 1
|
|
col = 1
|
|
} else {
|
|
col += 1
|
|
}
|
|
return ch
|
|
}
|
|
|
|
const atHereStringEnd = (quote) => {
|
|
if (sourceText[i] !== quote || sourceText[i + 1] !== '@') return false
|
|
return i === 0 || sourceText[i - 1] === '\n'
|
|
}
|
|
|
|
while (i < len) {
|
|
const ch = sourceText[i]
|
|
const next = sourceText[i + 1]
|
|
|
|
// Whitespace
|
|
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
|
|
advance()
|
|
continue
|
|
}
|
|
|
|
// Block comment <# ... #>
|
|
if (ch === '<' && next === '#') {
|
|
advance()
|
|
advance()
|
|
while (i < len && !(sourceText[i] === '#' && sourceText[i + 1] === '>')) advance()
|
|
if (i < len) {
|
|
advance()
|
|
advance()
|
|
}
|
|
continue
|
|
}
|
|
|
|
// Line comment # ...
|
|
if (ch === '#') {
|
|
while (i < len && sourceText[i] !== '\n') advance()
|
|
continue
|
|
}
|
|
|
|
// Here-strings @' ... '@ and @" ... "@
|
|
if (ch === '@' && (next === "'" || next === '"')) {
|
|
const quote = next
|
|
let look = i + 2
|
|
while (look < len && (sourceText[look] === ' ' || sourceText[look] === '\t' || sourceText[look] === '\r')) look++
|
|
if (look < len && sourceText[look] === '\n') {
|
|
const startLine = line
|
|
const startCol = col
|
|
while (i <= look) advance()
|
|
while (i < len && !atHereStringEnd(quote)) advance()
|
|
if (i < len) {
|
|
advance()
|
|
advance()
|
|
}
|
|
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
|
continue
|
|
}
|
|
}
|
|
|
|
// Single-quoted string ('' escapes ')
|
|
if (ch === "'") {
|
|
const startLine = line
|
|
const startCol = col
|
|
advance()
|
|
while (i < len) {
|
|
if (sourceText[i] === "'") {
|
|
advance()
|
|
if (sourceText[i] === "'") {
|
|
advance()
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
advance()
|
|
}
|
|
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
|
continue
|
|
}
|
|
|
|
// Double-quoted string (` escapes next char, "" escapes ")
|
|
if (ch === '"') {
|
|
const startLine = line
|
|
const startCol = col
|
|
advance()
|
|
while (i < len) {
|
|
if (sourceText[i] === '`') {
|
|
advance()
|
|
if (i < len) advance()
|
|
continue
|
|
}
|
|
if (sourceText[i] === '"') {
|
|
advance()
|
|
if (sourceText[i] === '"') {
|
|
advance()
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
advance()
|
|
}
|
|
tokens.push({ type: 'string', value: '', line: startLine, column: startCol })
|
|
continue
|
|
}
|
|
|
|
// Backtick escape outside strings
|
|
if (ch === '`') {
|
|
advance()
|
|
if (i < len) advance()
|
|
continue
|
|
}
|
|
|
|
const startLine = line
|
|
const startCol = col
|
|
|
|
// :: operator
|
|
if (ch === ':' && next === ':') {
|
|
advance()
|
|
advance()
|
|
tokens.push({ type: 'punct', value: '::', line: startLine, column: startCol })
|
|
continue
|
|
}
|
|
|
|
// Punctuation relevant to catch syntax
|
|
if ('{}[];,.'.includes(ch)) {
|
|
advance()
|
|
tokens.push({ type: 'punct', value: ch, line: startLine, column: startCol })
|
|
continue
|
|
}
|
|
|
|
// Word / identifier / parameter (e.g. -catch, catch)
|
|
if (/[A-Za-z_-]/.test(ch)) {
|
|
let word = ''
|
|
while (i < len && /[A-Za-z0-9_-]/.test(sourceText[i])) word += advance()
|
|
tokens.push({ type: 'word', value: word, line: startLine, column: startCol })
|
|
continue
|
|
}
|
|
|
|
// Any other token
|
|
advance()
|
|
tokens.push({ type: 'other', value: ch, line: startLine, column: startCol })
|
|
}
|
|
|
|
return tokens
|
|
}
|
|
|
|
/**
|
|
* Finds empty `catch` blocks (including comment-only and semicolon-only blocks,
|
|
* with or without `[Type]` exception filters) in a PowerShell script.
|
|
*/
|
|
export function findEmptyCatchesInPowerShell(sourceText, filePath = 'sample.ps1') {
|
|
const tokens = tokenizePowerShell(sourceText)
|
|
const findings = []
|
|
|
|
for (let idx = 0; idx < tokens.length; idx++) {
|
|
const tok = tokens[idx]
|
|
if (tok.type !== 'word' || tok.value.toLowerCase() !== 'catch') continue
|
|
const prev = tokens[idx - 1]
|
|
if (prev && (prev.value === '.' || prev.value === '::')) continue
|
|
|
|
// Skip optional comma-separated type filters: catch [TypeA], [TypeB] { ... }
|
|
let cursor = idx + 1
|
|
while (cursor < tokens.length && tokens[cursor].value === '[') {
|
|
let depth = 0
|
|
while (cursor < tokens.length) {
|
|
if (tokens[cursor].value === '[') depth++
|
|
else if (tokens[cursor].value === ']') {
|
|
depth--
|
|
if (depth === 0) {
|
|
cursor++
|
|
break
|
|
}
|
|
}
|
|
cursor++
|
|
}
|
|
if (cursor < tokens.length && tokens[cursor].value === ',') cursor++
|
|
else break
|
|
}
|
|
|
|
if (cursor >= tokens.length || tokens[cursor].value !== '{') continue
|
|
|
|
// Scan block body until matching '}'
|
|
let bodyCursor = cursor + 1
|
|
let empty = true
|
|
while (bodyCursor < tokens.length && tokens[bodyCursor].value !== '}') {
|
|
if (tokens[bodyCursor].value !== ';') {
|
|
empty = false
|
|
break
|
|
}
|
|
bodyCursor++
|
|
}
|
|
if (empty && bodyCursor < tokens.length && tokens[bodyCursor].value === '}') {
|
|
findings.push({
|
|
file: filePath,
|
|
line: tok.line,
|
|
column: tok.column,
|
|
kind: 'empty-ps-catch',
|
|
})
|
|
}
|
|
}
|
|
|
|
return findings
|
|
}
|
|
|
|
function walkFiles(dir, out = []) {
|
|
if (!fs.existsSync(dir)) return out
|
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
if (SKIP_DIRS.has(entry.name)) continue
|
|
const full = path.join(dir, entry.name)
|
|
if (entry.isDirectory()) walkFiles(full, out)
|
|
else out.push(full)
|
|
}
|
|
return out
|
|
}
|
|
|
|
test('detector self-test: catches all empty JS/TS catch forms and allows handled catches', () => {
|
|
const bad = [
|
|
'try { a() } catch {}',
|
|
'try { a() } catch (e) {}',
|
|
'try { a() } catch { /* comment only */ }',
|
|
'try { a() } catch (e) {\n // comment only\n}',
|
|
'try { a() } catch { ; ; }',
|
|
'p.catch(() => {})',
|
|
'p?.catch((e) => { /* noop */ })',
|
|
'p["catch"](function () {})',
|
|
'p.catch(async () => { ; })',
|
|
'p.then(ok, () => {})',
|
|
'p.then(ok, (err) => { // noop\n})',
|
|
'p.catch(() => null)',
|
|
'p.catch(() => "")',
|
|
'p.catch(() => false)',
|
|
'p.catch(() => [])',
|
|
'p.catch(() => { return null })',
|
|
].join('\n')
|
|
|
|
const badFindings = findEmptyCatchesInJS(bad, 'bad.ts')
|
|
assert.equal(badFindings.length, 16, `expected 16 findings, got ${JSON.stringify(badFindings)}`)
|
|
|
|
const good = [
|
|
'const text = "try { a() } catch {} .catch(() => {})"',
|
|
'// try { a() } catch {}',
|
|
'try { a() } catch (e) { console.warn(e) }',
|
|
'try { a() } catch { return fallback }',
|
|
'p.catch((e) => console.warn(e))',
|
|
'p.catch((e) => { console.warn(e); return null })',
|
|
'p.then(ok, (e) => handle(e))',
|
|
].join('\n')
|
|
|
|
assert.deepEqual(findEmptyCatchesInJS(good, 'good.ts'), [])
|
|
})
|
|
|
|
test('detector self-test: catches empty PowerShell catch blocks and ignores strings/comments', () => {
|
|
const bad = [
|
|
'try { foo } catch {}',
|
|
'try { foo } Catch { # comment only\n}',
|
|
'try { foo } catch { <# block comment #> ; }',
|
|
'try { foo } catch [System.IO.IOException], [System.Exception] {}',
|
|
].join('\n')
|
|
|
|
const badFindings = findEmptyCatchesInPowerShell(bad, 'bad.ps1')
|
|
assert.equal(badFindings.length, 4, `expected 4 findings, got ${JSON.stringify(badFindings)}`)
|
|
|
|
const good = [
|
|
'# try { foo } catch {}',
|
|
'<# try { foo } catch {} #>',
|
|
'$s1 = "try { foo } catch {}"',
|
|
"$s2 = 'try { foo } catch {}'",
|
|
'$here = @"\ntry { foo } catch {}\n"@',
|
|
'$obj.catch { }',
|
|
'try { foo } catch { Write-Warning $_ }',
|
|
'try { foo } catch [System.Exception] { throw }',
|
|
].join('\n')
|
|
|
|
assert.deepEqual(findEmptyCatchesInPowerShell(good, 'good.ps1'), [])
|
|
})
|
|
|
|
test('repository has zero empty catch blocks across frontend/ and scripts/', () => {
|
|
const roots = [path.join(repoRoot, 'frontend'), path.join(repoRoot, 'scripts')]
|
|
const violations = []
|
|
let scannedJS = 0
|
|
let scannedPS = 0
|
|
|
|
for (const root of roots) {
|
|
for (const file of walkFiles(root)) {
|
|
const ext = path.extname(file).toLowerCase()
|
|
const rel = path.relative(repoRoot, file).split(path.sep).join('/')
|
|
if (JS_TS_EXTS.has(ext)) {
|
|
scannedJS += 1
|
|
const text = fs.readFileSync(file, 'utf8')
|
|
violations.push(...findEmptyCatchesInJS(text, rel))
|
|
} else if (PS_EXTS.has(ext)) {
|
|
scannedPS += 1
|
|
const text = fs.readFileSync(file, 'utf8')
|
|
violations.push(...findEmptyCatchesInPowerShell(text, rel))
|
|
}
|
|
}
|
|
}
|
|
|
|
assert.ok(scannedJS > 0, 'expected to scan at least one JS/TS file')
|
|
assert.ok(scannedPS > 0, 'expected to scan at least one PowerShell file')
|
|
assert.deepEqual(
|
|
violations.map((v) => `${v.file}:${v.line}:${v.column} (${v.kind})`),
|
|
[],
|
|
`Empty catch blocks found (forbidden by AGENTS.md):\n${violations.map((v) => ` - ${v.file}:${v.line}:${v.column} (${v.kind})`).join('\n')}`,
|
|
)
|
|
})
|