workbuddy-layered-psd-bridge 1.1.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -24
- package/package.json +4 -1
- package/ps_backend/README.md +6 -4
- package/ps_backend/build_template.jsx +67 -7
- package/ps_backend/cli.mjs +365 -12
- package/ps_backend/tests/font_selection.test.mjs +80 -0
- package/ps_backend/tests/production_preflight.test.mjs +120 -0
- package/src/direct.mjs +30 -8
- package/src/duplicate-audit-core.mjs +217 -0
- package/src/duplicate-audit-runner.mjs +105 -0
- package/src/prepare-worker.mjs +1 -0
- package/src/quality.mjs +204 -0
- package/src/server.mjs +26 -4
- package/src/worker.mjs +55 -1
package/ps_backend/cli.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import fs from 'node:fs';
|
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { normalizeQualitySpec, evaluateQualitySpec, enforceQualitySpec } from '../src/quality.mjs';
|
|
7
8
|
|
|
8
9
|
const BACKEND_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
9
10
|
const TEMPLATE_PATH = path.join(BACKEND_DIR, 'build_template.jsx');
|
|
@@ -105,6 +106,63 @@ function imageDimensions(filePath, mediaType) {
|
|
|
105
106
|
throw new BuildError('JPEG 缺少可识别的尺寸段', 'INVALID_IMAGE');
|
|
106
107
|
} finally { fs.closeSync(fd); }
|
|
107
108
|
}
|
|
109
|
+
|
|
110
|
+
// Photoshop stores document resolution in PSD image resource 1005 as 16.16 PPI values.
|
|
111
|
+
function readPSDResolution(filePath) {
|
|
112
|
+
const fd = fs.openSync(filePath, 'r');
|
|
113
|
+
const size = fs.fstatSync(fd).size;
|
|
114
|
+
function readAt(position, length) {
|
|
115
|
+
assert(position >= 0 && length > 0 && position + length <= size,
|
|
116
|
+
'PSD 分辨率资源不完整', 'INVALID_PSD');
|
|
117
|
+
const bytes = Buffer.alloc(length);
|
|
118
|
+
assert(fs.readSync(fd, bytes, 0, length, position) === length,
|
|
119
|
+
'读取 PSD 分辨率资源失败', 'INVALID_PSD');
|
|
120
|
+
return bytes;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const head = readAt(0, 26);
|
|
124
|
+
assert(head.toString('ascii', 0, 4) === '8BPS' && head.readUInt16BE(4) === 1,
|
|
125
|
+
'Photoshop 输出不是有效 PSD', 'INVALID_PSD');
|
|
126
|
+
const colorModeLength = readAt(26, 4).readUInt32BE(0);
|
|
127
|
+
const sectionLengthAt = 30 + colorModeLength;
|
|
128
|
+
const resourceLength = readAt(sectionLengthAt, 4).readUInt32BE(0);
|
|
129
|
+
const end = sectionLengthAt + 4 + resourceLength;
|
|
130
|
+
assert(end <= size, 'PSD 图片资源段长度无效', 'INVALID_PSD');
|
|
131
|
+
let position = sectionLengthAt + 4;
|
|
132
|
+
while (position < end) {
|
|
133
|
+
assert(position + 7 <= end, 'PSD 图片资源段不完整', 'INVALID_PSD');
|
|
134
|
+
const resource = readAt(position, 7);
|
|
135
|
+
assert(resource.toString('ascii', 0, 4) === '8BIM',
|
|
136
|
+
'PSD 图片资源段标记无效', 'INVALID_PSD');
|
|
137
|
+
const id = resource.readUInt16BE(4);
|
|
138
|
+
const nameBytes = 1 + resource[6];
|
|
139
|
+
const paddedNameBytes = nameBytes + (nameBytes % 2);
|
|
140
|
+
const dataLengthAt = position + 6 + paddedNameBytes;
|
|
141
|
+
assert(dataLengthAt + 4 <= end, 'PSD 图片资源段名称无效', 'INVALID_PSD');
|
|
142
|
+
const dataLength = readAt(dataLengthAt, 4).readUInt32BE(0);
|
|
143
|
+
const dataAt = dataLengthAt + 4;
|
|
144
|
+
const next = dataAt + dataLength + (dataLength % 2);
|
|
145
|
+
assert(next <= end, 'PSD 图片资源段数据长度无效', 'INVALID_PSD');
|
|
146
|
+
if (id === 1005) {
|
|
147
|
+
assert(dataLength >= 16, 'PSD 分辨率资源无效', 'INVALID_PSD');
|
|
148
|
+
const data = readAt(dataAt, 16);
|
|
149
|
+
// Adobe's ResolutionInfo fixed values are always PPI. These flags affect display only.
|
|
150
|
+
const hUnit = data.readUInt16BE(4);
|
|
151
|
+
const vUnit = data.readUInt16BE(12);
|
|
152
|
+
assert((hUnit === 1 || hUnit === 2) && (vUnit === 1 || vUnit === 2),
|
|
153
|
+
'PSD 分辨率显示单位无效', 'INVALID_PSD');
|
|
154
|
+
const horizontalPpi = data.readUInt32BE(0) / 65536;
|
|
155
|
+
const verticalPpi = data.readUInt32BE(8) / 65536;
|
|
156
|
+
assert(horizontalPpi > 0 && verticalPpi > 0, 'PSD 分辨率值无效', 'INVALID_PSD');
|
|
157
|
+
return { horizontal_ppi: horizontalPpi, vertical_ppi: verticalPpi,
|
|
158
|
+
horizontal_display_unit: hUnit === 1 ? 'ppi' : 'ppcm',
|
|
159
|
+
vertical_display_unit: vUnit === 1 ? 'ppi' : 'ppcm' };
|
|
160
|
+
}
|
|
161
|
+
position = next;
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
} finally { fs.closeSync(fd); }
|
|
165
|
+
}
|
|
108
166
|
function validateBounds(value, label, canvas) {
|
|
109
167
|
const b = object(value, label);
|
|
110
168
|
keysOnly(b, ['x','y','width','height'], label);
|
|
@@ -114,9 +172,129 @@ function validateBounds(value, label, canvas) {
|
|
|
114
172
|
const height = number(b.height, `${label}.height`, 0.01, canvas.heightPx * 3);
|
|
115
173
|
return { x, y, width, height };
|
|
116
174
|
}
|
|
175
|
+
|
|
176
|
+
function validateProductionSpec(value) {
|
|
177
|
+
if (value == null) return { mode: 'proof' };
|
|
178
|
+
const raw = object(value, 'productionSpec');
|
|
179
|
+
keysOnly(raw, ['mode','widthMm','heightMm','minEffectivePpi'], 'productionSpec');
|
|
180
|
+
const mode = raw.mode ?? 'proof';
|
|
181
|
+
assert(mode === 'proof' || mode === 'production', 'productionSpec.mode 必须是 proof 或 production');
|
|
182
|
+
const hasWidth = raw.widthMm != null;
|
|
183
|
+
const hasHeight = raw.heightMm != null;
|
|
184
|
+
assert(hasWidth === hasHeight, 'productionSpec.widthMm 和 heightMm 必须同时提供');
|
|
185
|
+
const spec = { mode };
|
|
186
|
+
if (hasWidth) {
|
|
187
|
+
spec.widthMm = number(raw.widthMm, 'productionSpec.widthMm', 1, 100000);
|
|
188
|
+
spec.heightMm = number(raw.heightMm, 'productionSpec.heightMm', 1, 100000);
|
|
189
|
+
}
|
|
190
|
+
if (raw.minEffectivePpi != null) {
|
|
191
|
+
assert(hasWidth, 'productionSpec.minEffectivePpi 需要成品物理尺寸');
|
|
192
|
+
spec.minEffectivePpi = number(raw.minEffectivePpi, 'productionSpec.minEffectivePpi', 1, 1200);
|
|
193
|
+
}
|
|
194
|
+
if (mode === 'production') {
|
|
195
|
+
assert(hasWidth && spec.minEffectivePpi != null,
|
|
196
|
+
'production 模式必须提供 widthMm、heightMm 和按加工工艺确定的 minEffectivePpi',
|
|
197
|
+
'PRODUCTION_SPEC_INCOMPLETE');
|
|
198
|
+
}
|
|
199
|
+
return spec;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function productionPreflight(canvas, layers, assets, spec) {
|
|
203
|
+
const physical = spec.widthMm != null;
|
|
204
|
+
const canvasPpiX = physical ? canvas.widthPx * 25.4 / spec.widthMm : null;
|
|
205
|
+
const canvasPpiY = physical ? canvas.heightPx * 25.4 / spec.heightMm : null;
|
|
206
|
+
const target = spec.minEffectivePpi ?? null;
|
|
207
|
+
const plannedPsdDpi = spec.mode === 'production' ? canvasPpiX : canvas.dpi;
|
|
208
|
+
if (spec.mode === 'production') {
|
|
209
|
+
assert(Number.isFinite(plannedPsdDpi) && plannedPsdDpi >= 1 && plannedPsdDpi <= 30000,
|
|
210
|
+
'成品尺寸对应的 PSD 文档分辨率超出可可靠写入范围(1–30000 PPI);请调整画布像素或成品尺寸。',
|
|
211
|
+
'PRODUCTION_DPI_UNSUPPORTED');
|
|
212
|
+
}
|
|
213
|
+
const report = {
|
|
214
|
+
mode: spec.mode,
|
|
215
|
+
physical_size_mm: physical ? { width: spec.widthMm, height: spec.heightMm } : null,
|
|
216
|
+
target_min_ppi: target,
|
|
217
|
+
canvas: { width_px: canvas.widthPx, height_px: canvas.heightPx,
|
|
218
|
+
requested_dpi_metadata: canvas.dpi, planned_psd_dpi: plannedPsdDpi,
|
|
219
|
+
dpi_effect: 'physical_size_only_no_resampling',
|
|
220
|
+
effective_ppi_x: canvasPpiX, effective_ppi_y: canvasPpiY },
|
|
221
|
+
planned_psd_physical_size_mm: spec.mode === 'production' ? {
|
|
222
|
+
width: canvas.widthPx * 25.4 / plannedPsdDpi,
|
|
223
|
+
height: canvas.heightPx * 25.4 / plannedPsdDpi,
|
|
224
|
+
} : null,
|
|
225
|
+
preview: { max_side_px: 1600, intended_use: 'screen_preview_only' },
|
|
226
|
+
images: [],
|
|
227
|
+
ppi_check_passed: null,
|
|
228
|
+
notes: physical
|
|
229
|
+
? (target == null ? ['已计算有效 PPI,但未提供加工工艺的最低 PPI 门槛,无法判定是否达标。'] : [])
|
|
230
|
+
: ['未提供成品物理尺寸;不能根据 PSD 的 DPI 元数据判断加工清晰度。'],
|
|
231
|
+
};
|
|
232
|
+
if (physical) {
|
|
233
|
+
const aspectDifference = Math.abs(canvas.widthPx / canvas.heightPx - spec.widthMm / spec.heightMm)
|
|
234
|
+
/ (spec.widthMm / spec.heightMm);
|
|
235
|
+
const plannedHeightMm = canvas.heightPx * spec.widthMm / canvas.widthPx;
|
|
236
|
+
const toleranceMm = Math.max(0.5, spec.heightMm * 0.001);
|
|
237
|
+
if (spec.mode === 'production' && Math.abs(plannedHeightMm - spec.heightMm) > toleranceMm) {
|
|
238
|
+
throw new BuildError(`画布比例对应的成品高度为 ${plannedHeightMm.toFixed(2)} mm,要求为 ${spec.heightMm} mm(容差 ${toleranceMm.toFixed(2)} mm);请核对出血、裁切或画布比例。`,
|
|
239
|
+
'PRODUCTION_ASPECT_MISMATCH');
|
|
240
|
+
}
|
|
241
|
+
if (spec.mode === 'proof' && aspectDifference > 0.01)
|
|
242
|
+
report.notes.push('画布宽高比与成品物理尺寸相差超过 1%;请核对是否包含出血或裁切区域。');
|
|
243
|
+
}
|
|
244
|
+
function walk(nodes, ancestorVisible) {
|
|
245
|
+
for (const node of nodes) {
|
|
246
|
+
const visible = ancestorVisible && node.visible !== false && node.opacity !== 0;
|
|
247
|
+
if (node.type === 'group') { walk(node.children, visible); continue; }
|
|
248
|
+
if (node.type !== 'image') continue;
|
|
249
|
+
const asset = assets[node.image.assetId];
|
|
250
|
+
const b = node.bounds;
|
|
251
|
+
const scale = node.image.fit === 'cover'
|
|
252
|
+
? Math.max(b.width / asset.widthPx, b.height / asset.heightPx)
|
|
253
|
+
: Math.min(b.width / asset.widthPx, b.height / asset.heightPx);
|
|
254
|
+
const placedWidth = node.image.fit === 'cover' ? b.width : asset.widthPx * scale;
|
|
255
|
+
const placedHeight = node.image.fit === 'cover' ? b.height : asset.heightPx * scale;
|
|
256
|
+
const placedX = b.x + (b.width - placedWidth) / 2;
|
|
257
|
+
const placedY = b.y + (b.height - placedHeight) / 2;
|
|
258
|
+
let left = placedX, top = placedY, right = placedX + placedWidth, bottom = placedY + placedHeight;
|
|
259
|
+
if (node.rotation) {
|
|
260
|
+
const radians = node.rotation * Math.PI / 180;
|
|
261
|
+
const halfWidth = placedWidth / 2, halfHeight = placedHeight / 2;
|
|
262
|
+
const rotatedHalfWidth = Math.abs(Math.cos(radians) * halfWidth) + Math.abs(Math.sin(radians) * halfHeight);
|
|
263
|
+
const rotatedHalfHeight = Math.abs(Math.sin(radians) * halfWidth) + Math.abs(Math.cos(radians) * halfHeight);
|
|
264
|
+
const centerX = placedX + halfWidth, centerY = placedY + halfHeight;
|
|
265
|
+
left = centerX - rotatedHalfWidth; right = centerX + rotatedHalfWidth;
|
|
266
|
+
top = centerY - rotatedHalfHeight; bottom = centerY + rotatedHalfHeight;
|
|
267
|
+
}
|
|
268
|
+
const intersectsCanvas = right > 0 && bottom > 0 && left < canvas.widthPx && top < canvas.heightPx;
|
|
269
|
+
const ppiX = physical ? canvasPpiX / scale : null;
|
|
270
|
+
const ppiY = physical ? canvasPpiY / scale : null;
|
|
271
|
+
const ppi = physical ? Math.min(ppiX, ppiY) : null;
|
|
272
|
+
report.images.push({ layer_id: node.id, layer_name: node.name, asset_id: node.image.assetId,
|
|
273
|
+
visible, intersects_canvas: intersectsCanvas, fit: node.image.fit,
|
|
274
|
+
source_width_px: asset.widthPx, source_height_px: asset.heightPx,
|
|
275
|
+
target_bounds_px: b, placed_width_px: asset.widthPx * scale,
|
|
276
|
+
placed_height_px: asset.heightPx * scale, scale,
|
|
277
|
+
effective_ppi_x: ppiX, effective_ppi_y: ppiY, effective_ppi: ppi,
|
|
278
|
+
below_target: visible && intersectsCanvas && target != null ? ppi + 1e-9 < target : null });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
walk(layers, true);
|
|
282
|
+
if (target != null && physical) {
|
|
283
|
+
const canvasLow = Math.min(canvasPpiX, canvasPpiY) + 1e-9 < target;
|
|
284
|
+
const low = report.images.filter((item) => item.below_target);
|
|
285
|
+
report.ppi_check_passed = !canvasLow && low.length === 0;
|
|
286
|
+
if (canvasLow) report.notes.push(`画布有效分辨率 ${Math.min(canvasPpiX, canvasPpiY).toFixed(1)} PPI 低于要求 ${target} PPI。`);
|
|
287
|
+
if (low.length) report.notes.push(`低分辨率图片层:${low.map((item) => `${item.layer_name} (${item.effective_ppi.toFixed(1)} PPI)`).join(',')}。`);
|
|
288
|
+
if (spec.mode === 'production' && !report.ppi_check_passed) {
|
|
289
|
+
throw new BuildError(report.notes.join(' '), 'PRODUCTION_PPI_TOO_LOW');
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return report;
|
|
293
|
+
}
|
|
294
|
+
|
|
117
295
|
function validateManifest(value, dataRoot) {
|
|
118
296
|
const manifest = object(value, 'manifest');
|
|
119
|
-
keysOnly(manifest, ['schema','canvas','layers','assets','source','warnings'], 'manifest');
|
|
297
|
+
keysOnly(manifest, ['schema','canvas','layers','assets','source','warnings','qualitySpec','productionSpec'], 'manifest');
|
|
120
298
|
assert(manifest.schema === SCHEMA, `manifest.schema 必须是 ${SCHEMA}`);
|
|
121
299
|
const canvasRaw = object(manifest.canvas, 'canvas');
|
|
122
300
|
keysOnly(canvasRaw, ['name','widthPx','heightPx','dpi','colorMode'], 'canvas');
|
|
@@ -130,6 +308,7 @@ function validateManifest(value, dataRoot) {
|
|
|
130
308
|
assert(Number.isInteger(canvas.widthPx) && Number.isInteger(canvas.heightPx), '画布像素尺寸必须是整数');
|
|
131
309
|
assert(canvas.colorMode === 'RGB' || canvas.colorMode === 'CMYK', '画布色彩模式必须为 RGB 或 CMYK');
|
|
132
310
|
assert(canvas.widthPx * canvas.heightPx <= MAX_PIXELS, `画布不能超过 ${MAX_PIXELS} 像素`, 'CANVAS_TOO_LARGE');
|
|
311
|
+
const productionSpec = validateProductionSpec(manifest.productionSpec);
|
|
133
312
|
const assetsRaw = object(manifest.assets || {}, 'assets');
|
|
134
313
|
const assets = Object.create(null);
|
|
135
314
|
let totalAssetBytes = 0;
|
|
@@ -226,16 +405,28 @@ function validateManifest(value, dataRoot) {
|
|
|
226
405
|
}
|
|
227
406
|
const layers = manifest.layers.map((raw, index) => layer(raw, `layers[${index}]`, 0));
|
|
228
407
|
assert(layers.length > 0, '海报没有图层');
|
|
229
|
-
|
|
408
|
+
const qualitySpec = manifest.qualitySpec === undefined ? undefined : normalizeQualitySpec(manifest.qualitySpec);
|
|
409
|
+
const quality_report = evaluateQualitySpec(qualitySpec, layers, canvas);
|
|
410
|
+
enforceQualitySpec(quality_report);
|
|
411
|
+
const production_preflight = productionPreflight(canvas, layers, assets, productionSpec);
|
|
412
|
+
return { schema: SCHEMA, canvas, layers, assets, qualitySpec, quality_report,
|
|
413
|
+
productionSpec, production_preflight,
|
|
414
|
+
documentDpi: production_preflight.canvas.planned_psd_dpi,
|
|
415
|
+
totalLayers, totalLayerPixels, totalAssetPixels, totalAssetBytes };
|
|
230
416
|
}
|
|
231
417
|
|
|
232
418
|
function hardwareReport(canvas, layerCount, outputDir, assetPixels = 0, assetBytes = 0,
|
|
233
|
-
dataRoot = outputDir, layerPixels = canvas.widthPx * canvas.heightPx * layerCount
|
|
419
|
+
dataRoot = outputDir, layerPixels = canvas.widthPx * canvas.heightPx * layerCount,
|
|
420
|
+
memory = { totalBytes: os.totalmem(), freeBytes: os.freemem() }) {
|
|
234
421
|
const pixels = canvas.widthPx * canvas.heightPx;
|
|
235
|
-
const ram =
|
|
422
|
+
const ram = memory.totalBytes;
|
|
423
|
+
const freeRam = memory.freeBytes;
|
|
236
424
|
const estimatedRam = pixels * 4 * 3 + layerPixels * 4 * 1.5 + assetPixels * 4 * 1.5;
|
|
237
425
|
const estimatedDisk = pixels * 4 * 2 + layerPixels * 4 + assetPixels * 4 + 128 * 1024 * 1024;
|
|
238
|
-
const
|
|
426
|
+
const estimatedPsdUncompressed = pixels * 4 + layerPixels * 4;
|
|
427
|
+
const report = { architecture: os.arch(), ram_bytes: ram, free_ram_bytes: freeRam,
|
|
428
|
+
estimated_ram_bytes: Math.ceil(estimatedRam),
|
|
429
|
+
estimated_psd_uncompressed_bytes: Math.ceil(estimatedPsdUncompressed),
|
|
239
430
|
estimated_disk_bytes: Math.ceil(estimatedDisk), free_disk_bytes: null, free_data_disk_bytes: null, warnings: [] };
|
|
240
431
|
try {
|
|
241
432
|
const stat = fs.statfsSync(outputDir);
|
|
@@ -246,6 +437,18 @@ function hardwareReport(canvas, layerCount, outputDir, assetPixels = 0, assetByt
|
|
|
246
437
|
report.free_data_disk_bytes = Number(stat.bavail) * Number(stat.bsize);
|
|
247
438
|
} catch { report.warnings.push('无法读取工作盘可用空间,建稿前请自行确认。'); }
|
|
248
439
|
if (estimatedRam > ram * 0.75) throw new BuildError('画布和图层相对本机内存过大;请降低像素尺寸或减少图层。', 'INSUFFICIENT_MEMORY');
|
|
440
|
+
if (Number.isFinite(freeRam) && freeRam > 0) {
|
|
441
|
+
if (estimatedRam > freeRam * 1.25) {
|
|
442
|
+
throw new BuildError('当前可用内存不足以安全建稿;请关闭占内存的程序、降低像素尺寸或减少图层后重试。',
|
|
443
|
+
'INSUFFICIENT_AVAILABLE_MEMORY');
|
|
444
|
+
}
|
|
445
|
+
if (estimatedRam > freeRam * 0.75) {
|
|
446
|
+
report.warnings.push('当前可用内存接近建稿估计值;Photoshop 可能使用暂存盘,请确保空间充足。');
|
|
447
|
+
}
|
|
448
|
+
} else report.warnings.push('无法读取当前可用内存,建稿前请自行确认。');
|
|
449
|
+
if (estimatedPsdUncompressed > 1.5 * 1024 ** 3) {
|
|
450
|
+
report.warnings.push('图层像素数据估计较大,PSD 可能接近文件格式容量上限;当前版本不导出 PSB,请先缩小画布或减少图层。');
|
|
451
|
+
}
|
|
249
452
|
if (report.free_disk_bytes != null && estimatedDisk * 1.5 > report.free_disk_bytes) {
|
|
250
453
|
throw new BuildError('输出盘剩余空间不足以安全生成 PSD;请释放空间或更换数据目录。', 'INSUFFICIENT_DISK');
|
|
251
454
|
}
|
|
@@ -256,7 +459,8 @@ function hardwareReport(canvas, layerCount, outputDir, assetPixels = 0, assetByt
|
|
|
256
459
|
}
|
|
257
460
|
|
|
258
461
|
function defaultDataRoot() {
|
|
259
|
-
return process.env.WORKBUDDY_PSD_DATA_DIR || process.env.
|
|
462
|
+
return process.env.WORKBUDDY_PSD_DATA_DIR || process.env.ZAOJIAN_PSD_DATA_DIR ||
|
|
463
|
+
process.env.ZAOJIAN_PSD_DATA_ROOT ||
|
|
260
464
|
path.join(os.homedir(), 'Documents', 'WorkBuddyLayeredPSD', 'work');
|
|
261
465
|
}
|
|
262
466
|
function preparePaths(rawDataRoot, rawOutputRoot, rawOutputDir, rawManifest) {
|
|
@@ -365,6 +569,51 @@ function verifyLayerTree(file, layers) {
|
|
|
365
569
|
types: expected.reduce((counts, node) => { counts[node.type] = (counts[node.type] || 0) + 1; return counts; }, {}) };
|
|
366
570
|
}
|
|
367
571
|
|
|
572
|
+
function planBackgroundDiagnostic(clean) {
|
|
573
|
+
const requested = clean.qualitySpec?.expectedElements
|
|
574
|
+
.filter((element) => element.mustBeIndependent) ?? [];
|
|
575
|
+
if (!requested.length) return null;
|
|
576
|
+
const byId = new Map();
|
|
577
|
+
function walk(nodes) {
|
|
578
|
+
for (const node of nodes) {
|
|
579
|
+
byId.set(node.id, node);
|
|
580
|
+
if (node.type === 'group') walk(node.children);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
walk(clean.layers);
|
|
584
|
+
const hidden = [];
|
|
585
|
+
const skipped = [];
|
|
586
|
+
for (const element of requested) {
|
|
587
|
+
const reported = clean.quality_report?.elements.find((item) => item.id === element.id);
|
|
588
|
+
const layer = element.layerId ? byId.get(element.layerId) : null;
|
|
589
|
+
if (!reported?.structurally_editable || !layer || layer.type === 'group') {
|
|
590
|
+
skipped.push({ element_id: element.id, layer_id: element.layerId ?? null,
|
|
591
|
+
reason: 'missing_hidden_shared_or_type_mismatched_layer' });
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
const b = layer.bounds;
|
|
595
|
+
const coversCanvas = (layer.type === 'image' || layer.type === 'rect') &&
|
|
596
|
+
b.x <= clean.canvas.widthPx * 0.05 && b.y <= clean.canvas.heightPx * 0.05 &&
|
|
597
|
+
b.x + b.width >= clean.canvas.widthPx * 0.95 &&
|
|
598
|
+
b.y + b.height >= clean.canvas.heightPx * 0.95;
|
|
599
|
+
if (element.diagnosticRole === 'backdrop') {
|
|
600
|
+
skipped.push({ element_id: element.id, layer_id: element.layerId,
|
|
601
|
+
reason: 'explicit_backdrop_kept_visible' });
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
if (coversCanvas && element.diagnosticRole !== 'foreground') {
|
|
605
|
+
skipped.push({ element_id: element.id, layer_id: element.layerId,
|
|
606
|
+
reason: 'ambiguous_full_canvas_requires_role' });
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
hidden.push(element.layerId);
|
|
610
|
+
}
|
|
611
|
+
return { requested_element_ids: requested.map((element) => element.id),
|
|
612
|
+
hidden_layer_ids: [...new Set(hidden)], skipped_elements: skipped,
|
|
613
|
+
declared_element_coverage_complete: hidden.length > 0 && skipped.every((item) =>
|
|
614
|
+
item.reason === 'explicit_backdrop_kept_visible') };
|
|
615
|
+
}
|
|
616
|
+
|
|
368
617
|
export async function buildPSD(manifest, { dataRoot, outputRoot, outputDir, progId = 'Photoshop.Application' }) {
|
|
369
618
|
assert(process.platform === 'win32', '当前版本仅支持 Windows 桌面 Photoshop', 'UNSUPPORTED_OS');
|
|
370
619
|
const root = fs.realpathSync(dataRoot);
|
|
@@ -394,10 +643,20 @@ export async function buildPSD(manifest, { dataRoot, outputRoot, outputDir, prog
|
|
|
394
643
|
}
|
|
395
644
|
const psdPath = path.join(output, 'poster.psd');
|
|
396
645
|
const previewPath = path.join(output, 'preview.jpg');
|
|
646
|
+
const diagnosticPlan = planBackgroundDiagnostic(clean);
|
|
647
|
+
const diagnosticLayerIds = diagnosticPlan?.hidden_layer_ids ?? [];
|
|
648
|
+
const diagnosticCoverageWarning = diagnosticPlan && !diagnosticPlan.declared_element_coverage_complete
|
|
649
|
+
? '已声明元素的底图诊断覆盖不完整;请检查 skipped_elements,给全画布图层声明 diagnosticRole 或手动检查。'
|
|
650
|
+
: null;
|
|
651
|
+
const backgroundDiagnosticPath = diagnosticLayerIds.length
|
|
652
|
+
? path.join(output, 'background_diagnostic.jpg') : null;
|
|
397
653
|
const statusPath = path.join(cache, 'status.txt');
|
|
398
654
|
const layerReportPath = path.join(cache, 'layer-report.txt');
|
|
399
655
|
const jsxPath = path.join(cache, 'build.jsx');
|
|
400
|
-
const job = { ...clean, assets: stagedAssets, psdPath, previewPath,
|
|
656
|
+
const job = { ...clean, assets: stagedAssets, psdPath, previewPath,
|
|
657
|
+
...(backgroundDiagnosticPath ? { backgroundDiagnosticPath,
|
|
658
|
+
backgroundDiagnosticLayerIds: diagnosticLayerIds } : {}),
|
|
659
|
+
statusPath, layerReportPath };
|
|
401
660
|
const template = fs.readFileSync(TEMPLATE_PATH, 'utf8');
|
|
402
661
|
fs.writeFileSync(jsxPath, `#target photoshop\nvar JOB = ${asciiJsLiteral(job)};\n${template}`, 'utf8');
|
|
403
662
|
try {
|
|
@@ -414,16 +673,110 @@ export async function buildPSD(manifest, { dataRoot, outputRoot, outputDir, prog
|
|
|
414
673
|
const jpgInfo = fs.statSync(previewPath);
|
|
415
674
|
const psdFile = fs.openSync(psdPath, 'r');
|
|
416
675
|
const jpgFile = fs.openSync(previewPath, 'r');
|
|
417
|
-
const psdHead = Buffer.alloc(
|
|
676
|
+
const psdHead = Buffer.alloc(26), jpgHead = Buffer.alloc(2);
|
|
418
677
|
try {
|
|
419
|
-
fs.readSync(psdFile, psdHead, 0,
|
|
678
|
+
assert(fs.readSync(psdFile, psdHead, 0, 26, 0) === 26,
|
|
679
|
+
'Photoshop 输出 PSD 文件头不完整', 'INVALID_PSD');
|
|
420
680
|
fs.readSync(jpgFile, jpgHead, 0, 2, 0);
|
|
421
681
|
} finally { fs.closeSync(psdFile); fs.closeSync(jpgFile); }
|
|
422
|
-
assert(psdInfo.size > 32 && psdHead.toString('ascii') === '8BPS', 'Photoshop 输出不是有效 PSD', 'INVALID_PSD');
|
|
682
|
+
assert(psdInfo.size > 32 && psdHead.toString('ascii', 0, 4) === '8BPS', 'Photoshop 输出不是有效 PSD', 'INVALID_PSD');
|
|
423
683
|
assert(jpgInfo.size > 4 && jpgHead[0] === 0xff && jpgHead[1] === 0xd8, 'Photoshop 预览不是有效 JPEG', 'INVALID_PREVIEW');
|
|
684
|
+
const psdResolution = readPSDResolution(psdPath);
|
|
685
|
+
const actualPhysical = psdResolution ? {
|
|
686
|
+
width: psdHead.readUInt32BE(18) * 25.4 / psdResolution.horizontal_ppi,
|
|
687
|
+
height: psdHead.readUInt32BE(14) * 25.4 / psdResolution.vertical_ppi,
|
|
688
|
+
} : null;
|
|
689
|
+
const psdDimensions = { width_px: psdHead.readUInt32BE(18), height_px: psdHead.readUInt32BE(14),
|
|
690
|
+
dpi_metadata: psdResolution?.horizontal_ppi ?? null,
|
|
691
|
+
dpi_metadata_x: psdResolution?.horizontal_ppi ?? null,
|
|
692
|
+
dpi_metadata_y: psdResolution?.vertical_ppi ?? null,
|
|
693
|
+
dpi_display_unit_x: psdResolution?.horizontal_display_unit ?? null,
|
|
694
|
+
dpi_display_unit_y: psdResolution?.vertical_display_unit ?? null,
|
|
695
|
+
physical_size_mm: actualPhysical };
|
|
696
|
+
assert(psdDimensions.width_px === clean.canvas.widthPx && psdDimensions.height_px === clean.canvas.heightPx,
|
|
697
|
+
'Photoshop 输出 PSD 画布尺寸与设计清单不一致', 'PSD_SIZE_MISMATCH');
|
|
698
|
+
if (clean.productionSpec.mode === 'production') {
|
|
699
|
+
assert(psdResolution, 'Photoshop 输出 PSD 缺少分辨率元数据,无法核对成品尺寸', 'PSD_RESOLUTION_MISSING');
|
|
700
|
+
const tolerance = Math.max(0.25, clean.documentDpi * 0.005);
|
|
701
|
+
assert(Math.abs(psdResolution.horizontal_ppi - clean.documentDpi) <= tolerance &&
|
|
702
|
+
Math.abs(psdResolution.vertical_ppi - clean.documentDpi) <= tolerance,
|
|
703
|
+
'Photoshop 输出 PSD 的分辨率元数据与成品尺寸计划不一致', 'PSD_RESOLUTION_MISMATCH');
|
|
704
|
+
const wanted = clean.production_preflight.physical_size_mm;
|
|
705
|
+
const widthToleranceMm = Math.max(0.5, wanted.width * 0.001);
|
|
706
|
+
const heightToleranceMm = Math.max(0.5, wanted.height * 0.001);
|
|
707
|
+
assert(Math.abs(actualPhysical.width - wanted.width) <= widthToleranceMm &&
|
|
708
|
+
Math.abs(actualPhysical.height - wanted.height) <= heightToleranceMm,
|
|
709
|
+
`Photoshop 输出 PSD 的实际物理尺寸为 ${actualPhysical.width.toFixed(2)} × ${actualPhysical.height.toFixed(2)} mm,要求为 ${wanted.width} × ${wanted.height} mm。`,
|
|
710
|
+
'PSD_PHYSICAL_SIZE_MISMATCH');
|
|
711
|
+
}
|
|
712
|
+
const previewSize = imageDimensions(previewPath, 'image/jpeg');
|
|
713
|
+
const previewDimensions = { width_px: previewSize.widthPx, height_px: previewSize.heightPx };
|
|
714
|
+
let backgroundDiagnostic;
|
|
715
|
+
let diagnosticValidationWarning = null;
|
|
716
|
+
if (backgroundDiagnosticPath) {
|
|
717
|
+
const scriptFailure = script.warnings.find((warning) =>
|
|
718
|
+
warning.startsWith('BACKGROUND_DIAGNOSTIC_FAILED: '));
|
|
719
|
+
try {
|
|
720
|
+
if (scriptFailure) throw new Error(scriptFailure.slice('BACKGROUND_DIAGNOSTIC_FAILED: '.length));
|
|
721
|
+
if (!fs.existsSync(backgroundDiagnosticPath)) throw new Error('Photoshop 未生成诊断 JPG');
|
|
722
|
+
const diagnosticInfo = fs.statSync(backgroundDiagnosticPath);
|
|
723
|
+
if (diagnosticInfo.size <= 4) throw new Error('诊断 JPG 文件过小');
|
|
724
|
+
const diagnosticSize = imageDimensions(backgroundDiagnosticPath, 'image/jpeg');
|
|
725
|
+
backgroundDiagnostic = {
|
|
726
|
+
generated: true, path: backgroundDiagnosticPath, bytes: diagnosticInfo.size,
|
|
727
|
+
dimensions: { width_px: diagnosticSize.widthPx, height_px: diagnosticSize.heightPx },
|
|
728
|
+
hidden_layer_ids: diagnosticLayerIds,
|
|
729
|
+
requested_element_ids: diagnosticPlan.requested_element_ids,
|
|
730
|
+
skipped_elements: diagnosticPlan.skipped_elements,
|
|
731
|
+
declared_element_coverage_complete: diagnosticPlan.declared_element_coverage_complete,
|
|
732
|
+
diagnostic_scope: 'declared_quality_elements_only',
|
|
733
|
+
visual_review_required: true, visual_verified: false,
|
|
734
|
+
instruction: '将此图与完整预览及参考图对照,检查底图残留原字、旧标志、旧主体或遮挡空洞;不能仅凭文件生成就宣称通过。',
|
|
735
|
+
};
|
|
736
|
+
} catch (error) {
|
|
737
|
+
diagnosticValidationWarning = scriptFailure ? null :
|
|
738
|
+
'底图残影诊断图未生成或无效:' + String(error.message || error);
|
|
739
|
+
backgroundDiagnostic = {
|
|
740
|
+
generated: false, path: null, hidden_layer_ids: [],
|
|
741
|
+
requested_element_ids: diagnosticPlan.requested_element_ids,
|
|
742
|
+
attempted_hidden_layer_ids: diagnosticLayerIds,
|
|
743
|
+
skipped_elements: diagnosticPlan.skipped_elements,
|
|
744
|
+
declared_element_coverage_complete: false,
|
|
745
|
+
diagnostic_scope: 'declared_quality_elements_only',
|
|
746
|
+
visual_review_required: true, visual_verified: false,
|
|
747
|
+
error: String(error.message || error),
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
} else if (diagnosticPlan) {
|
|
751
|
+
backgroundDiagnostic = {
|
|
752
|
+
generated: false, path: null, hidden_layer_ids: [],
|
|
753
|
+
requested_element_ids: diagnosticPlan.requested_element_ids,
|
|
754
|
+
skipped_elements: diagnosticPlan.skipped_elements,
|
|
755
|
+
declared_element_coverage_complete: false,
|
|
756
|
+
diagnostic_scope: 'declared_quality_elements_only',
|
|
757
|
+
visual_review_required: true, visual_verified: false,
|
|
758
|
+
reason: '没有可隐藏的独立前景层;全画布底图会保留可见,其余元素需检查映射。',
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
const productionReport = { ...clean.production_preflight,
|
|
762
|
+
preview: { ...clean.production_preflight.preview, ...previewDimensions },
|
|
763
|
+
actual_psd_physical_size_mm: actualPhysical,
|
|
764
|
+
physical_size_deviation_mm: actualPhysical && clean.production_preflight.physical_size_mm ? {
|
|
765
|
+
width: actualPhysical.width - clean.production_preflight.physical_size_mm.width,
|
|
766
|
+
height: actualPhysical.height - clean.production_preflight.physical_size_mm.height,
|
|
767
|
+
} : null };
|
|
424
768
|
return { ok: true, psd_path: psdPath, preview_path: previewPath, photoshop_version: status.photoshop_version,
|
|
425
769
|
layer_count: script.layer_count, psd_bytes: psdInfo.size, preview_bytes: jpgInfo.size,
|
|
426
|
-
|
|
770
|
+
psd_dimensions: psdDimensions, preview_dimensions: previewDimensions,
|
|
771
|
+
production_preflight: productionReport,
|
|
772
|
+
...(clean.quality_report ? { quality_report: clean.quality_report } : {}),
|
|
773
|
+
...(backgroundDiagnostic ? { background_diagnostic: backgroundDiagnostic } : {}),
|
|
774
|
+
layer_tree: layerTree, hardware,
|
|
775
|
+
warnings: [...hardware.warnings, ...(clean.production_preflight.physical_size_mm ? clean.production_preflight.notes : []),
|
|
776
|
+
...(clean.quality_report?.issues.map((issue) => issue.message) ?? []),
|
|
777
|
+
...script.warnings, ...(diagnosticValidationWarning ? [diagnosticValidationWarning] : []),
|
|
778
|
+
...(diagnosticCoverageWarning ? [diagnosticCoverageWarning] : [])],
|
|
779
|
+
output_dir: output };
|
|
427
780
|
}
|
|
428
781
|
|
|
429
782
|
function parseArgs(argv) {
|
|
@@ -463,4 +816,4 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
|
|
|
463
816
|
}
|
|
464
817
|
}
|
|
465
818
|
|
|
466
|
-
export { validateManifest, hardwareReport, photoshopStatus };
|
|
819
|
+
export { validateManifest, productionPreflight, readPSDResolution, hardwareReport, photoshopStatus };
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import test from 'node:test';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import vm from 'node:vm';
|
|
6
|
+
|
|
7
|
+
const source = readFileSync(fileURLToPath(new URL('../build_template.jsx', import.meta.url)), 'utf8');
|
|
8
|
+
const startMarker = '// FONT_SELECTION_START';
|
|
9
|
+
const endMarker = '// FONT_SELECTION_END';
|
|
10
|
+
const start = source.indexOf(startMarker);
|
|
11
|
+
const end = source.indexOf(endMarker);
|
|
12
|
+
assert.ok(start >= 0 && end > start, 'font selection block must be present in the Photoshop script');
|
|
13
|
+
const fontSelectionSource = source.slice(start + startMarker.length, end);
|
|
14
|
+
|
|
15
|
+
function selectFont(fonts, fontFamily, fontWeight) {
|
|
16
|
+
const installed = new Set(fonts.map((font) => font.postScriptName));
|
|
17
|
+
let selected = null;
|
|
18
|
+
const textItem = {};
|
|
19
|
+
Object.defineProperty(textItem, 'font', {
|
|
20
|
+
get() { return selected; },
|
|
21
|
+
set(value) {
|
|
22
|
+
if (!installed.has(value)) throw new Error(`Font unavailable: ${value}`);
|
|
23
|
+
selected = value;
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
const context = { app: { fonts }, ZJ_WARNINGS: [] };
|
|
27
|
+
vm.runInNewContext(fontSelectionSource, context, { timeout: 1000 });
|
|
28
|
+
context.zjSetFont(textItem, { fontFamily, fontWeight }, '标题');
|
|
29
|
+
return { selected, warnings: Array.from(context.ZJ_WARNINGS) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
test('localized Photoshop family with matching PostScript name is not substituted', () => {
|
|
33
|
+
const result = selectFont([
|
|
34
|
+
{ family: '微软雅黑', postScriptName: 'MicrosoftYaHei', style: '常规' },
|
|
35
|
+
], 'Microsoft YaHei', 400);
|
|
36
|
+
assert.equal(result.selected, 'MicrosoftYaHei');
|
|
37
|
+
assert.deepEqual(result.warnings, []);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('localized bold variant is selected by PostScript family and weight', () => {
|
|
41
|
+
const result = selectFont([
|
|
42
|
+
{ family: '微软雅黑', postScriptName: 'MicrosoftYaHei', style: '常规' },
|
|
43
|
+
{ family: '微软雅黑', postScriptName: 'MicrosoftYaHei-Bold', style: '粗体' },
|
|
44
|
+
], 'Microsoft YaHei', 700);
|
|
45
|
+
assert.equal(result.selected, 'MicrosoftYaHei-Bold');
|
|
46
|
+
assert.deepEqual(result.warnings, []);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('a truly unavailable weight still produces a weight warning', () => {
|
|
50
|
+
const result = selectFont([
|
|
51
|
+
{ family: '微软雅黑', postScriptName: 'MicrosoftYaHei', style: '常规' },
|
|
52
|
+
], 'Microsoft YaHei', 700);
|
|
53
|
+
assert.equal(result.selected, 'MicrosoftYaHei');
|
|
54
|
+
assert.deepEqual(result.warnings, ['Requested font weight unavailable for 标题; used MicrosoftYaHei']);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('a missing family uses an installed fallback and reports it', () => {
|
|
58
|
+
const result = selectFont([
|
|
59
|
+
{ family: 'Arial', postScriptName: 'ArialMT', style: 'Regular' },
|
|
60
|
+
], 'Nonexistent Poster Font', 400);
|
|
61
|
+
assert.equal(result.selected, 'ArialMT');
|
|
62
|
+
assert.deepEqual(result.warnings, ["Missing font 'Nonexistent Poster Font' on 标题; used ArialMT"]);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('a family prefix is not mistaken for the requested family', () => {
|
|
66
|
+
const result = selectFont([
|
|
67
|
+
{ family: 'Arial Narrow', postScriptName: 'ArialNarrow-Bold', style: 'Bold' },
|
|
68
|
+
{ family: 'Arial', postScriptName: 'Arial-BoldMT', style: 'Bold' },
|
|
69
|
+
], 'Arial', 700);
|
|
70
|
+
assert.equal(result.selected, 'Arial-BoldMT');
|
|
71
|
+
assert.deepEqual(result.warnings, []);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('the word bold inside a family name does not mark its regular face bold', () => {
|
|
75
|
+
const result = selectFont([
|
|
76
|
+
{ family: 'Boldface Sans', postScriptName: 'BoldfaceSans-Regular', style: 'Regular' },
|
|
77
|
+
], 'Boldface Sans', 400);
|
|
78
|
+
assert.equal(result.selected, 'BoldfaceSans-Regular');
|
|
79
|
+
assert.deepEqual(result.warnings, []);
|
|
80
|
+
});
|