feat(form): create/update close-loop with re-read schema validation (Task 3, webapi hardening)
This commit is contained in:
1 parent
472f310b64
commit
8b075cec6d
5 files changed
+220
-7
No files matched your search
@@ -1,9 +1,10 @@
|
||||
/**
|
||||
* form schema 归一化 (webapi contract hardening)
|
||||
* 镜像 web formUtils.buildFormData: 把“输入 patch”变成 web 渲染用的最终 schema.
|
||||
* form schema 归一化 + 闭环 (webapi contract hardening)
|
||||
* 镜像 web formUtils.buildFormData: 把"输入 patch"变成 web 渲染用的最终 schema.
|
||||
* - 顶层字段 (dataType/required/...) → __config__ 深合并
|
||||
* - 控件切换时清理“上一种控件”专属字段 (relationForm → 普通控件)
|
||||
* - 控件切换时清理"上一种控件"专属字段 (relationForm → 普通控件)
|
||||
* - validateStrictSchema: 任何字段缺 jnpfKey 或控件能力冲突直接报错
|
||||
* - closeFormContract: POST/PUT → GET 回读 → 仅在回读合法时 release, 阻断"命令成功但 runtime 不一致"
|
||||
*/
|
||||
|
||||
export interface FormField {
|
||||
@@ -111,3 +112,60 @@ export function validateStrictSchema(fields: FormField[]): StrictValidation {
|
||||
}
|
||||
return { ok: errors.length === 0, errors }
|
||||
}
|
||||
|
||||
export interface CloseLoopInput {
|
||||
enCode: string
|
||||
appCode: string
|
||||
fields: any[]
|
||||
autoRelease?: boolean
|
||||
op: 'create' | 'update'
|
||||
}
|
||||
|
||||
export interface CloseLoopResult {
|
||||
id: string
|
||||
state: 0 | 1
|
||||
schema: any[]
|
||||
}
|
||||
|
||||
export interface CloseLoopWebapi {
|
||||
postForm: (payload: any) => Promise<{ id: string; code: number }>
|
||||
putForm?: (payload: any) => Promise<{ id: string; code: number }>
|
||||
getForm: (enCode: string) => Promise<{ id: string; state: 0 | 1; fields: any[] }>
|
||||
releaseForm?: (id: string) => Promise<{ code: number }>
|
||||
}
|
||||
|
||||
/**
|
||||
* form create/update 闭环 (webapi hardening)
|
||||
* POST/PUT → GET 回读 → validateStrictSchema → 仅在 schema 合法时 release
|
||||
* 任何 schema 非法立即抛 FORM_SCHEMA_INVALID, 防止"命令成功但 runtime 不一致".
|
||||
*/
|
||||
export async function closeFormContract(
|
||||
webapi: CloseLoopWebapi,
|
||||
input: CloseLoopInput,
|
||||
): Promise<CloseLoopResult> {
|
||||
// 1. POST 或 PUT
|
||||
if (input.op === 'create') {
|
||||
await webapi.postForm({ enCode: input.enCode, appCode: input.appCode, fields: input.fields })
|
||||
} else {
|
||||
if (!webapi.putForm) throw new Error('PUT operation requires putForm in webapi')
|
||||
await webapi.putForm({ enCode: input.enCode, appCode: input.appCode, fields: input.fields })
|
||||
}
|
||||
|
||||
// 2. GET 回读
|
||||
const got = await webapi.getForm(input.enCode)
|
||||
|
||||
// 3. 严格校验回读 schema
|
||||
const strict = validateStrictSchema(got.fields as FormField[])
|
||||
if (!strict.ok) {
|
||||
throw new Error('FORM_SCHEMA_INVALID:' + JSON.stringify(strict.errors))
|
||||
}
|
||||
|
||||
// 4. 仅在回读通过后 release
|
||||
if (input.autoRelease) {
|
||||
if (!webapi.releaseForm) throw new Error('autoRelease requires releaseForm in webapi')
|
||||
await webapi.releaseForm(got.id)
|
||||
return { id: got.id, state: 1, schema: got.fields }
|
||||
}
|
||||
|
||||
return { id: got.id, state: got.state, schema: got.fields }
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { callAiForm, printAiFormResult, renderAiFieldResult } from './_ai.ts'
|
||||
import { initBuildFormData, buildFormData as webBuildFormData, isBuildFormDataLoaded } from './_buildformdata.ts'
|
||||
import { applySmartProps, loadSmartPropsContext, applyHeuristicRequired, applyHeuristicRelationForm } from './_smart_props.ts'
|
||||
import { completeRelationFormFields } from './_relationform_completeness.ts' // v2.4+ (BS-新132-变种): relationForm 4 字段 silent_fix
|
||||
import { closeFormContract } from './_schema_normalize.ts' // T3: 创建闭环 (POST/PUT + GET 回读 + release gate, webapi hardening)
|
||||
import { repairFormDataFromString } from './_form_repair.ts'
|
||||
import { browserVerify } from './_browser_verify.ts'
|
||||
import { createFormViaUi } from './_create_ui.ts'
|
||||
@@ -1686,6 +1687,38 @@ export function buildFormCreateCommand(): Command {
|
||||
|
||||
if (opts.autoRelease && type !== 4 && newId !== '(unknown)') {
|
||||
log.info(`loadVisualDev.release (formId=${newId})`)
|
||||
|
||||
// T3 close-loop (webapi hardening): POST 已发生, 此处 closeFormContract 仅跑 GET + strict 校验
|
||||
// 通过后才让下方 release 重试逻辑跑; 失败立即 FORM_SCHEMA_INVALID 退出, 阻断 runtime 不一致
|
||||
const closeLoopWebapi = {
|
||||
postForm: async () => ({ id: newId, code: 200 }), // POST 已发生 (loadVisualDev.create 上面), no-op stub
|
||||
getForm: async () => {
|
||||
const info = (await loadVisualDev.getInfo(newId)) as { id: string; state: number | string; formData: string | object }
|
||||
const fdRaw = info.formData
|
||||
const fd = typeof fdRaw === 'string' ? JSON.parse(fdRaw) : (fdRaw as any) || {}
|
||||
const fields = Array.isArray(fd.fields) ? fd.fields : []
|
||||
const stateNum = (typeof info.state === 'string' ? parseInt(info.state, 10) : info.state) as 0 | 1
|
||||
return { id: info.id, state: stateNum, fields }
|
||||
},
|
||||
releaseForm: async () => ({ code: 200 }), // release 走下方既有重试, 此处 no-op
|
||||
}
|
||||
try {
|
||||
await closeFormContract(closeLoopWebapi, {
|
||||
enCode: opts.enCode,
|
||||
appCode: c.appCode,
|
||||
fields: [],
|
||||
autoRelease: false,
|
||||
op: 'create',
|
||||
})
|
||||
} catch (e) {
|
||||
if ((e as Error).message?.includes('FORM_SCHEMA_INVALID')) {
|
||||
log.error(`✗ T3 回读校验失败: ${(e as Error).message}`)
|
||||
return ctx.fail(`FORM_SCHEMA_INVALID (创建后回读校验失败)`, { id: newId, enCode: opts.enCode })
|
||||
}
|
||||
throw e
|
||||
}
|
||||
log.ok(` ✓ T3 闭环校验通过 (state=0, 等待 release)`)
|
||||
|
||||
// release 失败时重试 1 次 (500ms 间隔), 仍失败 process.exit(1)
|
||||
// 后端: VisualdevController.java:593 publish() — state=1 + base_visual_release 行 saveOrUpdate (line 673)
|
||||
// web 端: web/apps/jnpf-web-apps-main/src/api/onlineDev/visualDev.ts:43 release(id) → POST /visualdev/Base/{id}/Actions/Release
|
||||
|
||||
@@ -14,7 +14,7 @@ import { initWebapi, loadVisualDev } from '../../webapi/visualDev.ts'
|
||||
import { dirtyCheck, dirtyCheckFailAndExit, DirtyCheckError, logDirtyCheckSkip, buildDirtyCheckSkipFix } from '../_dirty_check.ts'
|
||||
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
|
||||
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
|
||||
import { applyNormalizedPatch, validateStrictSchema, type FormField } from './_schema_normalize.ts' // schema 归一化 + 严格校验 (webapi hardening)
|
||||
import { applyNormalizedPatch, validateStrictSchema, closeFormContract, type FormField } from './_schema_normalize.ts' // schema 归一化 + 严格校验 + T3 闭环 (webapi hardening)
|
||||
|
||||
interface Opts {
|
||||
id: string
|
||||
@@ -390,9 +390,41 @@ export function buildFormUpdateCommand(): Command {
|
||||
// === step 4 防护 / PUT 后自动重新发布 ===
|
||||
if (opts.autoRelease) {
|
||||
log.info(`PUT 后自动 Actions/Release (BS-53 防护)`)
|
||||
const rr = (await loadVisualDev.release(opts.id)) as { code?: number; msg?: string }
|
||||
if (rr.code === 200 || rr.code === undefined) log.ok(`✓ 已自动重新发布 (state 1/2 → 1)`)
|
||||
else log.warn(`自动重新发布失败 code=${rr.code}: ${rr.msg} — 手动跑 'dacli form release ${opts.id}'`)
|
||||
// T3 close-loop (webapi hardening): PUT 已发生, 此处 closeFormContract 跑 GET 回读 + strict 校验
|
||||
// 校验通过后才 release; 不通过立即 FORM_SCHEMA_INVALID 退出, 阻断 runtime 不一致
|
||||
// 与 T1 (PUT 前 strict 校验 merged) 互补 — T1 防"客户端缺字段", T3 防"服务端状态不一致"
|
||||
const closeLoopWebapi = {
|
||||
postForm: async () => ({ id: opts.id, code: 200 }), // no-op, 仅满足类型
|
||||
putForm: async () => ({ id: opts.id, code: 200 }), // PUT 已发生 (loadVisualDev.update 上面)
|
||||
getForm: async () => {
|
||||
const info = (await loadVisualDev.getInfo(opts.id)) as { id: string; state: number | string; formData: string | object }
|
||||
const fdRaw = info.formData
|
||||
const fd = typeof fdRaw === 'string' ? JSON.parse(fdRaw) : (fdRaw as any) || {}
|
||||
const fields = Array.isArray(fd.fields) ? fd.fields : []
|
||||
const stateNum = (typeof info.state === 'string' ? parseInt(info.state, 10) : info.state) as 0 | 1
|
||||
return { id: info.id, state: stateNum, fields }
|
||||
},
|
||||
releaseForm: async (id: string) => {
|
||||
const rr = (await loadVisualDev.release(id)) as { code?: number; msg?: string }
|
||||
return { code: rr.code ?? 200 }
|
||||
},
|
||||
}
|
||||
try {
|
||||
await closeFormContract(closeLoopWebapi, {
|
||||
enCode: orig.enCode as string,
|
||||
appCode: c.appCode,
|
||||
fields: [],
|
||||
autoRelease: true,
|
||||
op: 'update',
|
||||
})
|
||||
log.ok(`✓ T3 闭环通过 (state=1)`)
|
||||
} catch (e) {
|
||||
if ((e as Error).message?.includes('FORM_SCHEMA_INVALID')) {
|
||||
log.error(`✗ T3 回读校验失败: ${(e as Error).message}`)
|
||||
return ctx.fail(`FORM_SCHEMA_INVALID (更新后回读校验失败)`, { id: opts.id })
|
||||
}
|
||||
log.warn(`自动重新发布失败: ${(e as Error).message?.slice(0, 200)} — 手动跑 'dacli form release ${opts.id}'`)
|
||||
}
|
||||
}
|
||||
|
||||
const summary = { id: opts.id, action: 'updated' }
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { closeFormContract } from '../../src/commands/form/_schema_normalize.ts'
|
||||
|
||||
describe('form create/update 闭环 (Task 3)', () => {
|
||||
it('POST 后 GET schema 非法 → 不 release + 抛 FORM_SCHEMA_INVALID', async () => {
|
||||
const webapi = {
|
||||
postForm: vi.fn().mockResolvedValue({ id: '999', code: 200 }),
|
||||
getForm: vi.fn().mockResolvedValue({
|
||||
id: '999', state: 0,
|
||||
fields: [{ __vModel__: 'f_x', __config__: { jnpfKey: 'relationForm' /* 缺 modelId */ } }],
|
||||
}),
|
||||
releaseForm: vi.fn(),
|
||||
putForm: vi.fn(),
|
||||
}
|
||||
await expect(closeFormContract(webapi, {
|
||||
enCode: 'tdd5_x', appCode: 'tdd5',
|
||||
fields: [{ __vModel__: 'f_x', __config__: { jnpfKey: 'select' } }], // patch 是合法的
|
||||
autoRelease: true, op: 'create',
|
||||
})).rejects.toThrow(/FORM_SCHEMA_INVALID/)
|
||||
expect(webapi.releaseForm).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('POST → GET → release 全 OK → 返回 {id, state: 1, schema}', async () => {
|
||||
const webapi = {
|
||||
postForm: vi.fn().mockResolvedValue({ id: '999', code: 200 }),
|
||||
getForm: vi.fn().mockResolvedValue({
|
||||
id: '999', state: 0,
|
||||
fields: [{ __vModel__: 'f_x', __config__: { jnpfKey: 'select', label: 'X' } }],
|
||||
}),
|
||||
releaseForm: vi.fn().mockResolvedValue({ code: 200 }),
|
||||
}
|
||||
const r = await closeFormContract(webapi, {
|
||||
enCode: 'tdd5_x', appCode: 'tdd5',
|
||||
fields: [{ __vModel__: 'f_x', __config__: { jnpfKey: 'select' } }],
|
||||
autoRelease: true, op: 'create',
|
||||
})
|
||||
expect(r.id).toBe('999')
|
||||
expect(r.state).toBe(1)
|
||||
expect(r.schema).toHaveLength(1)
|
||||
expect(webapi.postForm).toHaveBeenCalledOnce()
|
||||
expect(webapi.getForm).toHaveBeenCalledOnce()
|
||||
expect(webapi.releaseForm).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('op=update 时调 putForm 而非 postForm', async () => {
|
||||
const webapi = {
|
||||
postForm: vi.fn(),
|
||||
putForm: vi.fn().mockResolvedValue({ id: '888', code: 200 }),
|
||||
getForm: vi.fn().mockResolvedValue({
|
||||
id: '888', state: 0,
|
||||
fields: [{ __vModel__: 'f_y', __config__: { jnpfKey: 'input' } }],
|
||||
}),
|
||||
releaseForm: vi.fn(),
|
||||
}
|
||||
const r = await closeFormContract(webapi, {
|
||||
enCode: 'tdd5_y', appCode: 'tdd5',
|
||||
fields: [{ __vModel__: 'f_y', __config__: { jnpfKey: 'input' } }],
|
||||
autoRelease: true, op: 'update',
|
||||
})
|
||||
expect(webapi.putForm).toHaveBeenCalledOnce()
|
||||
expect(webapi.postForm).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('autoRelease=false → 不调 releaseForm 但仍验证 schema', async () => {
|
||||
const webapi = {
|
||||
postForm: vi.fn().mockResolvedValue({ id: '777', code: 200 }),
|
||||
getForm: vi.fn().mockResolvedValue({
|
||||
id: '777', state: 0,
|
||||
fields: [{ __vModel__: 'f_z', __config__: { jnpfKey: 'divider', required: true } }], // divider+required conflict
|
||||
}),
|
||||
}
|
||||
await expect(closeFormContract(webapi, {
|
||||
enCode: 'tdd5_z', appCode: 'tdd5',
|
||||
fields: [{ __vModel__: 'f_z', __config__: { jnpfKey: 'divider' } }],
|
||||
autoRelease: false, op: 'create',
|
||||
})).rejects.toThrow(/FORM_SCHEMA_INVALID/)
|
||||
})
|
||||
})
|
||||
@@ -60,6 +60,7 @@ const mocks = vi.hoisted(() => ({
|
||||
getDataModelList: vi.fn(),
|
||||
create: vi.fn(),
|
||||
release: vi.fn(),
|
||||
getInfo: vi.fn(),
|
||||
getVisualDevList: vi.fn(),
|
||||
postJson: vi.fn(),
|
||||
saveCommandLog: vi.fn(() => '/tmp/test-log.json'),
|
||||
@@ -157,7 +158,10 @@ vi.mock('../../src/webapi/visualDev.ts', () => ({
|
||||
loadVisualDev: {
|
||||
create: mocks.create,
|
||||
release: mocks.release,
|
||||
getInfo: mocks.getInfo,
|
||||
update: vi.fn(),
|
||||
getVisualDevList: mocks.getVisualDevList,
|
||||
createMenu: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -265,6 +269,14 @@ beforeEach(() => {
|
||||
list: [{ id: 'form-id-1', enCode: 'eventSignup' }],
|
||||
})
|
||||
mocks.release.mockResolvedValue({ code: 200, msg: 'ok', data: null })
|
||||
// T3 close-loop (webapi hardening): getInfo mock 返合法 schema, 让 create 路径通过回读校验
|
||||
mocks.getInfo.mockResolvedValue({
|
||||
id: 'form-id-1',
|
||||
state: 0,
|
||||
formData: JSON.stringify({
|
||||
fields: [{ __vModel__: 'f_x', __config__: { jnpfKey: 'input', label: 'X' } }],
|
||||
}),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
Reference in new issue
Block a user