import { createHash } from 'node:crypto'; import { createReadStream } from 'node:fs'; import { open, readdir, readFile, stat } from 'node:fs/promises'; import { execFileSync } from 'node:child_process'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { parseArgs } from 'node:util'; const outputs = { detail: ['详情页', '详情页长图', '详情页切片'], main_images: ['主图', '主图'], sku_images: ['SKU', 'SKU'], }; function requireThat(condition, message) { if (!condition) throw Error(message); } export function jpegDimensions(bytes) { requireThat(bytes.readUInt16BE(0) === 0xffd8, 'JPG 文件头无效'); for (let offset = 2; offset < bytes.length;) { requireThat(bytes[offset++] === 0xff, 'JPG 标记无效'); while (bytes[offset] === 0xff) offset++; const marker = bytes[offset++]; if (marker === 0xda || marker === 0xd9) break; const length = bytes.readUInt16BE(offset); requireThat(length >= 2 && offset + length <= bytes.length, 'JPG 段长度无效'); if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) { requireThat(length >= 11, 'JPG 帧头无效'); const height = bytes.readUInt16BE(offset + 3); const width = bytes.readUInt16BE(offset + 5); requireThat(width && height, 'JPG 尺寸无效'); return { width, height }; } offset += length; } throw Error('JPG 缺少尺寸'); } async function readHeader(file, length) { const handle = await open(file); try { const { buffer, bytesRead } = await handle.read(Buffer.alloc(length)); return buffer.subarray(0, bytesRead); } finally { await handle.close(); } } async function inspect(file, format) { if (format === 'jpg') return jpegDimensions(await readFile(file)); if (format === 'psd' || format === 'psb') { const header = await readHeader(file, 26); requireThat(header.length === 26 && header.toString('ascii', 0, 4) === '8BPS' && header.readUInt16BE(4) === (format === 'psd' ? 1 : 2), 'PSD/PSB 文件头无效'); return { width: header.readUInt32BE(18), height: header.readUInt32BE(14) }; } if (format === 'pcraft') { const header = await readHeader(file, 4); requireThat(header.toString('hex') === '504b0304', 'PCraft ZIP 文件头无效'); const manifest = JSON.parse(execFileSync('tar', ['-xOf', file, 'manifest.json'], { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'], })); requireThat(manifest && typeof manifest === 'object' && !Array.isArray(manifest), 'PCraft 清单无效'); return manifest.size; } } export async function verifyDeliveryBundle(directory, expected = []) { const errors = []; const counts = {}; const files = []; const entries = new Map(); const root = path.resolve(directory); let missingOutputs = 0; let missing = []; let project; let bundle; let longestRelativePath = ''; const largeFiles = new Map(); const duplicateLargeFiles = []; try { bundle = JSON.parse(await readFile(path.join(root, '交付清单.json'), 'utf8')); requireThat(bundle.version === 1 && typeof bundle.deliveryId === 'string' && bundle.deliveryId && Array.isArray(bundle.files) && bundle.counts && Number.isInteger(bundle.totalOutputs) && Number.isInteger(bundle.completedOutputs) && bundle.completedOutputs >= 0 && bundle.totalOutputs > 0 && bundle.completedOutputs <= bundle.totalOutputs && bundle.allOutputsCompleted === (bundle.completedOutputs === bundle.totalOutputs), '交付清单字段无效'); missingOutputs = bundle.totalOutputs - bundle.completedOutputs; missing = bundle.missing ?? []; requireThat((bundle.missingOutputs ?? missingOutputs) === missingOutputs && Array.isArray(missing) && missing.length <= missingOutputs, '输出缺项记录与清单不符'); for (const field of ['failedCount', 'missingCount', 'failedOutputs']) { requireThat((bundle[field] ?? 0) === 0, `${field} 必须为 0`); } for (const record of bundle.files) { const { relativePath, category, format, sizeBytes, sha256, verified } = record; try { requireThat(typeof relativePath === 'string' && !relativePath.includes('\\') && !relativePath.includes(':') && relativePath.split('/').every(part => part && !['.', '..'].includes(part)) && !entries.has(relativePath), '清单路径无效或重复'); entries.set(relativePath, record); requireThat(relativePath.startsWith((category === '工程资源' ? '工程文件' : category) + '/') && format === path.extname(relativePath).slice(1) && verified === true && /^[a-f0-9]{64}$/.test(sha256), '文件记录字段无效'); const file = path.join(root, relativePath); const info = await stat(file); requireThat(info.isFile() && info.size > 0 && info.size === sizeBytes, '文件为空或字节数不符'); const size = await inspect(file, format); if (size) { requireThat(size.width > 0 && size.height > 0 && record.width === size.width && record.height === size.height, '尺寸与清单不符'); } const hash = createHash('sha256'); for await (const chunk of createReadStream(file)) hash.update(chunk); requireThat(hash.digest('hex') === sha256, 'SHA-256 与清单不符'); if (sizeBytes >= 10 * 1024 * 1024) { const previous = largeFiles.get(sha256); if (previous) duplicateLargeFiles.push([previous, relativePath]); else largeFiles.set(sha256, relativePath); } if (format === 'xiaoyi') { requireThat(!project && category === '工程文件' && path.posix.dirname(relativePath) === '工程文件', '工程入口无效或重复'); project = JSON.parse(await readFile(file, 'utf8')); } counts[category] = (counts[category] ?? 0) + 1; files.push({ relativePath, sizeBytes, ...(size ?? {}) }); } catch (error) { errors.push({ path: relativePath, message: error.message, missing: error.code === 'ENOENT' }); } } requireThat(Object.keys(counts).length === Object.keys(bundle.counts).length && Object.entries(counts).every(([category, count]) => bundle.counts[category] === count), '分类计数与清单不符'); requireThat(project?.version === 2 && typeof project.resources === 'string' && /^[^/\\:]+$/.test(project.resources) && !['.', '..'].includes(project.resources) && /^[a-f0-9-]{36}$/i.test(project.snapshot) && Array.isArray(project.projectManifest?.included), '工程入口或资源清单无效'); const checkpoint = `工程文件/${project.resources}/${project.snapshot}`; requireThat((await stat(path.join(root, checkpoint))).isDirectory(), '工程资源目录缺失'); requireThat(project.projectManifest.included.includes('canvas.pcraft') && project.projectManifest.included.every(name => { if (!project.resourcePaths) return entries.get(`${checkpoint}/${name}`)?.category === '工程资源'; return entries.get(project.resourcePaths[name])?.format === path.posix.extname(name).slice(1); }), '工程资源未完整列入交付清单'); const selected = new Set(); let outputCount = 0; for (const [relativePath, record] of entries) { if (record.category !== '工程文件' || record.format !== 'pcraft') continue; const output = Object.entries(outputs).find(([, [name]]) => path.posix.basename(relativePath) === name + '.pcraft'); requireThat(output, `无法识别输出 ${relativePath}`); const [id, [name, ...categories]] = output; selected.add(id); outputCount++; const folder = path.posix.dirname(relativePath).slice('工程文件'.length); requireThat(['psd', 'psb'].some(ext => entries.get(`PSD${folder}/${name}.${ext}`)?.category === 'PSD'), `缺少分层文件 ${relativePath}`); for (const category of categories) { const expectedDir = category + folder; requireThat([...entries.values()].some(row => { if (row.format !== 'jpg' || row.category !== category) return false; const dir = path.posix.dirname(row.relativePath); if (dir === expectedDir) return true; return category === 'SKU' && dir.startsWith(expectedDir + '/') && /^(?:\d+x\d+\/)?[^/]+$/.test(dir.slice(expectedDir.length + 1)); }), `缺少 ${category}${folder}`); } } for (const entry of await readdir(root, { recursive: true, withFileTypes: true })) { const relativePath = path.relative(root, path.join(entry.parentPath, entry.name)).split(path.sep).join('/'); if (relativePath.length > longestRelativePath.length) longestRelativePath = relativePath; if (/[a-f0-9]{64}/i.test(entry.name)) { errors.push({ path: relativePath, message: '文件名或目录名含 64 位哈希', missing: false }); } if (!entry.isFile()) continue; if (relativePath !== '交付清单.json' && !entries.has(relativePath)) { errors.push({ path: relativePath, message: '磁盘文件未列入清单', missing: false }); } } if (longestRelativePath.length > 120) { errors.push({ path: longestRelativePath, message: '相对路径超过 120 字符', missing: false }); } for (const [previous, duplicate] of duplicateLargeFiles) { errors.push({ path: duplicate, message: `大文件内容重复:${previous}`, missing: false }); } requireThat(outputCount === bundle.completedOutputs, '磁盘输出数与清单不符'); for (const id of expected) { if (!selected.has(id)) errors.push({ outputId: id, message: `缺少期望输出 ${id}`, missing: true }); } } catch (error) { errors.push({ message: error.message, missing: error.code === 'ENOENT' || error.message.startsWith('缺少') }); } return { ok: errors.length === 0 && missingOutputs === 0, deliveryDir: root, counts, files, missingOutputs, missing, longestRelativePath, longestRelativePathLength: longestRelativePath.length, duplicateLargeFiles, failedCount: errors.filter(error => !error.missing).length, missingCount: errors.filter(error => error.missing && !error.outputId).length + Math.max(missingOutputs, errors.filter(error => error.missing && error.outputId).length), errors }; } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const { values } = parseArgs({ options: { 'delivery-dir': { type: 'string' }, 'expect-output': { type: 'string', multiple: true }, } }); requireThat(values['delivery-dir'], '请指定 --delivery-dir'); const report = await verifyDeliveryBundle(values['delivery-dir'], values['expect-output']); console.log(JSON.stringify(report, null, 2)); process.exitCode = report.ok ? 0 : 1; }