feat(dacli): di/create.ts 完整 wrapCommand 迁移 (P6 6 exit 收口, 含 step machine)

6 处 process.exit → wrapCommand handler ctx.fail():
- validation 缺 fullName/enCode/category (exit 2 → fail summary 含 3 个 bool)
- runDiStepMachineCreate 抛错 (替代原 process.exit(1), handler catch → fail)
- --from-json-file 文件不存在
- --from-json-file JSON.parse 失败
- 后端 code !== 200 (含 enhanceFromBackend + formatErrorLine 错误增强)
- (其他 try/catch 兜底)

重构关键:
  - runDiStepMachineCreate 内部 process.exit(1) → throw new Error(...)
    wrapCommand handler catch → ctx.fail(`step machine 校验失败: ...`)
    原版内部 exit 会绕开 L3 CommandLog 落盘, 改抛错后 handler 收口
  - 删分散的 4 处 printCommandEnd (L3 落盘) — wrapCommand 自动调用
  - 删本地 --verbose/--json (改 addOutputOptions 注入)
  - runCommandAutoFix 后 opts.assign 保留 (silent fix 透传)

迁移模式统一:
  - import { setupOutputFilter, addOutputOptions, wrapCommand }
  - Opts interface 加 verbose?: boolean (原 verbose 已存在)
  - .action 开头 setupOutputFilter(opts)
  - 整块业务逻辑 wrapCommand 包 + try/catch → ctx.success/fail
  - log.error 输出保留 (用户感知) + ctx.fail 收口 (供 L3)

修改方式: Write 整文件重写 (Edit 工具不匹配, step machine 重排 + 6 exit 收口风险).

验证:
  - TS compile 0 新错误 (baseline 57 不变)
  - 73/73 单元测试 PASS

P6 累计: 剩 workflow/create (9) + form/codegen (8) + workflow/update (6) + form/create (13)
+ bigscreen/construct (6) + app/create (6) + report/update (5) + report/publish (5)
+ report/create (5) + portal/setDefault (5) + form/update (5) = ~67 exit 散布 11 文件.
form/audit.ts + log/last.ts 跳过 (semantic 退出码 / meta-recursive).
This commit is contained in:
ssw committed 2026-07-21 20:02:32 +08:00
1 parent 9a59adc9ac
commit b665b8b260
1 file changed
+147 -186
+147 -186
View File
@@ -18,7 +18,7 @@ import { initWebapi, loadDataInterface, getDataInterfaceList } from '../../webap
import { validateDiUpdate, type DiOpts } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): 跨命令 auto-fix pipeline (替代原 inline autoStripEnCode + soften)
import { setupOutputFilter, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
import { lookupDataInterfaceIdByEnCode } from './_lookup.ts'
interface CreateOpts {
@@ -39,6 +39,7 @@ interface CreateOpts {
parameterJson?: string
dataConfigJson?: string
json?: boolean
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
verbose?: boolean
}
@@ -61,199 +62,156 @@ export function buildDiCreateCommand(): Command {
.option('--fieldJson <json>', '字段映射 JSON 数组字符串 (BS-drift-DI-1 修, 透传 baseline fieldJson)')
.option('--parameterJson <json>', '参数映射 JSON 数组字符串 (BS-drift-DI-2 修, 透传 baseline parameterJson)')
.option('--dataConfigJson <json>', '数据源配置 JSON 字符串 (BS-drift-DI-3 修, 透传 baseline 真实 SQL/API 配置)')
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (opts: CreateOpts) => {
// 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON
setupOutputFilter(opts)
if (!opts.fullName || !opts.enCode || !opts.category) {
log.error('--fullName, --enCode, --category 必填')
process.exit(2)
}
const c = await JnpfClient.fromToken()
const startTime = Date.now()
await initWebapi(c)
// v2.1+ (2026-07-21): 命令级 auto-fix pipeline (替代原 inline autoStripEnCode + soften)
// S-X1 enCode strip silent (BS-新38)
// S-X2 fullName soften silent (BS-新52)
// G-X1 BS-47 重名 suggest (含 <appCode> 前缀建议, 启用需 fetchExistingLists)
const fixCtx = await fetchExistingLists(c, c.appCode)
const cmdFix = runCommandAutoFix(opts as unknown as Record<string, unknown>, fixCtx)
if (cmdFix.silent.length > 0) {
Object.assign(opts, cmdFix.opts)
}
// Phase di: step machine 校验 (复用 _validate.ts)
await runDiStepMachineCreate(c, opts)
// --from-json-file 优先, 直接读完整 body
if (opts.fromJsonFile) {
const { readFileSync, existsSync } = await import('node:fs')
if (!existsSync(opts.fromJsonFile)) {
const errMsg = `--from-json-file 文件不存在: ${opts.fromJsonFile}`
log.error(errMsg)
// v2.1+ (2026-07-21): 错误路径落 CommandLog
printCommandEnd({
command: 'di create',
appCode: c.appCode,
result: 'failure',
error: errMsg,
summary: { enCode: opts.enCode, fromJsonFile: opts.fromJsonFile },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
try {
const jsonBody = JSON.parse(readFileSync(opts.fromJsonFile, 'utf-8'))
// 必填字段覆盖 (file 提供的是 raw schema, 不含全字段)
jsonBody.fullName = opts.fullName
jsonBody.enCode = opts.enCode
jsonBody.category = opts.category
if (opts.type !== undefined) jsonBody.type = Number(opts.type)
if (opts.action !== undefined) jsonBody.action = Number(opts.action)
if (opts.sortCode !== undefined) jsonBody.sortCode = Number(opts.sortCode)
if (opts.enabledMark !== undefined) jsonBody.enabledMark = Number(opts.enabledMark)
if (opts.hasPage !== undefined) jsonBody.hasPage = Number(opts.hasPage)
if (opts.isPostPosition !== undefined) jsonBody.isPostPosition = Number(opts.isPostPosition)
if (opts.description) jsonBody.description = opts.description
log.ok(`✓ 从 ${opts.fromJsonFile} 加载完整 schema, 必填字段已覆盖`)
log.info(` 提示: file 必须含 dataConfigJson/fieldJson/parameterJson/dataCountJson/dataEchoJson/dataJsJson/dataExceptionJson, 否则后端 AD102`)
// 跳过默认 body 构造, 直接走 create
const r = (await loadDataInterface.createDataInterface(jsonBody)) as {
code?: number; msg?: string; data?: unknown
}
if (r.code !== 200) {
log.error(`di create 失败 (code=${r.code}): ${r.msg}`)
// v2.1+ (2026-07-21): 错误路径落 CommandLog
printCommandEnd({
command: 'di create',
appCode: c.appCode,
result: 'failure',
error: `di create 失败 (code=${r.code}): ${r.msg}`,
summary: { enCode: opts.enCode, source: 'json-file' },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
log.ok(`✓ DI 创建成功 (从 JSON file) id=${r.data} enCode=${opts.enCode}`)
if (opts.json) printJson({ id: r.data, enCode: opts.enCode, source: 'json-file' })
// v2.1+ (2026-07-21): 成功路径 (from-json-file) 落 CommandLog
printCommandEnd({
command: 'di create',
appCode: c.appCode,
summary: { id: String(r.data), enCode: opts.enCode, source: 'json-file' },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
return
} catch (e) {
const errMsg = `--from-json-file 解析失败: ${(e as Error).message?.slice(0, 200)}`
log.error(errMsg)
// v2.1+ (2026-07-21): 错误路径落 CommandLog
printCommandEnd({
command: 'di create',
appCode: c.appCode,
result: 'failure',
error: errMsg,
summary: { enCode: opts.enCode, fromJsonFile: opts.fromJsonFile },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
}
// 1. 构造 body (镜像 web Form.vue handleSubmit query 拼装)
const body: Record<string, unknown> = {
fullName: opts.fullName,
enCode: opts.enCode,
category: opts.category,
type: Number(opts.type || '2'),
sortCode: Number(opts.sortCode || '0'),
enabledMark: Number(opts.enabledMark || '1'),
isPostPosition: Number(opts.isPostPosition || '0'),
// web 端 MyBatis-Plus 拦截器用 f_delete_mark 列做 tenant 隔离,
// 默认填 0 (不删除). dacli 必须显式给, 否则 mapper insertOrUpdate 后 list 看不见
deleteMark: 0,
tenantId: '0',
}
if (opts.action !== undefined) body.action = Number(opts.action)
if (opts.hasPage !== undefined) body.hasPage = Number(opts.hasPage)
if (opts.description) body.description = opts.description
// fix : 镜像 web Form.vue:484-491 handleSubmit 完整 schema
// 必传 fieldJson/parameterJson/dataCountJson/dataEchoJson/dataJsJson/dataExceptionJson, 否则后端 AD102
// dataConfigJson 默认静态数据 (type=2), 后端会按 type 选择处理
// Round 10 --fieldJson/--parameterJson/--dataConfigJson 透传 baseline 真实配置
// 完整数据源 (SQL/API) 配置需要更详细的 JSON
const defaultApiData = { method: 1, url: '', header: [], query: [], body: '', bodyType: 0 }
const defaultSqlData = { dbLinkId: '', sql: '' }
const defaultDataConfig = { staticData: '', sqlData: defaultSqlData, apiData: defaultApiData }
// fieldJson/parameterJson 默认 '[]', 透传 baseline 用 --fieldJson/--parameterJson
body.fieldJson = opts.fieldJson || '[]'
body.parameterJson = opts.parameterJson || '[]'
// dataConfigJson/dataCountJson/dataEchoJson 默认空模板, 透传 baseline 用 --dataConfigJson
// 注: web Form.vue 三个 json 通常相同, dacli 默认统一, --dataConfigJson 同步覆盖三者
const dataConfigJsonStr = opts.dataConfigJson || JSON.stringify(defaultDataConfig)
body.dataConfigJson = dataConfigJsonStr
body.dataCountJson = dataConfigJsonStr
body.dataEchoJson = dataConfigJsonStr
body.dataJsJson = ''
body.dataExceptionJson = ''
// 2. POST 创建
log.info(`loadDataInterface.createDataInterface (enCode=${opts.enCode})`)
const r = (await loadDataInterface.createDataInterface(body)) as {
code?: number
msg?: string
data?: unknown
}
if (r.code !== 200 && r.code !== undefined) {
log.error(`di create 失败 (code=${r.code}): ${r.msg}`)
// Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode
const enhanced = enhanceFromBackend(r.msg || '', 'di', { entity: 'di' })
log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`)
if (opts.json) printJson(r)
// v2.1+ (2026-07-21): 错误路径落 CommandLog
printCommandEnd({
command: 'di create',
appCode: c.appCode,
result: 'failure',
error: `di create 失败 (code=${r.code}): ${r.msg}`,
summary: { enCode: opts.enCode },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
process.exit(1)
}
let newId = (r.data as { id?: string })?.id
if (!newId) {
// (Round 12 用共享 _lookup.ts 替代 inline list fallback
newId = (await lookupDataInterfaceIdByEnCode(opts.enCode)) || undefined
}
log.ok(`✓ DI 创建成功 id=${newId || '(unknown)'} enCode=${opts.enCode}`)
if (opts.json) printJson({ ...(r.data as object), id: newId })
// v2.1+ (2026-07-21): 成功路径 (默认 body) 落 CommandLog
printCommandEnd({
await wrapCommand({
command: 'di create',
appCode: c.appCode,
summary: { id: newId, enCode: opts.enCode },
fixes: [...cmdFix.silent, ...cmdFix.assertive, ...cmdFix.suggestions],
duration_ms: Date.now() - startTime,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
if (!opts.fullName || !opts.enCode || !opts.category) {
log.error('--fullName, --enCode, --category 必填')
return ctx.fail('--fullName, --enCode, --category 必填', {
fullName: !!opts.fullName,
enCode: !!opts.enCode,
category: !!opts.category,
})
}
await initWebapi(c)
// v2.1+ (2026-07-21): 命令级 auto-fix pipeline (替代原 inline autoStripEnCode + soften)
// S-X1 enCode strip silent (BS-新38)
// S-X2 fullName soften silent (BS-新52)
// G-X1 BS-47 重名 suggest (含 <appCode> 前缀建议, 启用需 fetchExistingLists)
const fixCtx = await fetchExistingLists(c, c.appCode)
const cmdFix = runCommandAutoFix(opts as unknown as Record<string, unknown>, fixCtx)
if (cmdFix.silent.length > 0) {
Object.assign(opts, cmdFix.opts)
}
// Phase di: step machine 校验 (复用 _validate.ts)
// v2.2+ (2026-07-21): step machine 抛 Error → wrapCommand handler catch → ctx.fail
// 原版内部 process.exit(1) 会绕开 L3 CommandLog, 改抛错让 handler 收口
try {
await runDiStepMachineCreate(c, opts)
} catch (e) {
return ctx.fail(`step machine 校验失败: ${(e as Error).message?.slice(0, 200)}`, { enCode: opts.enCode })
}
// --from-json-file 优先, 直接读完整 body
if (opts.fromJsonFile) {
const { readFileSync, existsSync } = await import('node:fs')
if (!existsSync(opts.fromJsonFile)) {
const errMsg = `--from-json-file 文件不存在: ${opts.fromJsonFile}`
log.error(errMsg)
return ctx.fail(errMsg, { enCode: opts.enCode, fromJsonFile: opts.fromJsonFile })
}
try {
const jsonBody = JSON.parse(readFileSync(opts.fromJsonFile, 'utf-8'))
// 必填字段覆盖 (file 提供的是 raw schema, 不含全字段)
jsonBody.fullName = opts.fullName
jsonBody.enCode = opts.enCode
jsonBody.category = opts.category
if (opts.type !== undefined) jsonBody.type = Number(opts.type)
if (opts.action !== undefined) jsonBody.action = Number(opts.action)
if (opts.sortCode !== undefined) jsonBody.sortCode = Number(opts.sortCode)
if (opts.enabledMark !== undefined) jsonBody.enabledMark = Number(opts.enabledMark)
if (opts.hasPage !== undefined) jsonBody.hasPage = Number(opts.hasPage)
if (opts.isPostPosition !== undefined) jsonBody.isPostPosition = Number(opts.isPostPosition)
if (opts.description) jsonBody.description = opts.description
log.ok(`✓ 从 ${opts.fromJsonFile} 加载完整 schema, 必填字段已覆盖`)
log.info(` 提示: file 必须含 dataConfigJson/fieldJson/parameterJson/dataCountJson/dataEchoJson/dataJsJson/dataExceptionJson, 否则后端 AD102`)
// 跳过默认 body 构造, 直接走 create
const r = (await loadDataInterface.createDataInterface(jsonBody)) as {
code?: number; msg?: string; data?: unknown
}
if (r.code !== 200) {
log.error(`di create 失败 (code=${r.code}): ${r.msg}`)
return ctx.fail(`di create 失败 (code=${r.code}): ${r.msg}`, { enCode: opts.enCode, source: 'json-file', code: r.code })
}
log.ok(`✓ DI 创建成功 (从 JSON file) id=${r.data} enCode=${opts.enCode}`)
const summary = { id: r.data, enCode: opts.enCode, source: 'json-file' }
if (opts.json) printJson(summary)
return ctx.success(summary)
} catch (e) {
const errMsg = `--from-json-file 解析失败: ${(e as Error).message?.slice(0, 200)}`
log.error(errMsg)
return ctx.fail(errMsg, { enCode: opts.enCode, fromJsonFile: opts.fromJsonFile })
}
}
// 1. 构造 body (镜像 web Form.vue handleSubmit query 拼装)
const body: Record<string, unknown> = {
fullName: opts.fullName,
enCode: opts.enCode,
category: opts.category,
type: Number(opts.type || '2'),
sortCode: Number(opts.sortCode || '0'),
enabledMark: Number(opts.enabledMark || '1'),
isPostPosition: Number(opts.isPostPosition || '0'),
// web 端 MyBatis-Plus 拦截器用 f_delete_mark 列做 tenant 隔离,
// 默认填 0 (不删除). dacli 必须显式给, 否则 mapper insertOrUpdate 后 list 看不见
deleteMark: 0,
tenantId: '0',
}
if (opts.action !== undefined) body.action = Number(opts.action)
if (opts.hasPage !== undefined) body.hasPage = Number(opts.hasPage)
if (opts.description) body.description = opts.description
// fix : 镜像 web Form.vue:484-491 handleSubmit 完整 schema
// 必传 fieldJson/parameterJson/dataCountJson/dataEchoJson/dataJsJson/dataExceptionJson, 否则后端 AD102
// dataConfigJson 默认静态数据 (type=2), 后端会按 type 选择处理
// Round 10 --fieldJson/--parameterJson/--dataConfigJson 透传 baseline 真实配置
// 完整数据源 (SQL/API) 配置需要更详细的 JSON
const defaultApiData = { method: 1, url: '', header: [], query: [], body: '', bodyType: 0 }
const defaultSqlData = { dbLinkId: '', sql: '' }
const defaultDataConfig = { staticData: '', sqlData: defaultSqlData, apiData: defaultApiData }
// fieldJson/parameterJson 默认 '[]', 透传 baseline 用 --fieldJson/--parameterJson
body.fieldJson = opts.fieldJson || '[]'
body.parameterJson = opts.parameterJson || '[]'
// dataConfigJson/dataCountJson/dataEchoJson 默认空模板, 透传 baseline 用 --dataConfigJson
// 注: web Form.vue 三个 json 通常相同, dacli 默认统一, --dataConfigJson 同步覆盖三者
const dataConfigJsonStr = opts.dataConfigJson || JSON.stringify(defaultDataConfig)
body.dataConfigJson = dataConfigJsonStr
body.dataCountJson = dataConfigJsonStr
body.dataEchoJson = dataConfigJsonStr
body.dataJsJson = ''
body.dataExceptionJson = ''
// 2. POST 创建
log.info(`loadDataInterface.createDataInterface (enCode=${opts.enCode})`)
const r = (await loadDataInterface.createDataInterface(body)) as {
code?: number
msg?: string
data?: unknown
}
if (r.code !== 200 && r.code !== undefined) {
log.error(`di create 失败 (code=${r.code}): ${r.msg}`)
// Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode
const enhanced = enhanceFromBackend(r.msg || '', 'di', { entity: 'di' })
log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`)
if (opts.json) printJson(r)
return ctx.fail(`di create 失败 (code=${r.code}): ${r.msg}`, { enCode: opts.enCode, code: r.code })
}
let newId = (r.data as { id?: string })?.id
if (!newId) {
// (Round 12 用共享 _lookup.ts 替代 inline list fallback
newId = (await lookupDataInterfaceIdByEnCode(opts.enCode)) || undefined
}
log.ok(`✓ DI 创建成功 id=${newId || '(unknown)'} enCode=${opts.enCode}`)
const summary = { id: newId, enCode: opts.enCode, ...(r.data as object) }
if (opts.json) printJson(summary)
ctx.success(summary)
} catch (e) {
ctx.fail(`di create 失败: ${(e as Error).message?.slice(0, 200)}`)
}
})
})
@@ -298,6 +256,8 @@ export function buildDiCreateCommand(): Command {
/**
* Phase di: di create step machine 校验 (3 步镜像, 复用 _validate.ts)
* 在发 API 前暴露问题, 聚合错误一次报
*
* v2.2+ (2026-07-21): 失败时抛 Error (不再 process.exit(1)), 让 wrapCommand handler 收口落 L3 CommandLog
*/
async function runDiStepMachineCreate(
c: JnpfClient,
@@ -352,7 +312,8 @@ async function runDiStepMachineCreate(
for (const e of allErrors) {
log.error(` [step ${e.step} ${e.stepName}] ${e.field || '?'}: ${e.message}`)
}
process.exit(1)
// v2.2+ (2026-07-21): 抛错代替 process.exit(1), wrapCommand handler catch → ctx.fail
throw new Error(`step machine 校验失败 (${allErrors.length} 个错误): ${allErrors.map(e => `${e.field || '?'}: ${e.message}`).join('; ').slice(0, 200)}`)
}
log.info(`✓ step machine 校验通过 (3/3): enCode=${opts.enCode}`)