"use strict";(()=>{var a={};a.id=3250,a.ids=[3250],a.modules={261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},1820:a=>{a.exports=require("os")},3033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},3295:a=>{a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},3873:a=>{a.exports=require("path")},4075:a=>{a.exports=require("zlib")},4870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},5511:a=>{a.exports=require("crypto")},6232:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>S,patchFetch:()=>R,routeModule:()=>N,serverHooks:()=>Q,workAsyncStorage:()=>O,workUnitAsyncStorage:()=>P});var d={};c.r(d),c.d(d,{POST:()=>M});var e=c(9225),f=c(4006),g=c(8317),h=c(9373),i=c(4775),j=c(4235),k=c(261),l=c(4365),m=c(771),n=c(3461),o=c(7798),p=c(2280),q=c(2018),r=c(5696),s=c(7929),t=c(6439),u=c(7527),v=c(9021),w=c.n(v),x=c(3211),y=c(4098),z=c(2363),A=c(3945),B=c(7044),C=c(9310),D=c(1254),E=c(8281),F=c(3081),G=c(7715),H=c(9570),I=c(7167);async function J(a){return a.provider.generateText({system:"You are a revision editor. Apply only requested local edits to existing content. Keep structure and unchanged sections intact. Do not regenerate from scratch. Understand Chinese, English, or mixed Chinese-English body-part and craft instructions as precise local design constraints.",user:`Field: ${a.fieldName}
${a.context}

Revision instruction:
${a.instruction}

Original text:
${a.currentText}

Return revised text only.`,signal:a.signal})}function K(a){let b=A.db.findFileById(a);return b&&w().existsSync(b.absPath)?{bytes:w().readFileSync(b.absPath),mimeType:b.mimeType||"image/png",fileName:b.fileName}:null}async function L(a){let b=await a.provider.generateText({system:"You revise an existing ecommerce image prompt. Keep all unchanged visual identity details. Apply only user-requested local changes. Understand Chinese, English, or mixed Chinese-English body-part and craft instructions as precise local design constraints.",user:`${a.context}
Original prompt:
${a.currentPrompt}

${a.promptHint?`${a.promptHint}

`:""}Revision instruction:
${a.instruction}

Return revised prompt only.`,signal:a.signal}),c=await (0,I.Oo)(a.provider,{prompt:b,count:1,size:a.size,mode:"edit",baseImage:a.baseImage,signal:a.signal}),d=await (0,B.AR)(c[0].bytes,c[0].mimeType,a.outputName,a.userId);return{fileId:d.id,url:`/api/files/${d.id}`,prompt:b}}async function M(a,{params:b}){var c;let d,e,f=await (0,y.J)();if("error"in f)return f.error;try{(0,H.vd)("refine",f.user.id)}catch(b){let a=b instanceof Error?b.message:"license check failed";return x.NextResponse.json({error:a},{status:403})}let{id:g}=await b,h=a.signal,i=A.db.findTaskById(g);if(!i)return x.NextResponse.json({error:"Task not found"},{status:404});if(i.requestedBy!==f.user.id&&"admin"!==f.user.role)return x.NextResponse.json({error:"Forbidden"},{status:403});if(!i.result)return x.NextResponse.json({error:"Task has no generated result yet"},{status:400});let j=await a.json(),k=(j.instruction||"").trim();if(!k)return x.NextResponse.json({error:"instruction is required"},{status:400});let l=Array.isArray(j.selectedImageFileIds)?Array.from(new Set(j.selectedImageFileIds.filter(a=>"string"==typeof a&&a.trim().length>0))):[],m=null;if(j.providerConfigId){let a=A.db.findProviderConfigById(j.providerConfigId);if(!a)return x.NextResponse.json({error:"Selected provider config not found"},{status:400});if("admin"!==f.user.role&&!(A.db.getUserProviderConfigBinding(f.user.id)?.configIds||[]).includes(a.id))return x.NextResponse.json({error:"Forbidden provider config selection"},{status:403});try{m={textProvider:a.textProvider,imageProvider:a.imageProvider,textBaseUrl:a.textBaseUrl,textApiKey:(0,F.wu)(a.textApiKeyEncrypted),textModel:a.textModel,imageBaseUrl:a.imageBaseUrl,imageApiKey:(0,F.wu)(a.imageApiKeyEncrypted),imageModel:a.imageModel,useSharedImageCredentials:a.useSharedImageCredentials}}catch{return x.NextResponse.json({error:"Provider config secret is invalid"},{status:500})}}else{let a="gemini"===j.textProvider||"deepseek"===j.textProvider||"mimo"===j.textProvider||"agnes"===j.textProvider?j.textProvider:"openai",b=j.textApiKey||"",c=!1!==j.useSharedImageCredentials,d=c?b:j.imageApiKey||"";if(!b||!d)return x.NextResponse.json({error:"Text API Key and Image API Key are required for refine"},{status:400});if("admin"!==f.user.role)return x.NextResponse.json({error:"Members must use assigned provider config"},{status:403});m={textProvider:a,imageProvider:"gemini"===j.imageProvider||"agnes"===j.imageProvider?j.imageProvider:"openai",textBaseUrl:j.textBaseUrl,textApiKey:b,textModel:j.textModel,imageBaseUrl:c?j.textBaseUrl:j.imageBaseUrl,imageApiKey:d,imageModel:j.imageModel,useSharedImageCredentials:c}}let n=(0,C.G)(i,m),o=(0,E.V)((0,z.b)(n),i.id),p=(d=i.request,[`Country: ${String(d.country||"")}`,`Language: ${String(d.language||"")}`,`Platform: ${String(d.platform||"")}`,`Category: ${String(d.category||"")}`,`Age group: ${String(d.ageGroup||"")}`,`Generation mode: ${String(d.generationMode||"")}`,`Product name: ${String(d.productName||"")}`,`Product info: ${String(d.productInfo||"")}`,`Global structure and craft glossary:
${(0,D.RH)(String(d.category||""))}`,d.productSpecs?`Product specs: ${String(d.productSpecs)}`:"",d.additionalRequirements?`Additional requirements: ${String(d.additionalRequirements)}`:"",d.linkExtractSummary?`Product URL insights: ${String(d.linkExtractSummary)}`:""].filter(Boolean).join("\n")),q=function(a){if(!Array.isArray(a))return[];let b=new Set;for(let c of a)"string"==typeof c&&G.JW.includes(c)&&b.add(c);return Array.from(b)}(j.targets),r=q.length?q:(c=i.result,e=[],c.nineGridImage&&e.push("NINE_GRID"),(c.productVideoPrompt||c.videoPrompt)&&e.push("PRODUCT_VIDEO_PROMPT"),c.modelVideoPrompt&&e.push("MODEL_VIDEO_PROMPT"),e);if(!r.length&&!l.length)return x.NextResponse.json({error:"No refinable target found"},{status:400});A.db.updateTask(i.id,a=>({...a,status:"running",phase:l.length?"refining_images":"refining_text",updatedAt:new Date().toISOString()}));let s=()=>!!A.db.findTaskById(i.id)?.stopRequested;try{let a=i.result,b={...a},c=[];for(let b=0;b<l.length&&!s();b+=1){let d=l[b],e=function(a,b){return a.detailImages?.find(a=>a.fileId===b)||(a.mainImage?.fileId===b?a.mainImage:void 0)||(a.nineGridImage?.fileId===b?a.nineGridImage:void 0)||(a.modelEffectImage?.fileId===b?a.modelEffectImage:void 0)}(a,d),f=K(d);if(!f||!e)continue;let g=await L({provider:o,instruction:k,context:p,currentPrompt:e.prompt,baseImage:f,size:(0,I.mB)((0,I.nZ)(i.request.resolutionPreset)),outputName:`detail-refined-${b+1}.png`,userId:i.requestedBy,signal:h,promptHint:"鞋子"===i.request.category?"Keep the image as a pure side-view shoe image only. Avoid front views, close-up detail shots, or ecommerce-style feature breakdowns.":"Keep the image as a front view or side view only. Avoid close-up detail shots or ecommerce-style feature breakdowns."});if(c.push(g),s())break}if(c.length&&(b.detailImages=[...a.detailImages||[],...c]),!s()&&r.includes("PRODUCT_VIDEO_PROMPT")&&(a.productVideoPrompt||a.videoPrompt)&&(b.productVideoPrompt=await J({provider:o,fieldName:"product video prompt text",currentText:a.productVideoPrompt||a.videoPrompt||"",instruction:k,context:p,signal:h}),b.videoPrompt=b.productVideoPrompt),!s()&&r.includes("MODEL_VIDEO_PROMPT")&&a.modelVideoPrompt&&(b.modelVideoPrompt=await J({provider:o,fieldName:"model video prompt text",currentText:a.modelVideoPrompt,instruction:k,context:p,signal:h})),!s()&&r.includes("NINE_GRID")&&a.nineGridImage){let c=K(a.nineGridImage.fileId);c&&(b.nineGridImage=await L({provider:o,instruction:k,context:p,currentPrompt:a.nineGridImage.prompt,baseImage:c,size:(0,I.mB)((0,I.nZ)(i.request.resolutionPreset)),outputName:"nine-grid-refined.png",userId:i.requestedBy,signal:h}))}let d=new Date().toISOString(),e=A.db.findTaskById(i.id),f=e?.stopRequested?"stopped":"completed";return A.db.updateTask(i.id,a=>({...a,status:f,phase:e?.stopRequested?"stopped":"refine_completed",result:b,updatedAt:d,completedAt:d,error:void 0,request:{...a.request,selectedOutputs:Array.from(new Set([...a.request.selectedOutputs]))}})),x.NextResponse.json({ok:!0,taskId:i.id,refinedTargets:r,result:b,taskStatus:f})}catch(b){if(h.aborted||b instanceof Error&&"AbortError"===b.name)return A.db.updateTask(i.id,a=>({...a,status:"stopped",phase:"stopped",updatedAt:new Date().toISOString(),completedAt:new Date().toISOString()})),x.NextResponse.json({error:"Request aborted"},{status:499});let a=b instanceof Error?b.message:"Refine failed";return A.db.updateTask(i.id,b=>({...b,status:"failed",phase:"refine_failed",error:a,updatedAt:new Date().toISOString()})),x.NextResponse.json({error:a},{status:500})}}let N=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/tasks/[id]/refine/route",pathname:"/api/tasks/[id]/refine",filename:"route",bundlePath:"app/api/tasks/[id]/refine/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"F:\\shopping\\crossborder-fashion-ai-design-exe-standard\\src\\app\\api\\tasks\\[id]\\refine\\route.ts",nextConfigOutput:"standalone",userland:d,...{}}),{workAsyncStorage:O,workUnitAsyncStorage:P,serverHooks:Q}=N;function R(){return(0,g.patchFetch)({workAsyncStorage:O,workUnitAsyncStorage:P})}async function S(a,b,c){c.requestMeta&&(0,h.setRequestMeta)(a,c.requestMeta),N.isDev&&(0,h.addRequestMeta)(a,"devRequestTimingInternalsEnd",process.hrtime.bigint());let d="/api/tasks/[id]/refine/route";"/index"===d&&(d="/");let e=await N.prepare(a,b,{srcPage:d,multiZoneDraftMode:!1});if(!e)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:g,deploymentId:v,params:w,nextConfig:x,parsedUrl:y,isDraftMode:z,prerenderManifest:A,routerServerContext:B,isOnDemandRevalidate:C,revalidateOnlyGenerated:D,resolvedPathname:E,clientReferenceManifest:F,serverActionsManifest:G}=e,H=(0,k.normalizeAppPath)(d),I=!!(A.dynamicRoutes[H]||A.routes[E]),J=async()=>((null==B?void 0:B.render404)?await B.render404(a,b,y,!1):b.end("This page could not be found"),null);if(I&&!z){let a=!!A.routes[E],b=A.dynamicRoutes[H];if(b&&!1===b.fallback&&!a){if(x.adapterPath)return await J();throw new t.NoFallbackError}}let K=null;!I||N.isDev||z||(K="/index"===(K=E)?"/":K);let L=!0===N.isDev||!I,M=I&&!L;G&&F&&(0,j.setManifestsSingleton)({page:d,clientReferenceManifest:F,serverActionsManifest:G});let O=a.method||"GET",P=(0,i.getTracer)(),Q=P.getActiveScopeSpan(),R=!!(null==B?void 0:B.isWrappedByNextServer),S=!!(0,h.getRequestMeta)(a,"minimalMode"),T=(0,h.getRequestMeta)(a,"incrementalCache")||await N.getIncrementalCache(a,x,A,S);null==T||T.resetRequestCache(),globalThis.__incrementalCache=T;let U={params:w,previewProps:A.preview,renderOpts:{experimental:{authInterrupts:!!x.experimental.authInterrupts},cacheComponents:!!x.cacheComponents,supportsDynamicResponse:L,incrementalCache:T,cacheLifeProfiles:x.cacheLife,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d,e)=>N.onRequestError(a,b,d,e,B)},sharedContext:{buildId:g,deploymentId:v}},V=new l.NodeNextRequest(a),W=new l.NodeNextResponse(b),X=m.NextRequestAdapter.fromNodeNextRequest(V,(0,m.signalFromNodeResponse)(b));try{let e,g=async a=>N.handle(X,U).finally(()=>{if(!a)return;a.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let c=P.getRootSpanAttributes();if(!c)return;if(c.get("next.span_type")!==n.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${c.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let f=c.get("next.route");if(f){let b=`${O} ${f}`;a.setAttributes({"next.route":f,"http.route":f,"next.span_name":b}),a.updateName(b),e&&e!==a&&(e.setAttribute("http.route",f),e.updateName(b))}else a.updateName(`${O} ${d}`)}),h=async e=>{var h,i;let j=async({previousCacheEntry:f})=>{try{if(!S&&C&&D&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let d=await g(e);a.fetchMetrics=U.renderOpts.fetchMetrics;let h=U.renderOpts.pendingWaitUntil;h&&c.waitUntil&&(c.waitUntil(h),h=void 0);let i=U.renderOpts.collectedTags;if(!I)return await (0,p.I)(V,W,d,U.renderOpts.pendingWaitUntil),null;{let a=await d.blob(),b=(0,q.toNodeOutgoingHttpHeaders)(d.headers);i&&(b[s.NEXT_CACHE_TAGS_HEADER]=i),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==U.renderOpts.collectedRevalidate&&!(U.renderOpts.collectedRevalidate>=s.INFINITE_CACHE)&&U.renderOpts.collectedRevalidate,e=void 0===U.renderOpts.collectedExpire||U.renderOpts.collectedExpire>=s.INFINITE_CACHE?void 0:U.renderOpts.collectedExpire;return{value:{kind:u.CachedRouteKind.APP_ROUTE,status:d.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:e}}}}catch(b){throw(null==f?void 0:f.isStale)&&await N.onRequestError(a,b,{routerKind:"App Router",routePath:d,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:M,isOnDemandRevalidate:C})},!1,B),b}},k=await N.handleResponse({req:a,nextConfig:x,cacheKey:K,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:C,revalidateOnlyGenerated:D,responseGenerator:j,waitUntil:c.waitUntil,isMinimalMode:S});if(!I)return null;if((null==k||null==(h=k.value)?void 0:h.kind)!==u.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==k||null==(i=k.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});S||b.setHeader("x-nextjs-cache",C?"REVALIDATED":k.isMiss?"MISS":k.isStale?"STALE":"HIT"),z&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let l=(0,q.fromNodeOutgoingHttpHeaders)(k.value.headers);return S&&I||l.delete(s.NEXT_CACHE_TAGS_HEADER),!k.cacheControl||b.getHeader("Cache-Control")||l.get("Cache-Control")||l.set("Cache-Control",(0,r.getCacheControlHeader)(k.cacheControl)),await (0,p.I)(V,W,new Response(k.value.body,{headers:l,status:k.value.status||200})),null};R&&Q?await h(Q):(e=P.getActiveScopeSpan(),await P.withPropagatedContext(a.headers,()=>P.trace(n.BaseServerSpan.handleRequest,{spanName:`${O} ${d}`,kind:i.SpanKind.SERVER,attributes:{"http.method":O,"http.target":a.url}},h),void 0,!R))}catch(b){if(b instanceof t.NoFallbackError||await N.onRequestError(a,b,{routerKind:"App Router",routePath:H,routeType:"route",revalidateReason:(0,o.c)({isStaticGeneration:M,isOnDemandRevalidate:C})},!1,B),I)throw b;return await (0,p.I)(V,W,new Response(null,{status:500})),null}}},6439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")},7715:(a,b,c)=>{c.d(b,{JW:()=>l,My:()=>j,OE:()=>k,P4:()=>f,T2:()=>d,Vk:()=>h,_O:()=>g,f$:()=>i,ks:()=>e});let d=["韩国","美国","比利时","加拿大","墨西哥","巴西","日本","英国","黎巴嫩","波兰","迪拜","哥斯达黎加","澳大利亚","印度","泰国","俄罗斯","意大利"],e=["English","German","Spanish","Thai","Vietnamese","Malay","Portuguese (Brazil)","French","Italian","Indonesian","Chinese","Simplified Chinese","Traditional Chinese","Japanese","Korean","Arabic"],f=["TikTok","SHEIN","Amazon","Douyin","Xiaohongshu","Mercado Libre","Taobao","Shopee"],g=["鞋子","服装","箱包"],h=["男童","女童","成年男","成年女"],i=["same_colorways","new_style"],j=["1k","2k","4k"],k=["NINE_GRID","PRODUCT_VIDEO_PROMPT","MODEL_VIDEO_PROMPT"],l=["NINE_GRID","PRODUCT_VIDEO_PROMPT","MODEL_VIDEO_PROMPT"]},9021:a=>{a.exports=require("fs")},9288:a=>{a.exports=require("sharp")},9294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},9646:a=>{a.exports=require("child_process")}};var b=require("../../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[3445,5573,1813,1590,9570,7826,1001,9310],()=>b(b.s=6232));module.exports=c})();