import { describe, it, expect } from '@jest/globals'; import { readFileSync } from 'fs'; import path from 'path'; /** * 口径字段反漂移守卫。 * * 背景:数据口径 `basis` 由 src/lib/cms/content-types.ts 的 metricBasisField 声明, * 但 prisma/seed.ts 里为 page 型模型**另写了一份字段定义**,并通过 * `contentModel.upsert({ fields: JSON.stringify(config.model.fields) })` 落库; * 后台表单读的是库里这份 ⇒ 种子少写一个 basis,编辑者就永远无法为该指标声明口径。 * * 两侧格式不同(content-types 一行一个键、种子把 name/type 写在同一行), * 故归属判定用「整源索引 + 最近的前置数组头」,不做逐行正则。 */ const ROOT = path.resolve(__dirname, '..', '..'); const CONTENT_TYPES = readFileSync(path.join(ROOT, 'src/lib/cms/content-types.ts'), 'utf8'); const SEED = readFileSync(path.join(ROOT, 'prisma/seed.ts'), 'utf8'); const BASIS_VALUES = ['target', 'team-history', 'verified']; /** 返回「子字段里出现过 marker 的数组字段名」集合 */ function arrayFieldsCarrying(source: string, marker: RegExp): string[] { const headers: { name: string; at: number }[] = []; for (const m of source.matchAll(/name:\s*'([a-zA-Z]+)',\s*type:\s*'array'/g)) { headers.push({ name: m[1] as string, at: m.index as number }); } const found = new Set(); for (const m of source.matchAll(new RegExp(marker, 'g'))) { const at = m.index as number; let owner: string | null = null; for (const h of headers) { if (h.at < at) owner = h.name; else break; } if (owner) found.add(owner); } return [...found]; } const typedWithBasis = arrayFieldsCarrying(CONTENT_TYPES, /\.\.\.metricBasisField/); const seedWithBasis = arrayFieldsCarrying(SEED, /name:\s*'basis'/); // 种子里「含指标子字段」的数组字段名(value/label/metric 三元组) const seedMetricArrays = arrayFieldsCarrying(SEED, /name:\s*'(?:value|metric)',\s*type:\s*'text'/); describe('seed 的指标数组必须与 content-types 一样声明数据口径 basis', () => { it('两侧解析都真的看到了东西(防「匹配零」的假绿)', () => { expect(typedWithBasis.length).toBeGreaterThan(0); expect(seedMetricArrays.length).toBeGreaterThan(0); }); it('content-types 带 basis 的字段名,种子若也定义则必须同样带 basis', () => { const overlapping = seedMetricArrays.filter((n) => typedWithBasis.includes(n)); expect(overlapping.length).toBeGreaterThan(0); const missing = overlapping.filter((n) => !seedWithBasis.includes(n)); expect(missing).toEqual([]); }); it('种子声明 basis 时,其选项值必须与 content-types 同一套(防自造第三套口径标签)', () => { for (const value of BASIS_VALUES) { expect(CONTENT_TYPES).toContain(`value: '${value}'`); } expect(seedWithBasis.length).toBeGreaterThan(0); for (const value of BASIS_VALUES) { expect(SEED).toContain(`value: '${value}'`); } }); });