gongxiangp2/apps/detail-agent-pi/src/enterprise-templates.mjs

535 lines
31 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'node:fs/promises';
import path from 'node:path';
import {setTimeout as delay} from 'node:timers/promises';
import { EnterpriseKnowledge } from './enterprise-knowledge.mjs';
import { openXiaoyiSkills } from './xiaoyi-release.mjs';
import { normalizeTemplateMapping } from './template-mapping.mjs';
import { atomic, digest } from './store.mjs';
import { EnterpriseContext } from './enterprise-context.mjs';
import {resourceRequest,resourceSnapshot} from './enterprise-resource-map.mjs';
import {nativeKnowledgeFetch} from './native-knowledge-http.mjs';
import {knowledgeTiming, retryKnowledgeRead, transientStatus} from './knowledge-network.mjs';
import origins from './enterprise-knowledge-origins.json' with {type:'json'};
async function waitForQuota(read, task) {
const networkRetryMs=task.retryPinnedRead?[2000,5000,12000]:[];
let transientFailures=0;
for (;;) {
task.signal?.throwIfAborted();
try { return await read(); }
catch(error) {
if(error.network===true&&!error.retryExhausted&&transientFailures<networkRetryMs.length){
await delay(networkRetryMs[transientFailures++],undefined,{signal:task.signal});
continue;
}
if(error.status!==429 || !(error.retryAfterSeconds>0&&Number.isFinite(error.retryAfterSeconds)))throw error;
task.onProgress?.({...task.progress,phase:'waiting',retryAfterSeconds:Math.ceil(error.retryAfterSeconds)});
await delay(Math.ceil(error.retryAfterSeconds*1000),undefined,{signal:task.signal});
task.onProgress?.(task.progress);
}
}
}
const operation = options => ({...options,metadata:new Map(),resolving:new Map(),downloads:new Map(),
cachedConflicts:new Map(),progress:{phase:'metadata'}});
const fileKey = file => JSON.stringify([file.fileId,file.revision||null]);
const versionConflict = status => [409,412].includes(status);
const assetFailure = (file, message, status, cause) => Object.assign(
Error(`模板资料「${file.name??file.path??file.fileId}」${file.revision?`(版本 ${file.revision})`:''}${message}`,{cause}),{status});
export function brandProfiles(text) {
const section=text.split(/^##\s+可用品牌\s*$/m)[1]?.split(/^##\s+/m)[0]||'';
const headings=[...section.matchAll(/^###\s+(.+)$/gm)];
return {schema_version:1,brands:headings.map((heading,index)=>{
const content=section.slice(heading.index+heading[0].length,headings[index+1]?.index).trim();
const tone=content.match(/^####\s+品牌风格[::]\s*(.+)$/m)?.[1]?.trim()||'';
return {name:heading[1].trim(),profile:{tone,visualRules:{knowledge:content}}};
})};
}
const asset = (manifest, id) => {
const item = manifest.template.assets.find(item => item.assetId === id);
if (!item) throw Error('资源地图缺少模板附件');
return item;
};
function componentPack(manifest, revision, mappings, binding) {
const template=manifest.template;
const pack={schemaVersion:1,id:template.templateId,name:template.name,version:manifest.version,
brandId:binding.brandId,categoryId:binding.categoryId,brandName:template.brand,categoryName:template.category,
enterprise:{manifestRevision:revision},outputs:[]};
pack.enterprise.components = {};
for (const component of manifest.template.components) {
if (!['detail', 'main_images', 'sku_images'].includes(component.component)) continue;
const mapping = mappings[component.component];
if (!mapping || mapping.template_id !== manifest.template.templateId || mapping.mapping_version !== component.mappingVersion) throw Error('模板组件或映射版本不一致');
if (mapping.skill_sources !== undefined) pack.skillSources = mapping.skill_sources;
if(component.component==='detail'){
const original=asset(manifest,component.originalAssetIds[0]);
Object.assign(pack.enterprise,{mappingAssetId:component.mappingAssetId,inventoryAssetId:component.sourceInventoryAssetId,
originalAssetId:original.assetId,originalRevision:original.revision,originalSha256:original.sha256,canvas:mapping.canvas});
}
const sources = component.component === 'detail'
? [{assetId:component.originalAssetIds[0],canvas:mapping.canvas,sha256:mapping.source.sha256}]
: mapping.source.assets.map(source => {
const original = component.originalAssetIds.map(id=>asset(manifest,id)).find(item=>item.declaredId===source.asset_id);
if (!original || original.sha256.toLowerCase() !== source.ps_sha256?.toLowerCase()) throw Error('组件字段映射不属于所选原稿');
return {assetId:original.assetId,sourceId:source.asset_id,canvas:source.canvas_px,sha256:source.ps_sha256};
});
if (sources.length !== component.originalAssetIds.length) throw Error('模板组件原稿清单不完整');
pack.enterprise.components[component.component] = {
mappingAssetId:component.mappingAssetId,inventoryAssetId:component.sourceInventoryAssetId,
originals:sources.map(source=>({...source,revision:asset(manifest,source.assetId).revision}))
};
let top = 0;
const outputs = mapping.screens.map(screen => {
const source = sources.find(item=>component.component==='detail' || item.sourceId===screen.asset_id);
if (!source) throw Error('模板页面缺少对应原稿');
const [left,nativeTop,right,bottom] = screen.bounds;
const slots = mapping.fields.filter(field=>field.screen_id===screen.screen_id).map(field=>{
if (component.component!=='detail' && field.asset_id!==source.sourceId) throw Error('字段不属于当前页面原稿');
const [l,t,r,b]=field.ps_style.coverage_rect;
const x=Math.max(left,l),y=Math.max(nativeTop,t),x2=Math.min(right,r),y2=Math.min(bottom,b);
if(x2<=x||y2<=y)throw Error(`字段 ${field.field_id} 不在所属页面`);
const kind=field.type==='图片'?'image':['文案','参数'].includes(field.type)?'text':null;
if(!kind)throw Error('未知模板字段类型');
const sourcePolicy=field.source_policy;
const productionRule=field.production_rule;
if(kind==='image'&&sourcePolicy!==undefined&&!['product','generate'].includes(sourcePolicy)) {
throw Error(`字段 ${field.field_id} 的图源要求无效`);
}
if(kind==='image'&&productionRule!==undefined&&(!['product','generate'].includes(productionRule?.source)||
typeof productionRule.focus!=='string'||!productionRule.focus.trim())){
throw Error(`字段 ${field.field_id} 的制作要求无效`);
}
const run=field.ps_style.style_runs?.[0],text=field.raw_text||field.reference||'';
if(kind==='text'&&field.style_roles!==undefined&&
(!Array.isArray(field.style_roles)||field.style_roles.some(role=>typeof role!=='string'||!role.trim()))){
throw Error(`字段 ${field.field_id} 的样式角色无效`);
}
return {fieldId:field.field_id,name:field.name,role:field.role,kind,
...(kind==='text'&&field.style_roles?.length?{styleRoles:field.style_roles}:{}),
...(kind==='text'&&field.textSafeFrame===true?{textSafeFrame:true}:{}),
frame:{x:x-left,y:y-nativeTop,width:x2-x,height:y2-y},nativeFrame:[l,t,r,b],
psLayer:field.ps_location,crop:'cover',...(field.nativeTextBounds?{nativeTextBounds:true}:{}),...(field.nativeBounds?{nativeBounds:field.nativeBounds}:{}),
requirements:[field.purpose,field.fill_requirements,field.adaptation_requirements,field.output_spec,field.rules].filter(Boolean).join('\n'),
...(kind==='image'?{imagePrompt:typeof field.fill_requirements==='string'?field.fill_requirements:null,outputSpec:field.output_spec,
...(sourcePolicy===undefined?{}:{sourcePolicy}),...(productionRule===undefined?{}:{productionRule})}:{}),
relatedFields:field.related_fields,example:field.reference,
...(kind==='text'?{font:{family:run?.font_name||'',size:run?.font_size||24,weight:400,color:'#000000'},
maxChars:field.maxChars??Math.max(1,Array.from(text).length),maxLines:field.maxLines??Math.max(1,text.split(/\r\n|\r|\n/).length)}:{})};
});
const output={id:screen.screen_id,name:screen.title,component:component.component,width:right-left,height:bottom-nativeTop,
top:component.component==='detail'?nativeTop:top,originalAssetId:source.assetId,slots};
top+=source.canvas[1];
return output;
});
if(component.component==='detail')pack.outputs=outputs;else pack.outputs.push(...outputs);
}
return pack;
}
export class EnterpriseTemplates {
constructor(root, client) {
this.root = root;
this.client = client || new EnterpriseKnowledge({store:{root,appendEvent:async event=>{
await fs.mkdir(root,{recursive:true});
await fs.appendFile(path.join(root,'sources.jsonl'),JSON.stringify(event)+'\n');
}}});
}
async cachedPinnedAsset(file, status, task) {
const key=fileKey(file), pinned=task.pinnedAssets.get(key);
if(!pinned)throw assetFailure(file,'缺少已校验的固定版本副本',status);
if(!task.cachedConflicts.size&&!task.verifyPinnedMapping()) {
const mapping=task.pinnedAssets.get(fileKey(task.mapping))??task.mapping;
throw assetFailure(mapping,'缺少已校验的字段映射副本',status);
}
if(pinned.roles.some(role=>role.startsWith('mapping:'))) {
task.cachedConflicts.set(key,null);
return;
}
const localPath=await this.client.cachedDownload(pinned,task.signal);
if(!localPath)throw assetFailure(pinned,'缺少已校验的固定版本副本',status);
task.cachedConflicts.set(key,localPath);
return localPath;
}
async resolve(files, task) {
task.signal?.throwIfAborted();
const unique=[...new Map(files.map(file=>[fileKey(file),file])).values()];
const fresh=unique.filter(file=>!task.metadata.has(fileKey(file))&&!task.resolving.has(fileKey(file)));
for(let start=0;start<fresh.length;start+=100) {
const batch=fresh.slice(start,start+100);
const pending=(async()=>{
let rows;
if(this.client.connection?.tools.has('get_files')) {
const reply=await waitForQuota(()=>this.client.call('get_files',{files:batch},{signal:task.signal}),task);
rows=reply.result.results;
} else {
rows=[];
for(const file of batch) {
try {
rows.push({fileId:file.fileId,status:200,file:(await waitForQuota(()=>this.client.call('get_file',file,{signal:task.signal}),task)).result});
} catch(error) {
if(!versionConflict(error.status)&&![403,404].includes(error.status))throw error;
rows.push({fileId:file.fileId,status:error.status,error:error.message});
}
}
}
if(rows.length!==batch.length)throw Error('企业知识库批量核验结果不完整');
for(let index=0;index<batch.length;index++) {
const row=rows[index],file=batch[index];
if(row.fileId!==file.fileId)throw Error('企业知识库批量核验文件身份不一致');
const pinned=task.pinnedAssets?.get(fileKey(file));
if(row.status!==200&&(!versionConflict(row.status)||!pinned)) {
const reason=row.error||([403,404].includes(row.status)?'资料不存在或无权访问':'知识库状态 '+row.status);
const message=versionConflict(row.status)?'缺少已校验的固定版本副本':`无法读取:${reason}`;
throw assetFailure(pinned??file,message,row.status);
}
if(row.status===200&&file.revision&&row.file?.revision!==file.revision)
throw assetFailure(pinned??file,'与知识库返回的版本不一致',409);
}
for(let index=0;index<batch.length;index++) {
const row=rows[index],key=fileKey(batch[index]);
if(row.status===200){
task.metadata.set(key,row.file);
continue;
}
const pinned=task.pinnedAssets.get(key);
await this.cachedPinnedAsset(pinned,row.status,task);
task.metadata.set(key,pinned);
}
})();
for(const file of batch)task.resolving.set(fileKey(file),pending);
}
await Promise.all(unique.map(file=>task.resolving.get(fileKey(file))));
task.signal?.throwIfAborted();
}
async json(fileId, revision, task=operation({}), parse=JSON.parse) {
// Permissions are checked even when the immutable body is already cached.
const ref={fileId,...(revision?{revision}:{})};
await this.resolve([ref],task);
const meta=task.metadata.get(fileKey(ref));
const file = path.join(this.root,'documents',encodeURIComponent(fileId)+'-'+meta.revision+'.json');
let value;
try { value = JSON.parse(await fs.readFile(file,'utf8')); }
catch(error) { if (error.code !== 'ENOENT') throw error; }
if (!value) {
const response = await waitForQuota(()=>this.client.readComplete(fileId,meta.revision,{signal:task.signal}),task);
value = parse(response.result.text);
await fs.mkdir(path.dirname(file),{recursive:true});
await fs.writeFile(file,JSON.stringify(value));
}
return {value,revision:meta.revision};
}
async brandSources(task) {
const entries=[];
let offset=0,more=true;
while(more) {
const {result}=await waitForQuota(()=>this.client.page('search_files',{query:'品牌风格索引',limit:100,offset},{signal:task.signal}),task);
if(result.pageRestarted)entries.length=0;
const page=result.page;
entries.push(...page.entries.filter(entry=>entry.kind==='file'&&
!path.posix.basename(entry.path).startsWith('._')&&entry.path.endsWith('品牌风格索引.md')));
offset=page.offset+page.entries.length;
more=page.hasMore;
}
await this.resolve(entries.map(entry=>({fileId:entry.id})),task);
const sources=[];
for (const entry of entries) {
const {value,revision}=await this.json(entry.id,undefined,task,brandProfiles);
if (value.schema_version===1 && Array.isArray(value.brands)) {
sources.push({value,provenance:{reference:entry.id,revision,path:entry.path}});
}
}
return sources;
}
async request(input, options={}) {
const task=operation({...options,retryPinnedRead:input.action==='field-preview'||
input.action==='prepare'&&Boolean(input.pinnedPack)});
if(input.action==='field-preview'){
const reply=await waitForQuota(()=>this.client.call('read_image',{fileId:input.fileId,revision:input.revision},{signal:task.signal}),task);
if((reply.result.sourceId||reply.result.fileId||reply.result.id)!==input.fileId || reply.result.revision!==input.revision) throw Error('图位原参考版本已变化');
const folder=path.join(this.root,'resource-previews');
await fs.mkdir(folder,{recursive:true});
const imagePath=path.join(folder,digest([input.fileId,input.revision])+'.image');
await fs.writeFile(imagePath,Buffer.from(reply.images[0].data,'base64'));
return {imagePath};
}
if (input.action === 'context') {
if (typeof input.projectRoot!=='string' || !path.isAbsolute(input.projectRoot)) throw Error('项目知识快照位置无效');
const store={root:input.projectRoot,appendEvent:async event=>{
await fs.appendFile(path.join(input.projectRoot,'knowledge-events.jsonl'),JSON.stringify(event)+'\n');
}};
const value=await new EnterpriseContext(store,this.client).load(input,{signal:task.signal,read:fn=>waitForQuota(fn,task)});
if (input.task==='image') {
return {context:{...value,skills:value.skills.map(({fileId,revision,path})=>({fileId,revision,path})),
rules:value.rules.filter(rule=>['brand','product-visual'].includes(rule.kind)||rule.kind.endsWith('-visual-rules'))}};
}
return {context:{task:value.task,brandName:value.brandName,categoryName:value.categoryName,templateId:value.templateId,releaseId:value.releaseId,
skills:value.skills.map(({fileId,revision,path})=>({fileId,revision,path})),rules:value.rules,execution:value.execution}};
}
if (['choices','brand','catalog','resource-set','resource-component'].includes(input.action)) {
const library=(await waitForQuota(()=>this.client.call('list_libraries',{}, {signal:task.signal}),task)).result;
const result=await resourceRequest(this,input,library,task,waitForQuota,componentPack);
if(input.action==='brand'&&result.brand){
const sources=await this.brandSources(task);
for(const {value,provenance} of sources){
const profile=value.brands.find(item=>item.name===result.brand.name)?.profile;
if(profile)Object.assign(result.brand.profile,profile,{source:provenance});
}
}
return result;
}
if (!['pack','prepare'].includes(input.action)) throw Error('模板操作无效');
if (input.sourceKind!=='resource-map') throw Error('请从企业知识库资源地图重新选择模板');
await waitForQuota(()=>this.client.call('list_libraries',{}, {signal:task.signal}),task);
return this.prepare(input,task,await resourceSnapshot(this,input,task));
}
async prepare(input,task,{pack,manifest}) {
if (input.action === 'pack') return {pack};
const component=input.component||'detail';
const outputs=pack.outputs.filter(output=>output.component===component&&(!input.documentId||output.id===input.documentId));
if(!outputs.length)throw Error('当前固定模板没有所选组件,请检查模板更新');
const ids=[...new Set(outputs.map(output=>output.originalAssetId||pack.enterprise.originalAssetId))];
const fontAssets=manifest.template.assets.filter(item=>item.roles.includes('font:'+component)&&/\.(ttf|otf)$/i.test(item.path));
const attachments=manifest.template.assets.filter(item=>item.roles.includes('attachment:'+component));
const needed=[...ids.map(id=>asset(manifest,id)),...fontAssets,...attachments];
await this.resolve(needed.map(item=>({fileId:item.fileId,revision:item.revision})),task);
task.progress={phase:'download',completed:0,fileCount:new Set(needed.map(item=>item.assetId)).size};
const download=async item=>{
task.signal?.throwIfAborted();
const ref={fileId:item.fileId,revision:item.revision},key=fileKey(ref);
if(!task.downloads.has(key))task.downloads.set(key,(async()=>{
let cached=task.cachedConflicts.get(key),result;
if(!cached) {
try {
result=await waitForQuota(()=>this.client.download(ref,{metadata:task.metadata.get(key),signal:task.signal,
onProgress:value=>task.onProgress?.({...task.progress,...value})}),task);
} catch(error) {
if(versionConflict(error.status))cached=await this.cachedPinnedAsset(item,error.status,task);
else if([403,404].includes(error.status))throw assetFailure(item,`无法读取:${error.message}`,error.status,error);
else throw error;
}
}
if(cached)result={result:{localPath:cached,cached:true}};
task.progress.completed++;task.onProgress?.({...task.progress,cached:result.result.cached});
return result;
})());
return task.downloads.get(key);
};
const originals=[];
for(const id of ids){
const original=asset(manifest,id);
const downloaded=await download(original);
const source=pack.enterprise.components?.[component]?.originals.find(item=>item.assetId===id);
originals.push({assetId:id,originalPath:downloaded.result.localPath,canvas:source?.canvas||pack.enterprise.canvas});
}
const fonts=[];
for (const font of fontAssets) {
const local=(await download(font)).result.localPath;
if(!fonts.includes(local))fonts.push(local);
}
for(const attachment of attachments)await download(attachment);
const versionNotice=task.cachedConflicts.size?'有新版模板资料,当前项目继续使用已锁定的版本。':undefined;
if(versionNotice)await this.client.store?.appendEvent({type:'enterprise_template_version_conflict',
resourceSetId:pack.enterprise.resourceSetId,componentId:pack.enterprise.componentId,versionNotice});
return {pack,originals,originalPath:originals[0].originalPath,fonts,...(versionNotice?{versionNotice}:null)};
}
}
function intakeMetadata(value) {
if (value === undefined || value === null) return undefined;
if (value.version !== 1 || !Array.isArray(value.productFields) || !Array.isArray(value.barcodeFields)) {
throw Error('小壹模板产品资料字段格式无效');
}
const readFields = fields => {
const ids = new Set();
return fields.map(field => {
if (!field || typeof field.id !== 'string' || !field.id.trim() || typeof field.label !== 'string' || !field.label.trim() ||
!['text','number','select','boolean'].includes(field.type) ||
(field.required !== undefined && typeof field.required !== 'boolean') ||
(field.multiline !== undefined && typeof field.multiline !== 'boolean') ||
(field.placeholder !== undefined && typeof field.placeholder !== 'string') ||
(field.help !== undefined && typeof field.help !== 'string') ||
(field.unit !== undefined && typeof field.unit !== 'string') ||
(field.options !== undefined && (!Array.isArray(field.options) || field.options.some(option => typeof option !== 'string'))) ||
(field.type === 'select' && (!field.options || !field.options.length))) {
throw Error('小壹模板产品资料字段格式无效');
}
if (ids.has(field.id)) throw Error('小壹模板产品资料字段编号重复');
ids.add(field.id);
return {
id:field.id, label:field.label, type:field.type,
...(field.required !== undefined && {required:field.required}),
...(field.multiline !== undefined && {multiline:field.multiline}),
...(field.placeholder !== undefined && {placeholder:field.placeholder}),
...(field.help !== undefined && {help:field.help}),
...(field.unit !== undefined && {unit:field.unit}),
...(field.options !== undefined && {options:field.options}),
};
});
};
return {version:1,productFields:readFields(value.productFields),barcodeFields:readFields(value.barcodeFields)};
}
export async function xiaoyiPacks(input, {signal,fetch,onProgress} = {}) {
const {templateId,projectDir,cache} = input;
const skills = await openXiaoyiSkills({dir:projectDir,xiaoyiCache:cache,xiaoyiProgress:onProgress},templateId,signal,undefined,fetch,input.knowledgeVersion,input.metadataOnly === true);
const {manifest,root} = skills.snapshot;
if (!manifest.bindings || !Object.keys(manifest.bindings).length) throw Error('小壹清单缺少组件绑定');
const files = new Map(manifest.files.map(file => [file.path,file]));
const assets = new Map(manifest.assets.map(asset => [asset.path,asset]));
const itemAt = (index, relative, type) => {
const item = index.get(relative);
if (item?.type !== type) throw Error('小壹组件绑定缺少' + type + ':' + relative);
return item;
};
const jsonAt = async item => JSON.parse(await fs.readFile(path.join(root,item.path),'utf8'));
const packs = {};
for (const [component,binding] of Object.entries(manifest.bindings)) {
const mappingFile = itemAt(files,binding.mapping,'mapping');
const inventoryFile = itemAt(files,binding.inventory,'inventory');
const raw = await jsonAt(mappingFile);
const inventory = await jsonAt(inventoryFile);
if (inventory.template_id !== templateId || (inventory.component ?? 'detail') !== component ||
inventory.mapping_version !== raw.mapping_version) throw Error('小壹图层清单与组件映射不一致');
const pages = Object.entries(binding.pages ?? {});
const references = binding.original ? [{original:binding.original,assetId:raw.source?.assets?.[0]?.asset_id ?? 'original'}]
: [...new Map(pages.map(([,page])=>[page.assetId,page])).values()];
const originals = references.map(ref => {
const file = itemAt(assets,ref.original,'original');
if (file.component !== component) throw Error('小壹原稿不属于当前组件');
return {id:ref.assetId,file};
});
const mapping = normalizeTemplateMapping(raw,originals,templateId,component);
for (const [page,ref] of pages) {
if (!mapping.screens.some(screen=>screen.screen_id===page && screen.asset_id===ref.assetId) ||
!inventory.source?.assets?.some(asset=>asset.asset_id===ref.assetId)) throw Error('小壹页面原稿绑定不一致:' + page);
}
if (!binding.original && pages.length !== mapping.screens.length) throw Error('小壹页面原稿绑定不完整');
const descriptor = {component,mappingVersion:mapping.mapping_version,mappingAssetId:binding.mapping,
sourceInventoryAssetId:binding.inventory,originalAssetIds:originals.map(({id})=>id)};
const pack = componentPack({version:manifest.version,template:{
templateId,name:input.name || raw.template_name || templateId,brand:raw.brand,category:raw.category,
components:[descriptor],assets:originals.map(({id,file})=>({...file,declaredId:id,assetId:id,revision:manifest.version})),
}},manifest.bundle.sha256,{[component]:mapping},input);
const original = pack.enterprise.components[component].originals[0];
Object.assign(pack.enterprise,{component,sourceKind:'xiaoyi-release',snapshotVersion:manifest.version,
originalSha256:original.sha256,canvas:original.canvas,
resourceSetId:templateId,componentId:component,
mappingPath:path.join(root,binding.mapping),inventoryPath:path.join(root,binding.inventory)});
const intake = intakeMetadata(manifest.intake ?? input.intake);
pack.xiaoyi = {...skills.productionBinding,...(intake && {intake})};
packs[component] = pack;
}
return {packs};
}
const clients = new Map();
export async function xiaoyiCatalog(input, {signal,fetch = nativeKnowledgeFetch,onProgress} = {}) {
let origin = origins[0];
if (process.env.PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE) {
origin = await fs.readFile(process.env.PHOTOCRAFT_KNOWLEDGE_ORIGIN_FILE, 'utf8')
.then(JSON.parse, error => {
if (error.code !== 'ENOENT') throw error;
return origins[0];
});
}
const cache = input.root && path.join(input.root, 'catalog', 'index-' + digest(origin) + '.json');
let rows, notice;
try {
rows = await retryKnowledgeRead(async () => {
const response = await fetch(new URL('/api/xiaoyi/v1/templates', origin), {
method:'GET', redirect:'manual', ...knowledgeTiming(fetch, signal, 45_000),
});
if (!response.ok) {
const messages = {401:'小壹知识库连接已失效,请重新登录素材库',403:'当前连接无权读取模板目录,请联系知识库管理员'};
if (messages[response.status]) {
await response.body?.cancel();
throw Object.assign(Error(messages[response.status]), {status:response.status});
}
const body = await response.json().catch(error => {
if (!(error instanceof SyntaxError)) throw error;
});
const message = body?.code === 'knowledge_session_misconfigured' ? '小壹知识库自动授权配置错误,请联系管理员'
: response.status >= 500 ? '模板目录服务端异常,请稍后重试' : '模板目录无法读取(HTTP ' + response.status + ')';
throw Object.assign(Error(message), {status:response.status, code:body?.code, network:false});
}
const data = await response.json();
if (!Array.isArray(data.items)) throw Error('小壹模板目录格式无效');
return data.items;
}, signal);
} catch (error) {
signal?.throwIfAborted();
if (error.category === 'credential') throw Error('小壹知识库未连接,请在小壹设置中检测连接', {cause:error});
if (!cache || !(error.network || error.retryable || transientStatus(error.status, error.code))) throw error;
rows = await fs.readFile(cache, 'utf8').then(JSON.parse, e => {
if (e.code !== 'ENOENT') throw e;
});
if (!Array.isArray(rows)) throw error;
notice = error.message + '。正在使用本机缓存模板,表单草稿已保留。';
}
signal?.throwIfAborted();
if (cache && !notice) await atomic(cache, rows);
const diagnostic = notice ? {notice} : {};
const brandId = name => 'ekb:brand:' + name;
const categoryId = name => 'ekb:category:' + name;
if (input.action === 'choices' || input.action === 'brand') {
const brands = new Map();
for (const item of rows) {
if (!item.brand || !item.category) continue;
if (!brands.has(item.brand)) brands.set(item.brand,{id:brandId(item.brand),name:item.brand,ready:true,templateCount:0,categories:[],profile:{name:item.brand,tone:'',visualRules:{}}});
const brand = brands.get(item.brand);
let category = brand.categories.find(row => row.name === item.category);
if (!category) {
category = {id:categoryId(item.category),name:item.category,brandId:brand.id,ready:true,templateCount:0};
brand.categories.push(category);
}
brand.templateCount++;
category.templateCount++;
}
const selected = input.brandName || input.brandId?.replace(/^ekb:brand:/,'');
if (input.action === 'brand') {
const brand = brands.get(selected);
if (!brand) throw Error('当前制作模板目录没有所选品牌');
return {brand,...diagnostic};
}
return {catalog:{kind:input.kind,items:input.kind === 'brands' ? [...brands.values()] : brands.get(selected)?.categories ?? []},...diagnostic};
}
const entries = rows.filter(item => item.brand === input.brandName && item.category === input.categoryName);
if (input.action === 'catalog') {
const query = input.query?.trim().toLocaleLowerCase() ?? '';
return {items:entries.filter(item => !query || (item.name + ' ' + item.templateId).toLocaleLowerCase().includes(query))
.map(item => ({id:item.templateId,key:item.templateId,name:item.name,brandId:input.brandId,categoryId:input.categoryId,
...(item.intake != null && {intake:intakeMetadata(item.intake)})})),...diagnostic};
}
const item = entries.find(row => row.templateId === input.resourceSetId);
if (!item) throw Error('所选模板已不在当前发布目录,请重新选择');
const labels = {detail:'详情页',main_images:'主图',sku_images:'SKU'};
const components = item.components.map(part => ({
id:part.id,name:labels[part.id] ?? part.id,kind:part.id,status:'available',issues:notice ? [notice] : [],previews:[]
}));
if (input.action === 'resource-set') return {items:components,...diagnostic};
const component = components.find(part => part.id === input.componentId);
if (!component) throw Error('当前模板没有所选组件');
const projectDir = path.join(input.root,'catalog',digest([item.templateId,item.version]));
const {packs} = await xiaoyiPacks({
templateId:item.templateId,projectDir,cache:path.join(input.root,'blobs'),
name:item.name,brandId:input.brandId,categoryId:input.categoryId,
knowledgeVersion:item.knowledgeVersion,metadataOnly:true,intake:intakeMetadata(item.intake),
},{signal,fetch,onProgress});
if (!packs[component.id]) throw Error('制作包缺少所选组件,请联系知识库管理员');
return {items:[{...component,pack:packs[component.id]}],...diagnostic};
}
export async function templateRequest(input,options) {
if (input.action === 'xiaoyi-pack') return xiaoyiPacks(input,options);
if (['choices','brand','catalog','resource-set','resource-component'].includes(input.action)) {
return xiaoyiCatalog(input,options);
}
if (typeof input.root !== 'string' || !path.isAbsolute(input.root)) throw Error('模板缓存目录无效');
let client=clients.get(input.root);
if (!client) {client=new EnterpriseTemplates(input.root);clients.set(input.root,client);}
return client.request(input,options);
}