import { existsSync, readFileSync, readdirSync } from 'node:fs' import { posix, resolve } from 'node:path' import { parseArgs } from 'node:util' const MAX_DIFF_LINES = 60 const bindingKeys = ['mapping', 'inventory', 'original', 'pages'] const fields = ['productFields', 'barcodeFields'] function readJson(root, path) { if (typeof path !== 'string' || /[\\:\x00]/u.test(path) || path.split('/').some(part => part === '' || part === '.' || part === '..')) { throw new Error('无效的知识包相对路径:' + JSON.stringify(path)) } try { return JSON.parse(readFileSync(resolve(root, path), 'utf8').replace(/^\uFEFF/u, '')) } catch (error) { throw new Error(path + ' 无法读取为 JSON(' + (error.code ?? error.name) + ')') } } function keyed(rows, idOf, label) { if (!Array.isArray(rows)) throw new Error(label + ' 必须是清单') const index = new Map() for (const row of rows) { const id = idOf(row) if (!id || index.has(id)) throw new Error(label + ' 中的标识缺失或重复:' + id) index.set(id, row) } return index } function sorted(value) { if (Array.isArray(value)) return value.map(sorted) if (value && typeof value === 'object') { return Object.fromEntries(Object.keys(value).sort().map(key => [key, sorted(value[key])])) } return value } function brief(value) { const json = JSON.stringify(sorted(value)) if (json === undefined) return '缺失' return json.length <= 140 ? json : json.slice(0, 137) + '…' } function compareEntries(report, label, source, release) { for (const id of [...new Set([...source.keys(), ...release.keys()])].sort()) { const before = source.get(id) const after = release.get(id) const location = label + ' ' + id if (!source.has(id)) report('- 仅小壹包有 ' + location) else if (!release.has(id)) report('+ 待补入小壹包 ' + location) else if (JSON.stringify(sorted(before)) !== JSON.stringify(sorted(after))) { report('~ ' + location + ' 通用源 ' + brief(before) + ' → 小壹包 ' + brief(after)) } } } function pick(row, keys) { return Object.fromEntries(keys.filter(key => row[key] !== undefined).map(key => [key, row[key]])) } function sourceAssets(doc, label) { const list = doc.source?.assets ?? doc.source?.ps_assets ?? doc.ps_assets if (list === undefined) return new Map() return keyed(list.map(asset => ({ id: asset.asset_id ?? asset.assetId ?? asset.id, digest: (asset.ps_sha256 ?? asset.sha256)?.toLowerCase(), canvas: asset.canvas_px ?? asset.canvas, })), asset => asset.id, label + ' 原稿') } function mappingFields(doc, label) { return keyed(doc.fields.map(field => ({ id: field.field_id, screen: field.screen_id, type: field.type, role: field.role, asset: field.asset_id ?? field.ps_location?.asset_id, layer: field.ps_location?.path ?? field.ps_location?.name, layerId: field.ps_location?.layer_id ?? field.ps_location?.id, embedded: field.embedded_target ?? field.ps_location?.embedded_target, bounds: (field.type === '图片' ? field.ps_style?.coverage_rect : field.ps_style?.bounds), })), field => field.id, label + ' 字段') } function inventoryRows(doc, label) { return keyed(doc.rows.map(row => ({ id: row.id, asset: row.asset_id ?? row.assetId, path: row.path, kind: row.kind, parent: row.parent_id, })), row => row.id == null && !row.path ? null : (row.asset ?? '') + '/' + (row.id ?? row.path), label + ' 图层') } function compareTemplate(sourceRoot, releaseRoot, manifest, report) { const descriptorPath = posix.join(posix.dirname(manifest.supplement), 'release.json') const descriptor = readJson(sourceRoot, descriptorPath) const expected = new Map(Object.entries(descriptor.bindings).map(([key, binding]) => [key, pick(binding, bindingKeys)])) const published = new Map(Object.entries(manifest.bindings).map(([key, binding]) => [key, pick(binding, bindingKeys)])) if (!expected.size || !published.size) throw new Error('组件绑定为空') if (descriptor.entrypoint !== manifest.entrypoint) { report('~ 企业规则入口 通用源 ' + brief(descriptor.entrypoint) + ' → 小壹包 ' + brief(manifest.entrypoint)) } compareEntries(report, '组件绑定', expected, published) const files = keyed(manifest.files, file => file.path, '出库文件清单') const assets = keyed(manifest.assets, asset => asset.path, '出库资产清单') for (const asset of descriptor.assets ?? []) { const released = assets.get(asset.path) if (!released || released.type !== asset.type || released.component !== asset.component) { report('~ 资产缺失或归属不同 ' + asset.path + ' (' + asset.component + '/' + asset.type + ')') } } for (const [component, binding] of expected) { const released = published.get(component) if (!released) continue for (const kind of ['mapping', 'inventory']) { if (files.get(released[kind])?.type !== kind) { report('- 小壹出库清单缺少 ' + component + ' ' + kind) continue } const left = readJson(sourceRoot, binding[kind]) const right = readJson(releaseRoot, released[kind]) const label = component + '/' + kind for (const [side, doc] of [['通用源', left], ['小壹包', right]]) { if ((doc.template_id && doc.template_id !== manifest.templateId) || (doc.component && doc.component !== component)) { report('~ ' + label + ' ' + side + ' 模板或组件标识不一致') } } const rightAssets = sourceAssets(right, label) compareEntries(report, label + ' 原稿', sourceAssets(left, label), rightAssets) if (kind === 'inventory') { compareEntries(report, label + ' 图层', inventoryRows(left, label), inventoryRows(right, label)) } else { const originals = released.original ? [[released.original, rightAssets.size === 1 ? rightAssets.values().next().value?.digest : right.source?.sha256]] : Object.values(released.pages ?? {}).map(page => [page.original, rightAssets.get(page.assetId)?.digest]) for (const [path, sha256] of originals) { const asset = assets.get(path) if (asset?.type !== 'original' || (sha256 && asset.sha256?.toLowerCase() !== sha256.toLowerCase())) { report('~ ' + label + ' 原稿与出库资产不一致 ' + path) } } compareEntries(report, label + ' 字段', mappingFields(left, label), mappingFields(right, label)) const screens = doc => keyed((doc.screens ?? []).map(screen => pick(screen, ['screen_id', 'asset_id', 'bounds'])), screen => screen.screen_id, label + ' 页面') compareEntries(report, label + ' 页面', screens(left), screens(right)) } } } const productionPath = manifest.productionConfig if (productionPath) { const left = readJson(sourceRoot, productionPath) const right = readJson(releaseRoot, productionPath) for (const key of fields) { const intake = config => keyed((config.intake?.[key] ?? []).map(field => pick(field, ['id', 'type', 'required', 'multiple', 'imageRole', 'options'])), field => field.id, 'intake/' + key) compareEntries(report, 'intake/' + key, intake(left), intake(right)) } } } function releaseDirectories(root) { if (existsSync(resolve(root, 'manifest.json'))) return [root] const directories = [] for (const entry of readdirSync(root, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { if (!entry.isDirectory() || !existsSync(resolve(root, entry.name, 'index.json'))) continue const { current } = readJson(root, entry.name + '/index.json') if (typeof current !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/iu.test(current)) { throw new Error(entry.name + '/index.json 缺少有效的 current 版本') } directories.push(resolve(root, entry.name, current)) } if (!directories.length) throw new Error('小壹目录中没有 manifest.json 或带 index.json 的模板') return directories } try { const { values, positionals } = parseArgs({ options: { help: { type: 'boolean', short: 'h' } }, allowPositionals: true }) if (values.help || positionals.length !== 2) { console.log('用法:node scripts/check-kb-contract-drift.mjs <通用源导出目录> <小壹版本目录或出库根目录>') process.exitCode = values.help ? 0 : 2 } else { const [sourceRoot, releaseRoot] = positionals const releases = releaseDirectories(releaseRoot) let diffCount = 0 let errors = 0 for (const root of releases) { try { const manifest = readJson(root, 'manifest.json') if (typeof manifest.templateId !== 'string' || !manifest.templateId) throw new Error('manifest.json 缺少 templateId') const before = diffCount compareTemplate(sourceRoot, root, manifest, line => { if (++diffCount <= MAX_DIFF_LINES) console.log('[' + manifest.templateId + '] ' + line) }) if (diffCount === before) console.log('[' + manifest.templateId + '] 契约一致') } catch (error) { errors++ console.error('读取或校验知识契约失败(' + root + '):' + error.message) } } if (diffCount > MAX_DIFF_LINES) console.log('另有 ' + (diffCount - MAX_DIFF_LINES) + ' 条差异未展开') console.log('已检查 ' + releases.length + ' 套,契约差异 ' + diffCount + ' 条,输入错误 ' + errors + ' 套') process.exitCode = errors ? 2 : Number(diffCount > 0) } } catch (error) { console.error(error.message) process.exitCode = 2 }