1import{M as e}from"./AppContext-BLosOwCf.js";import{M as t,b as r,et as a,j as i}from"./metadataReasoningEffort-C7LCniRE.js";import{C as o,f as s,t as n}from"./intellectualPropertyRisk-Ci1Vm_g7.js";import{r as l,u as d}from"./fileHelpers-B8ZwLNgH.js";import{t as p}from"./metadataProcessing-VucWvZk4.js";import{a as c,f as g,r as u}from"./rightsVerificationAccess-BtoMS9Mx.js";import{A as y,C as m,D as f,E as h,L as C,O as w,P as k,S,T as F,U as b,at as I,b as v,d as P,f as E,it as T,j as R,k as M,p as A,q,rt as O,s as _,u as D,v as L,w as x,x as U,y as K}from"./AppContent-DsUwgMov.js";var N=e=>String(e||"").trim(),B=()=>"undefined"!=typeof performance?performance.now():Date.now(),V=()=>{const e=new Error("StockTag could not save the recovery record for this operation. No AI request was sent and no credit was used. Please allow site storage and try again.");return e.code="metadata_recovery_journal_unavailable",e},j=async({applyMetadataDraftPipelineArgs:j={},applyPlatformFieldFallbacks:W,applyPlatformFieldsFromMetadataResponse:H,capitalizeTitleWords:$,clearPendingDraftResult:z,contentUsage:J,currentDraftIdRef:Y,creativeFabricaCSVEnabled:G,customPromptMessage:Q,deductCredit:X,descriptionLengthPreference:Z,designBundlesCSVEnabled:ee,detectArtStyles:te,disallowSpecialCharacters:re,getProcessedFilesSnapshot:ae,getMetadataCreditCost:ie,gettyImagesCSVEnabled:oe,gettyIstockEnrichmentEnabled:se,gettyIstockOnlyMode:ne,humanModelEthnicity:le,getCurrentUser:de,globalCreditLock:pe,incrementProcessedCount:ce,intellectualPropertyScanEnabled:ge,isPngMode:ue,isVectorMode:ye,istockCSVEnabled:me,outputLanguage:fe="en",keywordsLengthPreference:he,loadHistoryServiceModule:Ce,openByokLimitPrompt:we,openGuestPrompt:ke,processedFiles:Se=[],processImageAsset:Fe,processingAbortRef:be,metadataDispatchAbortRef:Ie=null,pushUndoState:ve,requestedKeywordCount:Pe,resolveAiRequestConfig:Ee,setByokDailyLimitReached:Te,setProcessedFiles:Re,stagePendingDraftResult:Me,showError:Ae,showWarning:qe,shutterstockCSVEnabled:Oe,singleWordKeywordsOnly:_e,siteCopy:De,titleLengthPreference:Le,useFilenameAsContext:xe,user:Ue},Ke,Ne=null)=>{const Be="function"==typeof de?de():Ue,Ve=String(Be?.uid||"").trim(),je=()=>{if("function"!=typeof de)return!1;try{return String(de()?.uid||"").trim()!==Ve}catch{return!0}},We=()=>!0===be?.current||je(),He=()=>{f(We)},$e=s(J),ze=$e===n.COMMERCIAL&&!0===ge,Je=se&&!ne;if(!Ke||"object"!=typeof Ke||!Ke.filename)return void Ae(De.appContent.regenerationFailed.replace("{message}","The selected file is unavailable. Please reload the metadata workspace and try again."));if(D(Ke))return void qe("StockTag is still verifying the original operation. Regeneration was blocked so the same file cannot be charged again.");if(We()||x(Ie))return;if(!Be)return void ke("regenerate_metadata");if(pe)return void qe(De.appContent.creditOperationInProgress);const Ye=Be?.plan||"free",Ge=Number(Be?.credits||0),Qe=-1===Ge?a(Be):Math.max(0,Ge),Xe=Boolean(Ke?.originalFile?.type?.startsWith?.("video/")||Ke?.previewFile?.type?.startsWith?.("video/")||Number(Ke?.videoDurationSeconds||0)>0),Ze=(e=!1)=>Xe?_(Number(Ke?.videoDurationSeconds||0))+(Je?O.gettyIstockEnrichmentCredits:0):ie(e),et=1+(Je?1:0),tt=i(Be,Qe)||t(Ye,Qe);let rt=Ee({plan:Ye,allowWarnings:!1,preferCredits:tt,isRegenerate:!0}),at=y({userPlan:Ye,userCredits:Qe,hasAnyKey:rt.hasAnyKey,requestedCreditCost:Ze(rt.enableReasoning),requestedByokCost:et,freeByokRemaining:r(Be),preferCredits:tt});at.shouldUseCredits!==tt&&(rt=Ee({plan:Ye,allowWarnings:!1,preferCredits:at.shouldUseCredits,isRegenerate:!0}),at=y({userPlan:Ye,userCredits:Qe,hasAnyKey:rt.hasAnyKey,requestedCreditCost:Ze(rt.enableReasoning),requestedByokCost:et,freeByokRemaining:r(Be),preferCredits:at.shouldUseCredits||tt}));const{provider:it,specificModel:ot,hasAnyKey:st,enableReasoning:nt,reasoningEffort:lt}=rt;if(at.requestedCreditCost,!at.canProceed)return"waiting_for_resources"===at.waitStatus?void Ae(De.appContent.byokRequiresKeyOrCredits):"waiting_for_limit"===at.waitStatus?(Ae(De.appContent.byokLimitReached.replace("{limit}",String(100))),Te(!0),void we()):void("free"===at.planCategory?Ae(De.appContent.regenerateFreeCreditsExhausted):Ae(De.appContent.regenerateInsufficientCredits));Te(!1);const dt=String(Ke.filename||"").trim(),pt=((e,t)=>{const r=N(t);return r&&Array.isArray(e)&&e.find(e=>e?.filename===r)||null})("function"==typeof ae?ae():Se,dt);if(!pt)return;const ct=async(e={})=>{const t=String(Y?.current||"").trim();if(!Ve||!t||"function"!=typeof Me)throw V();const r={...pt,...e,filename:pt.filename||Ke.filename,processingStatus:"pending",queueState:"running",lastOutcomeAtMs:Date.now()};if(!Me(r,t,{immediate:!0}))throw V();"function"==typeof Ce&&Ce().then(({updateDraftHistory:e})=>e(Ve,t,r)).catch(e=>{})},gt=e=>{Re(t=>((e,t,r)=>{const a=N(t);if(!a||!Array.isArray(e)||"function"!=typeof r)return e;let i=!1;const o=e.map(e=>{if(e?.filename!==a)return e;const t=r(e);return t!==e&&(i=!0),t});return i?o:e})(t,dt,e))},ut=pt.mediaKind||l(Ke),yt=d(pt,{isPngMode:ue,isVectorMode:ye,preferStored:!0}),mt=(e,t=null,r=!1)=>{gt(a=>({...a,isRegenerating:!0,...I({siteCopy:De,phase:e,progress:t,requestFingerprint:a.requestFingerprint||"",processingStatus:r?"success":"pending",queueState:r?"idle":"running",clearLabel:r})}))},ft={title:pt.title||"",description:pt.description||"",keywords:Array.isArray(pt.keywords)?[...pt.keywords]:[],category:pt.category||"",shutterstockCategory:pt.shutterstockCategory||"",gettyIstockTitle:pt.gettyIstockTitle||"",gettyIstockDescription:pt.gettyIstockDescription||"",gettyIstockCreatedDate:pt.gettyIstockCreatedDate||"",gettyIstockCountry:pt.gettyIstockCountry||"",gettyIstockKeywords:Array.isArray(pt.gettyIstockKeywords)?[...pt.gettyIstockKeywords]:[]};try{gt(e=>({...e,isRegenerating:!0,title:"",description:"",keywords:[],error:null,...I({siteCopy:De,phase:T.prepare,progress:8,requestFingerprint:e.requestFingerprint||"",processingStatus:"pending",queueState:"running"})}));const t=B();let r="",a=Ke.previewFile||Ke.pairedJpgFile||null,i=Ke.requestFingerprint||"",s=Ke.assetFacts||pt.assetFacts||null;if(Ke.downloadURL){const e=await fetch(Ke.downloadURL);if(He(),!e.ok)throw new Error(`Failed to download file from Storage: ${e.statusText}`);const t=await e.blob();He();const o=new File([t],Ke.filename||Ke.originalFile?.name||"downloaded-file",{type:t.type||Ke.originalFile?.type||"application/octet-stream",lastModified:Date.now()}),n=await Fe(Ke.previewFile||Ke.pairedJpgFile||o,"vector"===yt);He(),r=n.base64,a=Ke.previewFile||Ke.pairedJpgFile||n.previewFile||a,i=i||n.assetFingerprintBase||"",s=n.assetFacts||s}else if(Ke.originalFile instanceof File){const e=await Fe(Ke.previewFile||Ke.pairedJpgFile||Ke.originalFile,"vector"===yt);He(),r=e.base64,a=Ke.previewFile||Ke.pairedJpgFile||e.previewFile||a,i=i||e.assetFingerprintBase||"",s=e.assetFacts||s}else Ke.originalFile?.base64Data&&(r=Ke.originalFile.base64Data);if(!r)throw new Error("No image data available for regeneration. The file might be missing from Storage.");a&&a!==Ke.previewFile&>(e=>({...e,previewFile:a}));const n=Ke.metadata?.title||Ke.title||"",l=Ke.metadata?.keywords||Ke.keywords||[],d=Ke.metadata?.category||Ke.category||"",y=Ke.metadata?.shutterstockCategory||Ke.shutterstockCategory||"",f=Array.isArray(l)?l.slice(0,10).join(", "):"",F=Ne?`\n\nð¯ REFINEMENT INSTRUCTION - IMPORTANT:\nThe user wants to refine the previous result with this specific instruction: "${Ne}"\n\nPREVIOUS RESULT:\n- Title: "${n}"\n- Keywords: ${f}\n- Category: "${d}"\n- Shutterstock Category: "${y}"\n\nCRITICAL INSTRUCTION - PARTIAL UPDATES:\n1. If the user asks to change ONLY one specific field (e.g. "change title"), YOU MUST KEEP ALL OTHER FIELDS EXACTLY THE SAME as the "PREVIOUS RESULT" provided above.\n2. Do NOT regenerate keywords if the user only asked for a title change.\n3. Do NOT change the category unless explicitly asked or if the new subject matter completely invalidates the old category.\n4. Output the FULL JSON with both the NEW/MODIFIED fields and the UNCHANGED existing fields.`:n||f?`\n\nð REGENERATE REQUEST - IMPORTANT:\nThe following metadata was previously generated for this image but was not satisfactory:\n- Previous Title: "${n}"\n- Previous Keywords (sample): ${f}\n\nYou MUST generate COMPLETELY DIFFERENT and MORE DESCRIPTIVE title and keywords. Do NOT reuse or slightly modify the previous ones. Be more creative, specific, and SEO-optimized.`:"",O=Q?`${Q}${F}`:F,_=_e||e(Q)||e(Ne),D=a||Ke.previewFile||Ke.pairedJpgFile||Ke.originalFile||{name:Ke.filename,type:"image/jpeg"},N=String(Ke?.filename||Ke?.originalFile?.name||"").toLowerCase().match(/\.([a-z0-9]{1,12})$/)?.[1]||"",J={...s||{},sourceFileName:Ke?.filename||Ke?.originalFile?.name||D?.name||"",..."vector"===ut&&N?{sourceFormat:N,formatEvidence:"upload-media-kind"}:{},actualVectorSource:"vector"===ut}
1,ae=P(D),ie=D?.type?.startsWith?.("video/")?"video":yt,de=((e="")=>String(e||"").match(/^data:([^;,]+);base64,/i)?.[1]?.trim()||"")(r)||D?.type||"image/jpeg",pe=Ke.requestFingerprint||await k({assetFingerprintBase:i,base64Image:r,mimeType:de,fileType:ie,sourceFileName:D?.name||Ke.filename||""});He();const ge=C({operationType:"video"===ie?"video_metadata":"metadata_regenerate",reasoningEnabled:nt,reasoningEffort:lt,gettyEnabled:Je,rightsEnabled:ze,fileType:ie,durationSeconds:Number(Ke?.videoDurationSeconds||0)});b({phase:"prepare",latencyMs:B()-t,queueWaitMs:0,provider:it,model:ot||"",fileType:ie,gettyEnabled:se,usageSource:"estimated",requestFingerprint:pe});const ue=c(),ye=u(D,{isVector:"vector"===yt,isPng:"png"===yt,titlePreset:Le,descPreset:Z,keyPreset:he,customMsg:O,contentUsage:$e,outputLanguage:fe,forceSingleWordKeywords:_,disallowSpecialCharacters:re,capitalizeTitleWords:$,humanModelEthnicity:le,detectArtStyles:te,intellectualPropertyScanEnabled:ze,reasoning:nt,shutterstockCSVEnabled:Oe||"true"===localStorage.getItem("shutterstockCSVEnabled"),cfEnabled:G,dbEnabled:ee,gettyIstockCSVEnabled:ne,gettyIstockOnlyMode:ne,assetFacts:J,useFilenameAsContext:xe,filenameContext:Ke?.filename||Ke?.originalFile?.name||D?.name||"",regenerate:!0,customRanges:ue});mt(T.main_request,26),await ct({metadataLanguage:ne?"en":fe,titleLengthPreference:Le,descriptionLengthPreference:Z,requestFingerprint:pe,normalizedPixelFingerprint:pe,provider:it,resolvedModel:ot||"",operationId:ge.operationId,operationStep:"main_request",operationType:ge.operationType,operationContext:ge.operationContext,mainOperationId:ge.operationId,mainOperationType:ge.operationType,mainOperationContext:ge.operationContext,processingProgress:26,processingPhase:T.main_request}),h({processingAbortSource:We,stopFutureDispatchSource:Ie});const we=await R.generateMetadataForUser(r,ye,Be,!0,it,!0,de,at.a
1piKeyOverride,nt,ot,null,at.shouldCountFreeByok,{phase:"main_request",requestFingerprint:pe,assetFingerprintBase:i||pe,fileType:ie,gettyEnabled:Je,reasoningEffort:lt,...ge,shouldDispatch:()=>!We()&&!x(Ie),operationStep:"main_request"});He();const ke="object"==typeof we?we.content:we,Se="object"==typeof we?we.usage:null,be=we?.operationId||ge.operationId,Te=await ae,Re={...pt,metadataLanguage:ne?"en":fe,contentUsage:$e,intellectualPropertyScanEnabled:ze,intellectualPropertyRisk:ze&&pt.intellectualPropertyRisk||null,isRegenerating:!1,lastProcessed:(new Date).toLocaleTimeString(),processingStatus:"success",queueState:"idle",requestFingerprint:pe,operationId:be,operationStep:"main_request",operationType:ge.operationType,operationContext:ge.operationContext,sourceContentHash:Te.sourceContentHash||pt.sourceContentHash||"",sourceRightsMetadata:Te.sourceRightsMetadata||pt.sourceRightsMetadata||null,assetFacts:J,error:null,tokenUsage:Se?{main:Se,platform:null}:pt.tokenUsage},Ae=B();let qe=p(ke,{medium:"video"===ie?"video":yt,sourceFileName:D?.name||Ke?.filename||"",assetFacts:J,outputLanguage:fe,titleLengthPreference:Le,descriptionLengthPreference:Z,requestedKeywordCount:Pe,flexibleKeywordCount:o(he),gettyIstockOnlyMode:ne,forceSingleWordKeywords:!ne&&_});if(qe&&("unknown"===qe.title||"Content for unknown"===qe.title))throw new Error("AI generation failed (returned unknown data) - Please retry");!qe?.title||ne||"en"!==fe||_e||x(Ie)||(He(),qe=await m({cleanedMetadata:qe,applySpecialCharacterPolicy:j.applySpecialCharacterPolicy,requestedKeywordCount:Pe,shouldAbort:We,shouldStopFutureDispatch:Ie}),He()),qe&&(ne?Object.assign(Re,g({...Re,...qe},{maxKeywordCount:Pe,preserveSelection:!1})):Object.assign(Re,S({metadata:Re,cleanedMetadata:qe,capitalizeTitleWords:$,keywordsLengthPreference:he,...j,applyPlatformFieldsFromMetadataResponse:H}))),b({phase:"main_clean",latencyMs:B()-Ae,queueWaitMs:Number(we?.queueWaitMs||0),provider:it,model:we?.resolvedModel||ot||"",fileType:ie,gettyEnabled:se,usageSource:q(Se)?"measured":"estimated",requestFingerprint:pe});let Ue=null,je="",Ge="",Qe="",Xe=null,Ze=!1;if(Je){He(),mt(T.platform_request,ze?70:74);const e=at.shouldUseCredits,t=Ee({plan:Ye,reasoning:!1,allowWarnings:!1,preferCredits:e,isRegenerate:!0}),a=await U({base64Image:r,metadata:Re,promptSourceFile:D,user:Be,modelProvider:t.provider,apiKey:e?"proxy":null,specificModel:t.specificModel,skipCache:!0,isVector:"vector"===yt,gettyImagesCSVEnabled:oe,istockCSVEnabled:me,requestedKeywordCount:Pe,titleLengthPreference:Le,descriptionLengthPreference:Z,contentUsage:$e,countFreeByok:!e,requestFingerprintBase:pe,assetFingerprintBase:i||pe,operationId:be,operationType:ge.operationType,operationContext:ge.operationContext,onOperationPrepared:e=>ct({...Re,...e,mainOperationId:be,mainOperationType:ge.operationType,mainOperationContext:ge.operationContext,processingProgress:70,processingPhase:T.platform_request}),onOperationSettled:e=>ct({...H(Re,e.cleaned),...e,mainOperationId:be,mainOperationType:ge.operationType,mainOperationContext:ge.operationContext,processingProgress:76,processingPhase:T.platform_request}),shouldAbort:We});He(),Ze=!0,a?.cleaned&&Object.assign(Re,H(Re,a.cleaned)),Xe=a?.usage||null}if(Object.assign(Re,W(Re)),ze){He(),mt(T.rights_review,82);try{const e=await A({processImageAsset:Fe,sourceFile:D,promptSourceFile:D,isVectorMode:"vector"===yt,fileType:ie,fallbackBase64Image:r,fallbackAssetFingerprintBase:i||pe,fallbackRequestFingerprintBase:pe});try{e.preparationError,Re.rightsVisualProfile=e.processingProfile||"metadata-visual-fallback",Re.rightsVisualDimensions={width:e.analysisWidth,height:e.analysisHeight},Re.rightsVisualFallbackUsed=e.usedFallback;const t=await v({base64Image:e.base64Image,promptSourceFile:e.promptSourceFile,metadata:Re,user:Be,skipCache:!0,medium:ie,requestFingerprintBase:e.requestFingerprintBase||pe,assetFingerprintBase:e.assetFingerprintBase||pe,operationId:be,operationType:ge.operationType,operationContext:ge.operationContext,onOperationPrepared:e=>ct({...Re,...e,...e.priorRisk?{intellectualPropertyRisk:e.priorRisk}:{},mainOperationId:be,mainOperationType:ge.operationType,mainOperationContext:ge.operationContext,rightsAuditStatus:"processing",rightsAuditOperationId:e.operationId,rightsAuditModel:e.resolvedModel,processingProgress:"rights_audit"===e.operationStep?89:82,processingPhase:"rights_audit"===e.operationStep?T.rights_audit:T.rights_review}),onOperationSettled:e=>ct({...Re,...e,intellectualPropertyRisk:e.risk,sourceRightsMetadata:E(Re.sourceRightsMetadata,e.risk),mainOperationId:be,mainOperationType:ge.operationType,mainOperationContext:ge.operationContext,rightsAuditStatus:"rights_audit"===e.operationStep?"success":"processing",rightsAuditOperationId:e.operationId,rightsAuditModel:e.resolvedModel,processingProgress:"rights_audit"===e.operationStep?91:86,processingPhase:"rights_audit"===e.operationStep?T.rights_audit:T.rights_review}),shouldAbort:We,shouldStopFutureDispatch:null});He(),Re.intellectualPropertyRisk=t.risk,Re.sourceRightsMetadata=E(Re.sourceRightsMetadata,t.risk),Ue=t.usage||null,je="success",Re.rightsAuditedAt=Date.now(),Ge=String(t?.operationId||""),Qe=String(t?.resolvedModel||"gpt-5.4")}finally{e.cleanup()}}catch(ht){if(!K(ht))throw ht;const e=L(ht);Re.intellectualPropertyRisk=e.risk,Ue=e.usage,je="failed",Ge=e.operationId,Qe=e.resolvedModel}}else Re.intellectualPropertyRisk=null;He(),mt(T.draft_write,92);const et=B();Re.mediaKind=ut,Re.resolvedPromptMedium=yt,Re.isVector="vector"===ut,Re.operationId=be,Re.operationStep=Ze?"platform_request":"main_request",Re.operationType=ge.operationType,Re.operationContext=ge.operationContext,Re.normalizedPixelFingerprint=pe,Re.rightsAuditStatus=je,Re.rightsAuditOperationId=Ge,Re.rightsAuditModel=Qe,Object.assign(Re,I({siteCopy:De,phase:T.completed,progress:100,requestFingerprint:pe,processingStatus:"success",queueState:"idle",clearLabel:!0})),(Se||Ue||Xe)&&(Re.tokenUsage={main:Se||null,rights:Ue,platform:Xe}),b({phase:"draft_write",latencyMs:B()-et,queueWaitMs:0,provider:it,model:we?.resolvedModel||ot||"",fileType:ie,gettyEnabled:se,usageSource:q(Se)||q(Ue)||q(Xe)?"measured":"estimated",requestFingerprint:pe});const tt=B();He();const rt=await w({funding:at,deductCredit:X,incrementProcessedCount:ce,serverSettled:!0});if(He(),!rt?.success){const e=new Error(rt?.error?.message||"Metadata billing failed");throw e.code=M(rt?.waitStatus)||rt?.error?.code||"system_error",e}b({phase:"credit_update",latencyMs:B()-tt,queueWaitMs:0,provider:it,model:we?.resolvedModel||ot||"",fileType:ie,gettyEnabled:se,usageSource:q(Se)||q(Ue)||q(Xe)?"measured":"estimated",requestFingerprint:pe}),He(),ve({type:"regenerate",filename:Ke.filename,before:ft,after:{title:Re.title||"",description:Re.description||"",keywords:Array.isArray(Re.keywords)?[...Re.keywords]:[],category:Re.category||"",shutterstockCategory:Re.shutterstockCategory||"",gettyIstockTitle:Re.gettyIstockTitle||"",gettyIstockDescription:Re.gettyIstockDescription||"",gettyIstockCreatedDate:Re.gettyIstockCreatedDate||"",gettyIstockCountry:Re.gettyIstockCountry||"",gettyIstockKeywords:Array.isArray(Re.gettyIstockKeywords)?[...Re.gettyIstockKeywords]:[]}}),He();const st=String(Y?.current||"").trim();if(!Me(Re,st,{immediate:!0}))throw V();"function"==typeof Ce&&Ce().then(({updateDraftHistory:e})=>e(Ve,st,Re)).then(()=>z?.(Re.filename,st)).catch(e=>{}),gt(()=>Re)}catch(Ct){if(We()||"processing_aborted"===Ct?.code||F(Ct))return void(je()||gt(()=>({...pt,isRegenerating:!1,error:null})));"byok_daily_limit"===Ct.code?(Te(!0),we(),Ae(De.appContent.byokLimitReached.replace("{limit}",String(100)))):"byok_missing_resources"===Ct.code?Ae(De.appContent.byokRequiresKeyOrCredits):"insufficient_credits"===Ct.code?"free"===at.planCategory?Ae(De.appContent.regenerateFreeCreditsExhausted):Ae(De.appContent.regenerateInsufficientCredits):Ae(De.appContent.regenerationFailed.replace("{message}",String(Ct.message||"")));const e=["insufficient_credits","byok_daily_limit","byok_missing_resources"].includes(Ct?.code);gt(()=>e?{...pt,isRegenerating:!1,error:null}:{...pt,isRegenerating:!1,error:Ct.message,...I({siteCopy:De,phase:T.failed,progress:0,requestFingerprint:pt.requestFingerprint||"",processingStatus:"failed",queueState:"idle",clearLabel:!0})})}};export{j as default,j as runMetadataRegeneration}; 2//# sourceMappingURL=metadataRegenerationRuntime-D8nwb5jp.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.