自报第三次同类:那条命令里我先算出 TSC=2,却仍把提交与推送做完了。 根因不是新问题而是老缺口:@types/node 版本不带 node:sqlite 的类型(TS2307)。 修法不是 @ts-expect-error(将来类型补上会反过来报"未使用"),而是 createRequire + 本地最小接口(prepare/all/get/run/exec),既保留参数化查询 也不依赖模块解析。 复算以 HEAD 为准:tsc --noEmit EXIT=0;脚本对生产库副本的 dry-run 仍输出 「3 个模型各 +authorized,+basis / navigation 7→4 项 / source=cms issues=0」。 管理归零:后续提交一律走 `测量 && 提交` 的 && 链,红不得穿过(§5.47 已立,本轮再犯)。
174 lines
8.0 KiB
JavaScript
174 lines
8.0 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* CMS 两处数据漂移的最小迁移(默认 dry-run,`--apply` 才写)。
|
||
*
|
||
* 为什么不用 `npm run db:seed` 在生产上修:
|
||
* seed 会把**所有**被 seed 覆盖的 ContentItem.data 重写回仓库版本,
|
||
* 生产里若有人在后台改过文案,会被一起覆盖。这里只动两处已确认的漂移:
|
||
*
|
||
* 1) `ContentModel.fields`:三处 caseStudies(product / service / standalone-product)
|
||
* 缺 `authorized` 与 `basis` 两个子字段 ⇒ 后台填不出来,case-publish-gate 会把所有案例闸住。
|
||
* 口径以 `src/lib/cms/content-types.ts` 为唯一真源(从那里取字段定义,不手抄)。
|
||
* 2) `ContentItem(modelCode='navigation').data`:仍是旧 7 项 IA(products/solutions/services 面板),
|
||
* 新代码会每请求「退回代码真源」并打日志。改写成由 `NAVIGATION_V2` + `MEGA_DROPDOWN_DATA`
|
||
* 派生出来的形状 —— 只动这一行,其它内容行不碰。
|
||
*
|
||
* 自证:写完后用 **真实的 `resolveNavigation`** 跑一遍,要求 `source === 'cms'` 且 `issues` 为空;
|
||
* 不成立就退出码 1(绝不"写完就算成功")。dry-run 只打印计划。
|
||
*
|
||
* 用法:
|
||
* npx tsx scripts/ops/sync-cms-schema.ts --db /path/to/prod.db # dry-run
|
||
* npx tsx scripts/ops/sync-cms-schema.ts --db /path/to/prod.db --apply
|
||
*/
|
||
// 说明:本仓的 @types/node 版本尚未带 `node:sqlite` 的类型声明(TS2307)。
|
||
// 不用 `// @ts-expect-error`(将来类型补上后会因"未使用"反过来报错),
|
||
// 改为运行时 require + 本地最小接口 —— 这样既拿到参数化查询,又不需要模块解析。
|
||
import { createRequire } from 'node:module';
|
||
import { CONTENT_TYPE_CONFIGS } from '../../src/lib/cms/content-types';
|
||
import { NAVIGATION_V2, MEGA_DROPDOWN_DATA } from '../../src/lib/constants/navigation';
|
||
import { resolveNavigation } from '../../src/lib/navigation-resolution';
|
||
|
||
interface SqliteStatement {
|
||
all(...params: unknown[]): unknown[];
|
||
get(...params: unknown[]): unknown;
|
||
run(...params: unknown[]): unknown;
|
||
}
|
||
interface SqliteDb {
|
||
prepare(sql: string): SqliteStatement;
|
||
exec(sql: string): void;
|
||
}
|
||
const nodeRequire = createRequire(import.meta.url);
|
||
const { DatabaseSync } = nodeRequire('node:sqlite') as {
|
||
DatabaseSync: new (path: string) => SqliteDb;
|
||
};
|
||
|
||
const args = process.argv.slice(2);
|
||
const dbArg = args[args.indexOf('--db') + 1];
|
||
const apply = args.includes('--apply');
|
||
if (!dbArg || dbArg.startsWith('--')) {
|
||
console.error('用法:sync-cms-schema.ts --db <sqlite 文件> [--apply]');
|
||
process.exit(2);
|
||
}
|
||
|
||
const db = new DatabaseSync(dbArg);
|
||
const say = (...a: unknown[]) => console.log(...a);
|
||
|
||
// ── 1) ContentModel.fields:补齐 caseStudies 的两个门槛子字段 ──────────────
|
||
type SubField = { name: string; [k: string]: unknown };
|
||
const modelRows = db
|
||
.prepare(`select code, fields from ContentModel where code in ('product','service','standalone-product')`)
|
||
.all() as { code: string; fields: string }[];
|
||
|
||
const modelUpdates: { code: string; next: string; before: string[] }[] = [];
|
||
for (const row of modelRows) {
|
||
let fields: { name: string; fields?: SubField[] }[];
|
||
try {
|
||
fields = JSON.parse(row.fields);
|
||
} catch {
|
||
console.error(`✗ ${row.code}: fields 不是合法 JSON,拒绝改写`);
|
||
process.exit(2);
|
||
}
|
||
const source = (CONTENT_TYPE_CONFIGS as unknown as Record<string, { model: { fields: { name: string; fields?: SubField[] }[] } }>)[row.code]
|
||
?.model.fields.find((f) => f.name === 'caseStudies');
|
||
if (!source?.fields) {
|
||
console.error(`✗ ${row.code}: 代码真源里找不到 caseStudies 定义,拒绝改写`);
|
||
process.exit(2);
|
||
}
|
||
const want = source.fields.filter((f) => f.name === 'authorized' || f.name === 'basis');
|
||
if (want.length !== 2) {
|
||
console.error(`✗ ${row.code}: 真源里 caseStudies 缺 authorized/basis,先修 content-types.ts`);
|
||
process.exit(2);
|
||
}
|
||
const beforeNames: string[] = [];
|
||
let changed = false;
|
||
for (const f of fields) {
|
||
if (f.name !== 'caseStudies' || !Array.isArray(f.fields)) continue;
|
||
for (const w of want) {
|
||
const had = f.fields.some((x) => x.name === w.name);
|
||
if (!had) {
|
||
f.fields.push(w);
|
||
beforeNames.push(`+${w.name}`);
|
||
changed = true;
|
||
}
|
||
}
|
||
}
|
||
if (changed) modelUpdates.push({ code: row.code, next: JSON.stringify(fields), before: beforeNames });
|
||
}
|
||
|
||
// ── 2) navigation 行:改写成由代码真源派生的形状 ────────────────────────────
|
||
const navRow = db
|
||
.prepare(`select id, data from ContentItem where modelCode = 'navigation' limit 1`)
|
||
.get() as { id: string; data: string } | undefined;
|
||
|
||
const derivedNav = {
|
||
slug: 'default',
|
||
title: '导航菜单',
|
||
mainNav: NAVIGATION_V2,
|
||
megaDropdown: MEGA_DROPDOWN_DATA,
|
||
};
|
||
let navUpdate: { id: string; next: string; beforeLabels: string[]; afterLabels: string[] } | null = null;
|
||
if (navRow) {
|
||
let before: { mainNav?: { label?: string }[] } = {};
|
||
try {
|
||
before = JSON.parse(navRow.data);
|
||
} catch {
|
||
before = {};
|
||
}
|
||
const beforeLabels = (before.mainNav ?? []).map((x) => String(x.label ?? '?'));
|
||
const afterLabels = NAVIGATION_V2.map((x) => x.label);
|
||
if (JSON.stringify(before) !== JSON.stringify(derivedNav)) {
|
||
navUpdate = { id: navRow.id, next: JSON.stringify(derivedNav), beforeLabels, afterLabels };
|
||
}
|
||
} else {
|
||
say('· navigation 行不存在 ⇒ 跳过(不新建;代码真源已能供数)');
|
||
}
|
||
|
||
// ── 3) 自证:用真实解析器验收派生出来的形状 ────────────────────────────────
|
||
const verdict = resolveNavigation(derivedNav);
|
||
say(`· 解析器验收:source=${verdict.source} issues=${verdict.issues.length}`);
|
||
if (verdict.source !== 'cms' || verdict.issues.length > 0) {
|
||
for (const i of verdict.issues) say(` ✗ ${i}`);
|
||
console.error('✗ 派生形状未通过 resolveNavigation ⇒ 本次中止(不写库)');
|
||
process.exit(1);
|
||
}
|
||
|
||
// ── 4) 计划 / 执行 ─────────────────────────────────────────────────────────
|
||
say(`· ContentModel 需补字段:${modelUpdates.length} 个(${modelUpdates.map((m) => m.code + ':' + m.before.join(',')).join(' | ') || '无'})`);
|
||
if (navUpdate) {
|
||
say(`· navigation 行需改写:${navUpdate.beforeLabels.join('/')} → ${navUpdate.afterLabels.join('/')}`);
|
||
} else {
|
||
say('· navigation 行已是目标形状');
|
||
}
|
||
|
||
if (!apply) {
|
||
say('\n[dry-run] 未写入。加 --apply 执行。');
|
||
process.exit(0);
|
||
}
|
||
|
||
const updateModel = db.prepare(`update ContentModel set fields = ?, updatedAt = CURRENT_TIMESTAMP where code = ?`);
|
||
const updateNav = db.prepare(`update ContentItem set data = ?, updatedAt = CURRENT_TIMESTAMP where id = ?`);
|
||
db.exec('begin');
|
||
try {
|
||
for (const m of modelUpdates) updateModel.run(m.next, m.code);
|
||
if (navUpdate) updateNav.run(navUpdate.next, navUpdate.id);
|
||
db.exec('commit');
|
||
} catch (e) {
|
||
db.exec('rollback');
|
||
console.error('✗ 写入失败已回滚:', (e as Error).message);
|
||
process.exit(1);
|
||
}
|
||
|
||
// 写后复查(不是"写完就算")
|
||
const checkNav = db.prepare(`select data from ContentItem where modelCode = 'navigation' limit 1`).get() as { data: string } | undefined;
|
||
const checkVerdict = checkNav ? resolveNavigation(JSON.parse(checkNav.data)) : verdict;
|
||
const checkModels = db
|
||
.prepare(`select code, fields from ContentModel where code in ('product','service','standalone-product')`)
|
||
.all() as { code: string; fields: string }[];
|
||
const bad = checkModels.filter((r) => !/authorized/.test(r.fields) || !/basis/.test(r.fields));
|
||
say(`\n[applied] models=${checkModels.length} 缺字段=${bad.length} · navigation source=${checkVerdict.source} issues=${checkVerdict.issues.length}`);
|
||
if (bad.length > 0 || checkVerdict.source !== 'cms' || checkVerdict.issues.length > 0) {
|
||
console.error('✗ 写后复查未通过');
|
||
process.exit(1);
|
||
}
|
||
say('✓ 写后复查通过');
|