Files
dacli/tools/validate-bpmn-xsd.ts
T
sswandClaude 3f1cb3a03b feat(dacli): JNPF7 验证闭环 Stage 0 + P0-6 preview + workflow canvas 回归修复
Stage 0 (验证基础设施):
- 5 层验证工具链 (tools/) + JSON Schema + validate-baseline.sh CI gate
- P0-9: components-whitelist.yaml 单一来源 + parseFlowXml 消漂移 (create.ts tag 改消费 component-map.json)
- E-2: docs/components.md 文档化 6 个 pass-through 组件
- P1-16: validate-baseline 接入 quality-gate.sh
- L3 回归测试 (bs117 / bpmn-bs / antipattern-output) + mock LLM 库

P0-6 (user-in-the-loop):
- form create --ai --preview: 提交前渲染字段表格 (CJK 对齐) + TTY 交互确认 (_preview.ts)

workflow canvas 回归修复 (v0.22+ SSW 迁移引入):
- parseFlowXml 命名空间无关 (flowNodes 缺口)
- _autoLayout 无 DI 时合成完整 BPMNDiagram+Shape+Edge + bpmn2 归一化 (canvas 缺口)
- 真实后端 + 浏览器设计器验证画布渲染; 详见 jnpf7-analysis §14

quality-gate 全绿: tsc 0 · vitest 483 · doc:check · baseline L1-L5

Co-Authored-By: Claude <[email protected]>
2026-07-27 12:49:44 +08:00

224 lines
8.0 KiB
TypeScript

/**
* L1.2 — BPMN 2.0 validator (mirrors bpmnLintUtil.ts:29-169 from jnpf-bpmn)
*
* Mirrors `/home/ubuntu/ccWorkDir/jnpf/jnpf7/jnpf-bpmn/lib/utils/bpmnLintUtil.ts:29-169`
* structural rules. Also adds JNPF-specific failure mode checks (URL-encoded flowXml,
* trivial 3-node, random Activity_ IDs).
*
* Usage:
* npx tsx tools/validate-bpmn-xsd.ts <xml-file>
* npx tsx tools/validate-bpmn-xsd.ts --stdin
*
* Exit codes:
* 0 = valid
* 1 = validation failed
* 2 = input not parseable
*
* Rules enforced:
* R1 Must contain bpmn:startEvent + at least one bpmn:userTask + bpmn:endEvent
* R2 Only one start event allowed
* R3 Only one end event allowed
* R4 Start must not have incoming edges; end must not have outgoing edges
* R5 Split/join gateways must come in pairs (parallel/inclusive)
* R6 Every userTask must have both incoming and outgoing sequenceFlow
* R7 No URL-encoded flowXml (JNPF bug: FlowXmlUtil.xml:151-164 URL-encodes output)
* R8 No random "Activity_<7 random chars>" IDs (JNPF bug: FlowXmlUtil.java:203-205)
* R9 Process id should equal enCode (we enforce; JNPF leaves as "Process_1")
* R10 flowable:assignee / candidateGroups should be present on userTask
*/
import { readFileSync } from 'node:fs'
import { BpmnModdle } from 'bpmn-moddle'
interface Issue {
severity: 'error' | 'warn'
rule: string
message: string
path?: string
}
function isUrlEncoded(s: string): boolean {
// If > 20% of chars are %-escaped, it's URL-encoded
const escaped = (s.match(/%[0-9A-Fa-f]{2}/g) ?? []).join('').length
return escaped / s.length > 0.2
}
async function validateBpmn(flowXml: string): Promise<Issue[]> {
const issues: Issue[] = []
// R7: URL-encoded?
if (isUrlEncoded(flowXml)) {
issues.push({
severity: 'error',
rule: 'BS-JNPF-url-encoded-flowXml',
message: 'flowXml appears URL-encoded (FlowXmlUtil.java:151-164 JNPF bug). dacli/SSW must produce plain BPMN XML.',
})
return issues // bail — no point parsing encoded blob
}
const moddle = new BpmnModdle()
let rootElement: any
try {
const result = (await moddle.fromXML(flowXml)) as any
rootElement = result.rootElement
} catch (e: any) {
issues.push({
severity: 'error',
rule: 'BPMN-parse',
message: `XML parse failed: ${e.message}`,
})
return issues
}
const procs = rootElement.rootElements?.filter((e: any) => e.$type === 'bpmn:Process') ?? []
if (procs.length === 0) {
issues.push({ severity: 'error', rule: 'BPMN-no-process', message: 'no bpmn:Process found' })
return issues
}
if (procs.length > 1) {
issues.push({ severity: 'warn', rule: 'BPMN-multi-process', message: `found ${procs.length} bpmn:Process elements (expected 1)` })
}
const proc = procs[0]
const flowElements = proc.flowElements ?? []
const starts = flowElements.filter((e: any) => e.$type === 'bpmn:StartEvent')
const ends = flowElements.filter((e: any) => e.$type === 'bpmn:EndEvent')
const userTasks = flowElements.filter((e: any) => e.$type === 'bpmn:UserTask')
const seqFlows = flowElements.filter((e: any) => e.$type === 'bpmn:SequenceFlow')
const gateways = flowElements.filter((e: any) => e.$type?.startsWith('bpmn:') && e.$type.includes('Gateway'))
// Build id → element map and wire incoming/outgoing from sequenceFlow (bpmn-moddle does not auto-wire)
const elemMap = new Map<string, any>()
for (const e of flowElements) {
elemMap.set(e.id, { ...e, incoming: [] as any[], outgoing: [] as any[] })
}
for (const sf of seqFlows) {
const srcId = sf.sourceRef?.id
const tgtId = sf.targetRef?.id
const src = srcId ? elemMap.get(srcId) : null
const tgt = tgtId ? elemMap.get(tgtId) : null
if (src) src.outgoing.push(sf)
if (tgt) tgt.incoming.push(sf)
}
// R1: must contain start + userTask + end
if (starts.length === 0) {
issues.push({ severity: 'error', rule: 'R1-missing-start', message: 'no bpmn:StartEvent' })
}
if (userTasks.length === 0) {
issues.push({ severity: 'error', rule: 'R1-missing-userTask', message: 'no bpmn:UserTask (SSW AIRepairServiceImpl.java:1171-1179 warns)' })
}
if (ends.length === 0) {
issues.push({ severity: 'error', rule: 'R1-missing-end', message: 'no bpmn:EndEvent' })
}
// R2: only one start
if (starts.length > 1) {
issues.push({ severity: 'error', rule: 'R2-multi-start', message: `${starts.length} StartEvents (only 1 allowed)` })
}
// R3: only one end
if (ends.length > 1) {
issues.push({ severity: 'error', rule: 'R3-multi-end', message: `${ends.length} EndEvents (only 1 allowed)` })
}
// R4: start must not have incoming; end must not have outgoing
for (const s of starts) {
const inc = elemMap.get(s.id)?.incoming ?? []
if (inc.length > 0) {
issues.push({ severity: 'error', rule: 'R4-start-has-incoming', message: `startEvent ${s.id} has ${inc.length} incoming edge(s)` })
}
}
for (const e of ends) {
const out = elemMap.get(e.id)?.outgoing ?? []
if (out.length > 0) {
issues.push({ severity: 'error', rule: 'R4-end-has-outgoing', message: `endEvent ${e.id} has ${out.length} outgoing edge(s)` })
}
}
// R5: split/join gateway pairs
const parallelSplits = gateways.filter((g: any) => (elemMap.get(g.id)?.outgoing ?? []).length > 1).length
const parallelJoins = gateways.filter((g: any) => (elemMap.get(g.id)?.incoming ?? []).length > 1).length
if (parallelSplits !== parallelJoins) {
issues.push({
severity: 'warn',
rule: 'R5-gateway-pair-mismatch',
message: `parallel gateway split=${parallelSplits} join=${parallelJoins} (should be equal)`,
})
}
// R6: every userTask must have incoming + outgoing
for (const t of userTasks) {
const wired = elemMap.get(t.id)
const inc = wired?.incoming ?? []
const out = wired?.outgoing ?? []
if (inc.length === 0) {
issues.push({ severity: 'error', rule: 'R6-task-no-incoming', message: `userTask ${t.id} has no incoming edge` })
}
if (out.length === 0) {
issues.push({ severity: 'error', rule: 'R6-task-no-outgoing', message: `userTask ${t.id} has no outgoing edge` })
}
}
// R8: random Activity_<7 chars> IDs
const randomIds = flowElements.filter((e: any) => /^Activity_[a-z0-9]{5,}$/i.test(e.id)).length
if (randomIds > 0) {
issues.push({
severity: 'warn',
rule: 'BS-JNPF-random-Activity-id',
message: `${randomIds} element(s) use random Activity_<7chars> IDs (FlowXmlUtil.java:203-205 JNPF bug). dacli must use deterministic IDs (process id = enCode).`,
})
}
// R10: flowable:assignee / candidateGroups presence
const tasksWithoutAssignee = userTasks.filter((t: any) => !t.$attrs?.['flowable:assignee'] && !t.$attrs?.['flowable:candidateGroups']).length
if (tasksWithoutAssignee > 0 && userTasks.length > 0) {
issues.push({
severity: 'warn',
rule: 'R10-no-flowable-assignee',
message: `${tasksWithoutAssignee}/${userTasks.length} userTask(s) lack flowable:assignee / candidateGroups (BUILD_WORKFLOW_PROMPT WR-5)`,
})
}
return issues
}
function loadInput(): string {
const args = process.argv.slice(2)
if (args.includes('--stdin')) {
return readFileSync(0, 'utf8')
}
const file = args[0]
if (!file) {
console.error('Usage: validate-bpmn-xsd.ts <xml-file> | --stdin')
process.exit(2)
}
return readFileSync(file, 'utf8')
}
async function main() {
let xml: string
try {
xml = loadInput()
} catch (e: any) {
console.error(`✗ input read failed: ${e.message}`)
process.exit(2)
}
const issues = await validateBpmn(xml)
if (issues.length === 0) {
console.log('✓ BPMN valid: structure OK + no JNPF antipatterns')
process.exit(0)
}
console.error(`✗ ${issues.length} issue(s) found:`)
for (const i of issues) {
console.error(` [${i.severity.toUpperCase()}] ${i.rule}: ${i.message}`)
}
const errorCount = issues.filter(i => i.severity === 'error').length
process.exit(errorCount > 0 ? 1 : 0)
}
main().catch(e => {
console.error(`✗ unhandled: ${e.message}`)
process.exit(2)
})