From 509ecc7e81b2c74a23325813bf0752bb4d073354 Mon Sep 17 00:00:00 2001 From: ssw Date: Tue, 28 Jul 2026 15:21:44 +0800 Subject: [PATCH] feat(form): schema normalize + strict validation (Task 1, webapi hardening) --- src/commands/form/_schema_normalize.ts | 98 ++++++++++++++++++++++++ src/commands/form/_validate.ts | 3 + src/commands/form/update.ts | 10 ++- tests/unit/form_schema_normalize.test.ts | 47 ++++++++++++ 4 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 src/commands/form/_schema_normalize.ts create mode 100644 tests/unit/form_schema_normalize.test.ts diff --git a/src/commands/form/_schema_normalize.ts b/src/commands/form/_schema_normalize.ts new file mode 100644 index 0000000..281080a --- /dev/null +++ b/src/commands/form/_schema_normalize.ts @@ -0,0 +1,98 @@ +/** + * form schema 归一化 (Task 1, 2026-07-28) + * 镜像 web formUtils.buildFormData: 把“输入 patch”变成 web 渲染用的最终 schema. + * - 顶层字段 (dataType/required/...) → __config__ 深合并 + * - 控件切换时清理“上一种控件”专属字段 (relationForm → 普通控件) + * - validateStrictSchema: 任何字段缺 jnpfKey 或控件能力冲突直接报错 + */ + +export interface FormField { + __vModel__: string + __config__: Record + [k: string]: any +} + +const CONFIG_KEYS = [ + 'jnpfKey', + 'label', + 'required', + 'dataType', + 'dictionaryType', + 'placeholder', + 'defaultValue', +] as const +const CONFIG_KEY_SET = new Set(CONFIG_KEYS) +const RELATION_FORM_KEYS = ['modelId', 'propsValue', 'relationField', 'showField', 'relationTable'] +const NO_REQUIRE_JNPF_KEYS = new Set(['divider', 'button', 'alert', 'collapse', 'card']) + +export function normalizeFieldPatch(patch: Record): Record { + const out: Record = { __config__: {} } + + // 顶层字段优先归位到 __config__, 避免顶层与 __config__ 出现矛盾值。 + for (const key of CONFIG_KEYS) { + if (key in patch) out.__config__[key] = patch[key] + } + + // 其他 __config__ 字段保持;同名时顶层归一化值优先。 + if (patch.__config__) { + for (const [key, value] of Object.entries(patch.__config__)) { + if (!(key in out.__config__)) out.__config__[key] = value + } + } + + // options/slot 等非配置顶层字段透传。 + for (const [key, value] of Object.entries(patch)) { + if (key === '__config__' || key === '__vModel__' || CONFIG_KEY_SET.has(key)) continue + out[key] = value + } + return out +} + +export function applyNormalizedPatch(existing: FormField[], patches: Record[]): FormField[] { + const byVModel = new Map(existing.map(field => [field.__vModel__, structuredClone(field)])) + + for (const patch of patches) { + const vModel = patch.__vModel__ + if (!byVModel.has(vModel)) { + byVModel.set(vModel, { __vModel__: vModel, __config__: {} } as FormField) + } + + const current = byVModel.get(vModel)! + const normalized = normalizeFieldPatch(patch) + const previousJnpfKey = current.__config__?.jnpfKey + const nextJnpfKey = normalized.__config__.jnpfKey + + current.__config__ = { ...current.__config__, ...normalized.__config__ } + + if (previousJnpfKey === 'relationForm' && nextJnpfKey && nextJnpfKey !== previousJnpfKey) { + for (const key of RELATION_FORM_KEYS) delete current.__config__[key] + } + + for (const [key, value] of Object.entries(normalized)) { + if (key === '__config__') continue + current[key] = value + } + byVModel.set(vModel, current) + } + + return Array.from(byVModel.values()) +} + +export interface StrictValidation { + ok: boolean + errors: string[] +} + +export function validateStrictSchema(fields: FormField[]): StrictValidation { + const errors: string[] = [] + for (const field of fields) { + const config = field.__config__ || {} + if (!config.jnpfKey) { + errors.push(`field ${field.__vModel__}: missing __config__.jnpfKey`) + } + if (NO_REQUIRE_JNPF_KEYS.has(config.jnpfKey) && config.required === true) { + errors.push(`field ${field.__vModel__}: jnpfKey=${config.jnpfKey} cannot be required`) + } + } + return { ok: errors.length === 0, errors } +} diff --git a/src/commands/form/_validate.ts b/src/commands/form/_validate.ts index 7e10d6d..a1eea6b 100644 --- a/src/commands/form/_validate.ts +++ b/src/commands/form/_validate.ts @@ -33,6 +33,9 @@ import { ValidationError } from '../_error_codes.ts' import { ENCODE_REGEXP, FULLNAME_REGEXP, validateEnCode, validateFullName } from '../_encode_validator.ts' import { log } from '../../core/log.ts' +// Task 1 (2026-07-28): create 路径共用 form update 的 strict 校验 (仅 re-export, 避免循环依赖) +export { validateStrictSchema } from './_schema_normalize.ts' + /** upload folder name 正则 — 镜像 Generator.getData() line 295 */ // eslint-disable-next-line regexp/no-unused-capturing-group const FOLDER_REGEXP = /^[a-z0-9][\w-]{0,99}$/i diff --git a/src/commands/form/update.ts b/src/commands/form/update.ts index 1de85d0..bdfbc8a 100644 --- a/src/commands/form/update.ts +++ b/src/commands/form/update.ts @@ -9,10 +9,12 @@ import { Command } from 'commander' import { JnpfClient } from '../../core/client.ts' import { installHelpHookWithPatterns } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' +import { DacliError } from '../../core/types.ts' 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 } from './_schema_normalize.ts' // Task 1 (2026-07-28): schema 归一化 + 严格校验 interface Opts { id: string @@ -333,8 +335,14 @@ export function buildFormUpdateCommand(): Command { formData = fd as Record } const existingFields = Array.isArray(formData.fields) ? (formData.fields as unknown[]) : [] - const merged = mergeFormFieldUpdates(existingFields, parsed) + const merged = applyNormalizedPatch(existingFields as any[], parsed as any[]) as unknown[] formData.fields = merged + // Task 1 (2026-07-28): 严格 schema 校验, 阻断非法字段 (缺 jnpfKey / 控件能力冲突) + const strict = validateStrictSchema(merged as any[]) + if (!strict.ok) { + for (const err of strict.errors) log.error(` ✗ ${err}`) + throw new DacliError('FORM_SCHEMA_INVALID', -1, JSON.stringify({ id: opts.id, errors: strict.errors, source: 'applyNormalizedPatch' })) + } // v2.4+ (2026-07-24): strict 校验, relationForm 4 字段必填 (TD8 smoke test 命中) if (opts.strict !== false) { const val = validateRelationFormFields(merged) diff --git a/tests/unit/form_schema_normalize.test.ts b/tests/unit/form_schema_normalize.test.ts new file mode 100644 index 0000000..e5bf5a9 --- /dev/null +++ b/tests/unit/form_schema_normalize.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { normalizeFieldPatch, applyNormalizedPatch, validateStrictSchema } from '../../src/commands/form/_schema_normalize.ts' + +describe('form schema normalize (Task 1)', () => { + const existing = [{ + __vModel__: 'f_x', + __config__: { + jnpfKey: 'relationForm', modelId: 'old-id', propsValue: 'f_x_name', relationField: 'f_x_ref', + label: 'X', required: false, dataType: 'static', + }, + }] + + it('顶层 dataType → __config__.dataType', () => { + const patch = [{ __vModel__: 'f_x', dataType: 'dictionary', dictionaryType: 'cat-1' }] + const merged = applyNormalizedPatch(existing, patch) + expect(merged[0].__config__.dataType).toBe('dictionary') + expect(merged[0].__config__.dictionaryType).toBe('cat-1') + expect(merged[0].__config__.jnpfKey).toBe('relationForm') // 保留 + }) + + it('relationForm → select 时清除 relationForm 字段', () => { + const patch = [{ __vModel__: 'f_x', __config__: { jnpfKey: 'select', optionsList: [] } }] + const merged = applyNormalizedPatch(existing, patch) + expect(merged[0].__config__.jnpfKey).toBe('select') + expect(merged[0].__config__.modelId).toBeUndefined() + expect(merged[0].__config__.propsValue).toBeUndefined() + expect(merged[0].__config__.relationField).toBeUndefined() + }) + + it('required 顶层 → __config__.required', () => { + const patch = [{ __vModel__: 'f_x', required: true }] + const merged = applyNormalizedPatch(existing, patch) + expect(merged[0].__config__.required).toBe(true) + }) + + it('validateStrictSchema: __config__ 缺 jnpfKey 报错', () => { + const r = validateStrictSchema([{ __vModel__: 'f_x', __config__: { label: 'X' } }]) + expect(r.ok).toBe(false) + expect(r.errors[0]).toContain('f_x') + expect(r.errors[0]).toContain('jnpfKey') + }) + + it('validateStrictSchema: required 与控件 capability 矛盾时报错 (如 divider 不能 required)', () => { + const r = validateStrictSchema([{ __vModel__: 'f_x', __config__: { jnpfKey: 'divider', required: true } }]) + expect(r.ok).toBe(false) + }) +})