366 lines
21 KiB
JavaScript
366 lines
21 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs/promises';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import {EnterpriseTemplates} from '../src/enterprise-templates.mjs';
|
|
import {normalizeTemplateMapping} from '../src/template-mapping.mjs';
|
|
|
|
const sha='a'.repeat(64), version='b'.repeat(32), setId='c'.repeat(32);
|
|
const file=(fileId,ext)=>({fileId,name:fileId+ext,path:fileId+ext,revision:version,sha256:sha,size:100});
|
|
const attachment=(id,role,ext,status='available')=>({id,role,status,required:true,file:file(id,ext)});
|
|
const sku=(id,status,mappingStatus='available')=>({id,name:id,status,assets:[
|
|
attachment('original','original','.psd'),attachment('mapping','mapping','.json',mappingStatus),attachment('preview','preview','.jpg')
|
|
]});
|
|
const base={brandName:'顾家',categoryName:'SKU',brandId:'ekb:brand:顾家',categoryId:'ekb:category:SKU'};
|
|
const resourceSet={resourceSetId:setId,name:'顾家 SKU',brand:'顾家',category:'SKU',key:'GUJIA-SKU'};
|
|
const library={resourceSets:{schemaVersion:1,listTool:'list_resource_sets',getTool:'get_resource_set'}};
|
|
const bounds={left:0,top:0,right:600,bottom:500};
|
|
const mapping={schema_version:1,template:{sha256:sha.toUpperCase(),canvas:{width:1440,height:1440}},
|
|
production_profile:{schemaVersion:1,copyRules:{'K01-color':{pictures:['K01-product']}}},
|
|
main_image:{layer:'产品图',original_bounds:bounds,fill_requirements:'自然侧光,展示真实木纹。',
|
|
source_policy:'product',production_rule:{source:'product',focus:'同款整体及颜色'}},
|
|
text_layers:{color:{layer:'产品颜色',safe_bounds:bounds,maxLines:2,style_roles:['label']}}};
|
|
|
|
async function fixture(t,{parts=[sku('default','available')],call,readDocument}={}) {
|
|
const root=await fs.mkdtemp(path.join(os.tmpdir(),'resource-map-test-'));
|
|
t.after(()=>fs.rm(root,{recursive:true,force:true}));
|
|
const calls=[];
|
|
const client={
|
|
connection:{tools:new Map([['get_files',{}]])},
|
|
async call(name,args){
|
|
calls.push([name,args]);
|
|
const result=await call?.(name,args);
|
|
if(result)return result;
|
|
if(name==='list_libraries')return {result:library};
|
|
if(name==='list_resource_sets')return {result:{entries:[resourceSet,{...resourceSet,resourceSetId:'d'.repeat(32)}]}};
|
|
if(name==='get_resource_set')return {result:{resourceSet,components:parts}};
|
|
if(name==='read_image')return {result:{sourceId:'preview',revision:version},images:[{data:'AQID'}]};
|
|
if(name==='get_files')return {result:{results:args.files.map(({fileId})=>({status:200,fileId,file:file(fileId,'.psd')}))}};
|
|
throw Error(name);
|
|
},
|
|
async readDocument(id,revision,_options,read) {
|
|
return read(async()=>{
|
|
calls.push(['read_text',{fileId:id,revision}]);
|
|
return await readDocument?.()??{result:{sourceId:id,text:JSON.stringify(mapping)}};
|
|
});
|
|
},
|
|
async download(args,{metadata}){
|
|
calls.push(['download',{args,metadata}]);
|
|
return {result:{localPath:path.join(root,'verified.psd')}};
|
|
}
|
|
};
|
|
const service=new EnterpriseTemplates(root,client);
|
|
return {calls,service,request:(input,options)=>service.request({...base,...input},options)};
|
|
}
|
|
|
|
test('resource map lists every candidate using exact filters and does not read a pack until selected',async t=>{
|
|
const {calls,request}=await fixture(t);
|
|
const result=await request({action:'catalog',query:'GUJIA'});
|
|
assert.equal(result.items.length,2);
|
|
assert.deepEqual(calls,[['list_libraries',{}],['list_resource_sets',{brand:'顾家',category:'SKU',query:'GUJIA',limit:100}]]);
|
|
const detail=await request({action:'resource-set',resourceSetId:setId});
|
|
assert.equal(detail.items[0].kind,'sku_images');
|
|
assert.equal(calls.at(-1)[0],'get_resource_set');
|
|
});
|
|
|
|
test('a selected SKU pins the mapping and original; preparing uses only those pins and no release catalog',async t=>{
|
|
const {calls,request}=await fixture(t);
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'});
|
|
assert.ok(result.imagePath);
|
|
assert.equal(result.pack.outputs[0].slots[1].psLayer.path,'产品颜色');
|
|
assert.deepEqual(result.pack.outputs[0].slots[1].styleRoles,['label']);
|
|
assert.equal(result.pack.outputs[0].slots[1].maxLines,2);
|
|
assert.equal(result.pack.outputs[0].slots[0].imagePrompt,'自然侧光,展示真实木纹。');
|
|
assert.equal(result.pack.outputs[0].slots[0].sourcePolicy,'product');
|
|
assert.deepEqual(result.pack.outputs[0].slots[0].productionRule,{source:'product',focus:'同款整体及颜色'});
|
|
assert.deepEqual(result.pack.productionProfiles.sku_images,mapping.production_profile);
|
|
assert.equal(result.pack.enterprise.component,'sku_images');
|
|
assert.equal(result.pack.enterprise.originalSha256,sha);
|
|
const prepared=await request({action:'prepare',...result.pack.enterprise,pinnedPack:result.pack});
|
|
assert.deepEqual(prepared.pack,result.pack);
|
|
assert.deepEqual(calls.filter(([name])=>name==='read_text'),[['read_text',{fileId:'mapping',revision:version}]]);
|
|
assert.deepEqual(calls.find(([name])=>name==='download')[1].args,{fileId:'original',revision:version});
|
|
assert.equal(calls.some(([,args])=>args.fileId?.startsWith('ekb:')),false);
|
|
});
|
|
|
|
test('preparing a pinned component retries a transient read and respects permission denial',async t=>{
|
|
let state='select', transient=0, denied=0;
|
|
const {calls,request}=await fixture(t,{call(name){
|
|
if(name!=='list_libraries')return;
|
|
if(state==='retry'&&transient++===0)throw Object.assign(Error('企业知识库网络不可达'),{network:true});
|
|
if(state==='denied'){
|
|
denied++;
|
|
throw Object.assign(Error('模板访问已拒绝'),{status:403});
|
|
}
|
|
}});
|
|
const {items:[{pack}]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default'});
|
|
const input={action:'prepare',...pack.enterprise,pinnedPack:pack};
|
|
state='retry';
|
|
const prepared=await request(input);
|
|
assert.deepEqual(prepared.pack,pack);
|
|
assert.equal(transient,2);
|
|
assert.equal(calls.filter(([method])=>method==='download').length,1);
|
|
state='denied';
|
|
await assert.rejects(request(input),/模板访问已拒绝/u);
|
|
assert.equal(denied,1);
|
|
assert.equal(calls.filter(([method])=>method==='download').length,1);
|
|
});
|
|
|
|
test('detail fields pin the exact references outside the resource set screen previews',async t=>{
|
|
const adapter='knowledge/workflows/template-adapter';
|
|
const dir=adapter+'/assets/chair/detail/extraction/reference';
|
|
const part=sku('detail','available');
|
|
part.assets.find(asset=>asset.role==='mapping').file.path=adapter+'/assets/chair/detail/字段映射.json';
|
|
part.assets.find(asset=>asset.role==='preview').file.path=adapter+'/assets/chair/detail/S04.jpg';
|
|
const fields=['S04-I01','S04-I02'].map(id=>({field_id:id,screen_id:'S04',name:id,type:'图片',
|
|
ps_location:{name:id,path:id},ps_style:{coverage_rect:[0,0,600,500]},
|
|
source_policy:'generate',
|
|
reference:{image_path:'assets/chair/detail/extraction/reference/arm.png'}}));
|
|
const raw={template_id:resourceSet.key,component:'detail',mapping_version:'1',canvas:[750,1000],source:{sha256:sha},
|
|
screens:[{screen_id:'S04',title:'落座',bounds:[0,0,750,500]}],fields,
|
|
production_profile:{schemaVersion:1,imageRules:{'S04-I01':{source:'generate',focus:'参考图位的实际使用动作'}}}};
|
|
const {calls,request}=await fixture(t,{parts:[part],
|
|
readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(raw)}}),
|
|
call(name,args){
|
|
if(name==='list_directory'){
|
|
assert.equal(args.path,dir);
|
|
return {result:{page:{hasMore:false,entries:[
|
|
{id:'another-file',revision:version,kind:'file',path:dir+'/other.png'},
|
|
{id:'arm-layout',revision:version,kind:'file',path:dir+'/arm.png'}
|
|
]}}};
|
|
}
|
|
}});
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'detail'});
|
|
assert.deepEqual(result.issues,[]);
|
|
assert.equal(result.pack.outputs[0].slots[0].sourcePolicy,'generate');
|
|
assert.deepEqual(result.pack.productionProfiles.detail,raw.production_profile);
|
|
assert.deepEqual(result.pack.outputs[0].slots.map(slot=>slot.previewReference),[
|
|
{fileId:'arm-layout',revision:version},{fileId:'arm-layout',revision:version}
|
|
]);
|
|
assert.equal(calls.filter(([name])=>name==='list_directory').length,1);
|
|
assert.equal(calls.some(([name])=>name==='read_image'),false);
|
|
});
|
|
|
|
test('a map-only role update creates a new selection while saved projects keep their pins',async t=>{
|
|
let role='attachment';
|
|
let manifestRevision='1'.repeat(32);
|
|
const {request}=await fixture(t,{call(name){
|
|
if(name==='get_resource_set'){
|
|
const part=sku('default','available');
|
|
part.assets.push(attachment('family',role,'.ttf'));
|
|
return {result:{resourceSet:{...resourceSet,manifestRevision},components:[part]}};
|
|
}
|
|
}});
|
|
const select=async ()=>(await request({action:'resource-component',resourceSetId:setId,componentId:'default'})).items[0].pack;
|
|
const first=await select();
|
|
role='font';
|
|
manifestRevision='2'.repeat(32);
|
|
const current=await select();
|
|
assert.notEqual(current.version,first.version);
|
|
assert.equal(current.enterprise.adapterVersion,4);
|
|
assert.equal(current.resourceFiles.find(f=>f.fileId==='family').role,'font');
|
|
const saved=await request({action:'prepare',...first.enterprise,pinnedPack:first});
|
|
assert.deepEqual(saved.pack,first);
|
|
assert.equal(saved.pack.resourceFiles.find(f=>f.fileId==='family').role,'attachment');
|
|
});
|
|
|
|
const groupedMapping={schema_version:1,template:mapping.template,smart_objects:{
|
|
main:{layer:'产品图片',target:'canvas'},
|
|
details:{layers:['卖点图1','卖点图2'],targets:['卖点底纹1','卖点底纹2']}
|
|
},text_layers:{
|
|
product_name:{layer:'产品名称'},
|
|
selling_copy:{layers:['卖点文案1','卖点文案2'],fallback_layers:{卖点文案2:['买点文案2']}},
|
|
hidden:{rendered:false}
|
|
}};
|
|
|
|
test('grouped image and text declarations use the same layer rules for any template',async t=>{
|
|
const {request}=await fixture(t,{readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(groupedMapping)}})});
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'});
|
|
assert.deepEqual(result.issues,[]);
|
|
const slots=result.pack.outputs[0].slots;
|
|
assert.deepEqual(slots.map(f=>f.psLayer.path),['产品图片','卖点图1','卖点图2','产品名称','卖点文案1','卖点文案2']);
|
|
assert.deepEqual(slots[0].nativeBounds,{kind:'canvas'});
|
|
assert.deepEqual(slots[2].nativeBounds,{kind:'layer',layer:{path:'卖点底纹2',name:'卖点底纹2',byName:true}});
|
|
assert.deepEqual(slots[5].psLayer.alternatives,['买点文案2']);
|
|
assert.equal(slots[3].nativeTextBounds,true);
|
|
});
|
|
|
|
test('unpaired image groups explain the mapping issue and keep the preview',async t=>{
|
|
const unpaired=structuredClone(groupedMapping);
|
|
unpaired.smart_objects.details.targets.pop();
|
|
const {request}=await fixture(t,{readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(unpaired)}})});
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'});
|
|
assert.deepEqual(result.issues,['卖点图层和目标图层须按相同顺序一一对应']);
|
|
assert.ok(result.imagePath);
|
|
assert.equal(result.pack,undefined);
|
|
});
|
|
|
|
test('named image slots and standalone main image packages share the same importer',async t=>{
|
|
const {request}=await fixture(t,{
|
|
call(name){if(name==='get_resource_set')return {result:{resourceSet:{...resourceSet,category:'主图'},components:[sku('800','available')]}};},
|
|
readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify({
|
|
schema_version:3,template:mapping.template,
|
|
smart_objects:{main:{layer:'产品图',target:'original-layer-bounds'},detail1:{layer:'细节图',target:'装饰/底图'}},
|
|
text_layers:{产品名:{safe_area:bounds}}
|
|
})}})
|
|
});
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'800',categoryName:'主图'});
|
|
assert.deepEqual(result.issues,[]);
|
|
assert.equal(result.pack.enterprise.component,'main_images');
|
|
assert.deepEqual(result.pack.outputs[0].slots.map(f=>f.psLayer.path),['产品图','细节图','产品名']);
|
|
assert.equal(result.pack.outputs[0].slots[1].nativeBounds.layer.byName,undefined);
|
|
});
|
|
|
|
test('a mismatched 750 mapping can display its preview without blocking the available 800 component',async t=>{
|
|
const {calls,request}=await fixture(t,{parts:[sku('750','needs_review','needs_review'),sku('800','available')]});
|
|
const choose=componentId=>request({action:'resource-component',resourceSetId:setId,componentId,previewId:'preview'});
|
|
const {items:[bad]}=await choose('750');
|
|
assert.ok(bad.imagePath);
|
|
assert.deepEqual(bad.issues,['字段映射与当前原稿版本不符']);
|
|
assert.equal(bad.pack,undefined);
|
|
assert.equal(calls.some(([name])=>name==='read_text'||name==='download'),false);
|
|
assert.ok((await choose('800')).items[0].pack);
|
|
});
|
|
|
|
test('re-reads the selected resource group after a version conflict and allows cancellation during rate limit',async t=>{
|
|
let lookups=0;
|
|
const {calls,request}=await fixture(t,{call(name){
|
|
if(name==='get_resource_set')return {result:{resourceSet,components:[++lookups===1?sku('default','available'):sku('default','needs_review','needs_review')]}};
|
|
},readDocument(){throw Object.assign(Error('conflict'),{status:409});}});
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default'});
|
|
assert.deepEqual(result.issues,['字段映射与当前原稿版本不符']);
|
|
assert.equal(calls.filter(([name])=>name==='get_resource_set').length,2);
|
|
const rate=await fixture(t,{call(name){if(name==='list_resource_sets')throw Object.assign(Error('quota'),{status:429,retryAfterSeconds:60});}});
|
|
const stop=new AbortController();
|
|
await assert.rejects(rate.request({action:'catalog'},{signal:stop.signal,onProgress(progress){
|
|
assert.equal(progress.retryAfterSeconds,60);
|
|
stop.abort();
|
|
}}),{name:'AbortError'});
|
|
});
|
|
|
|
test('template preparation requires the resource map contract',async t=>{
|
|
const {calls,request}=await fixture(t);
|
|
for(const sourceKind of [undefined,'files']){
|
|
await assert.rejects(request({action:'prepare',sourceKind}),/从企业知识库资源地图重新选择/);
|
|
}
|
|
assert.deepEqual(calls,[]);
|
|
});
|
|
|
|
test('SKU smart-object mappings preserve the declared layer paths and use native text bounds',async t=>{
|
|
const smart={schema_version:1,template:mapping.template,
|
|
smart_objects:{main:{path:'产品/图片',target_bounds:[10,20,110,220]}},
|
|
text_layers:{product:[{path:'标题/产品名称'}]}};
|
|
const {request}=await fixture(t,{readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(smart)}})});
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default'});
|
|
const [image,text]=result.pack.outputs[0].slots;
|
|
assert.deepEqual(image.frame,{x:10,y:20,width:100,height:200});
|
|
assert.equal(image.psLayer.path,'产品/图片');
|
|
assert.equal(text.psLayer.path,'标题/产品名称');
|
|
assert.equal(text.nativeTextBounds,true);
|
|
});
|
|
|
|
test('a quota wait resumes the unfinished read without reloading the chosen resource set',async t=>{
|
|
let previews=0;
|
|
const {calls,request}=await fixture(t,{call(name){
|
|
if(name==='read_image'&&++previews===1)throw Object.assign(Error('quota'),{status:429,retryAfterSeconds:0.01});
|
|
}});
|
|
const progress=[];
|
|
const {items:[result]}=await request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'},
|
|
{onProgress:event=>progress.push(event.phase)});
|
|
assert.ok(result.imagePath&&result.pack);
|
|
assert.deepEqual(progress,['waiting','metadata']);
|
|
assert.equal(calls.filter(([name])=>name==='get_resource_set').length,1);
|
|
assert.equal(calls.filter(([name])=>name==='read_image').length,2);
|
|
assert.equal(calls.filter(([name])=>name==='read_text').length,1);
|
|
});
|
|
|
|
test('a brief network interruption retries only the same pinned field preview',async t=>{
|
|
let reads=0;
|
|
const {calls,request}=await fixture(t,{call(name){
|
|
if(name==='read_image'&&++reads===1)throw Object.assign(Error('preview temporarily unreachable'),{network:true});
|
|
}});
|
|
const args={fileId:'preview',revision:version};
|
|
const {imagePath}=await request({action:'field-preview',...args});
|
|
assert.deepEqual(calls,[['read_image',args],['read_image',args]]);
|
|
assert.deepEqual(await fs.readFile(imagePath),Buffer.from([1,2,3]));
|
|
});
|
|
|
|
test('SKU maps product and selling points by exact nested PSD layer paths', async t => {
|
|
const layered = {
|
|
schema_version: 1,
|
|
template: mapping.template,
|
|
product: {
|
|
layer_path: '4/组 7/产品图片', original_bounds: [351, 289, 1112, 1241],
|
|
target_width: 981, target_center: [731.5, 719], fit: 'fit-width-center',
|
|
},
|
|
details: [{layer_path: '4/组 10/卖点图1', bounds: [95, 187, 496, 432], fit: 'cover'}],
|
|
text_layers: {product_combo: '4/产品组合名', selling_points: ['4/卖点文案1']},
|
|
};
|
|
const {request} = await fixture(t,{readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(layered)}})});
|
|
const {items:[result]} = await request({action:'resource-component',resourceSetId:setId,componentId:'default'});
|
|
assert.deepEqual(result.issues, []);
|
|
const fields = result.pack.outputs[0].slots;
|
|
assert.deepEqual(fields.map(field=>field.psLayer.path), [
|
|
'4/组 7/产品图片','4/组 10/卖点图1','4/产品组合名','4/卖点文案1',
|
|
]);
|
|
assert.deepEqual(fields[1].nativeFrame,[95,187,496,432]);
|
|
assert.equal(fields[2].nativeTextBounds,true);
|
|
});
|
|
|
|
test('SKU maps main and detail target bounds and keeps explicit text safe bounds', async t => {
|
|
const layered = {
|
|
schema_version: 1,
|
|
template: mapping.template,
|
|
main: {layer_path:'组 1/产品图片',target_bounds:[16,278,1114,1308],fit:'cover'},
|
|
details: [{layer_path:'组 1/卖点图1',target_bounds:[1131,41,1426,345],fit:'cover'}],
|
|
text_layers: {product_combo:{path:'组 1/产品组合名',safe_bounds:[700,30,1110,180]}},
|
|
};
|
|
const {request} = await fixture(t,{readDocument:()=>({result:{sourceId:'mapping',text:JSON.stringify(layered)}})});
|
|
const {items:[result]} = await request({action:'resource-component',resourceSetId:setId,componentId:'default'});
|
|
assert.deepEqual(result.issues, []);
|
|
const fields = result.pack.outputs[0].slots;
|
|
assert.deepEqual(fields.map(field=>field.nativeFrame), [[16,278,1114,1308],[1131,41,1426,345],[700,30,1110,180]]);
|
|
assert.equal(fields[2].psLayer.path,'组 1/产品组合名');
|
|
assert.equal(fields[2].nativeTextBounds,undefined);
|
|
});
|
|
|
|
test('resource map reuses complete mappings by file identity and revision after live revalidation', async t => {
|
|
let revision=version;
|
|
const {request,calls}=await fixture(t,{call(name) {
|
|
if(name!=='get_resource_set')return;
|
|
const part=sku('default','available');
|
|
part.assets.find(a=>a.role==='mapping').file.revision=revision;
|
|
return {result:{resourceSet,components:[part]}};
|
|
}});
|
|
const choose=()=>request({action:'resource-component',resourceSetId:setId,componentId:'default',previewId:'preview'});
|
|
assert.ok((await choose()).items[0].pack);
|
|
assert.ok((await choose()).items[0].pack);
|
|
assert.equal(calls.filter(([name])=>name==='get_resource_set').length,2);
|
|
assert.equal(calls.filter(([name])=>name==='read_text').length,1);
|
|
revision='c'.repeat(32);
|
|
assert.ok((await choose()).items[0].pack);
|
|
assert.deepEqual(calls.filter(([name])=>name==='read_text').map(([,args])=>args.revision),[version,revision]);
|
|
});
|
|
|
|
test('component-scoped original IDs bind by the published path and digest', () => {
|
|
const relative = 'assets/fixtures/desk/main/plate.psd';
|
|
const original = {id:'publication-plate',file:{path:'library/template-adapter/'+relative,sha256:sha}};
|
|
const mapping = {
|
|
template_id:'test-desk',component:'main_images',
|
|
source:{assets:[{asset_id:'plate',ps_asset_path:relative,ps_sha256:sha}]},
|
|
screens:[{asset_id:'plate',screen_id:'main',bounds:[0,0,100,100]}],
|
|
fields:[{field_id:'hero',asset_id:'plate',screen_id:'main',type:'图片',
|
|
ps_location:{asset_id:'plate',path:'Hero',name:'Hero'},ps_style:{coverage_rect:[0,0,100,100]}}],
|
|
};
|
|
const bind = a => normalizeTemplateMapping(mapping,[a],'test-desk','main_images');
|
|
const normalized = bind(original);
|
|
assert.equal(normalized.source.assets[0].asset_id,original.id);
|
|
assert.equal(normalized.screens[0].asset_id,original.id);
|
|
assert.equal(normalized.fields[0].asset_id,original.id);
|
|
assert.equal(normalized.fields[0].ps_location.asset_id,original.id);
|
|
assert.equal(mapping.fields[0].asset_id,'plate');
|
|
assert.throws(() => bind({...original,file:{...original.file,sha256:'c'.repeat(64)}}),/路径或版本/);
|
|
assert.throws(() => bind({...original,file:{...original.file,path:'elsewhere/plate.psd'}}),/路径或版本/);
|
|
});
|