import L from"node:path";import{existsSync as b}from"node:fs";import{writeFile as x,access as v,rm as N,constants as X}from"fs/promises";import{REDOCLY_ROUTE_RBAC as _,REDOCLY_TEAMS_RBAC as D}from"@redocly/config";import $ from"picomatch";import{DEFAULT_LOCALE_PLACEHOLDER as C}from"../../../../constants/index.js";import{isBuildMode as j}from"../../../utils/is-build-mode.js";import{AI_INDEX_EXPORT_FOLDER as G}from"../constants.js";import{LLMS_TXT_FILE_NAME as k}from"../../../constants/common.js";import{shaHexShort as B}from"../../../utils/crypto.js";import{ensureDir as A}from"../../../utils/fs.js";import{canAccessResource as q,extractTeamsForSearch as H,getRbacTeamsForSearch as U}from"../../../utils/rbac.js";import s from"../../../utils/reporter/logger.js";import{promiseMapLimit as M}from"../../../utils/async.js";import{validateLLMsTxtConfig as Y,generateLLMsTxt as J,getLLMsTxtMdSlug as K}from"../llmstxt/index.js";const w=20,R="llms.txt:";async function Lt(t,e,{aiSearchEnabled:i,llmstxtEnabled:a}){const c=L.join(t.outdir,k);if(!a){try{await v(c,X.W_OK),await N(c)}catch{}if(!i)return}s.info("Preparing AI search documents...");const p=s.startTiming(),r=t.getGlobalConfig("seo"),m=r?.llmstxt,g=L.resolve(t.outdir,G),f=t.getConfig(),S=f.rbac??{},E=t.getGlobalConfig("requiresLogin"),P=t.getAllRoutes(),F=f?.l10n?.defaultLocale||f?.i18n?.defaultLocale||C,O=(m?.excludeFiles||[]).map(o=>$(o)),T=[];if(await M(P,w,async o=>{const d=await V(o,t),h=await W(o,d,e,t);if(h){if(a&&q(o,{teams:["anonymous"]},S,E))for(const n of await h.getLLMsTxts()){if(O.some(l=>l(n.fsPath)))continue;const u=L.join(t.outdir,K(n.slug));A(u),await x(u,n.content),n.includeInLLMsTxt&&T.push(n)}if(i&&j()){const n=await h.getSearchDocuments();if(!n.length)return;const u=z(o,S),l=o.versions?.find(({active:I})=>I),y=l&&{folder:l.folderId,label:l.label,default:l.default};await Q(n,o.fsPath,u,g,F,y)}}}),T.length)try{Y(m),s.info(`${R} Generating llms.txt files...`);const o=s.startTiming(),d=await J(T,m,{title:r?.title,description:r?.description},e);A(c),await x(c,d),s.infoTime(o,`${R} files generated`)}catch(o){s.error(`${R} Failed to generate llms.txt file. ${o.message}`)}s.infoTime(p,"AI search documents prepared")}async function V(t,e){return t.getStaticData?t.getStaticData(t,{...e,contentDir:e.contentDir,parseMarkdoc:(...i)=>e.parseMarkdoc(...i)}):{}}async function W(t,e,i,a){if(t.getAiDocumentsStore)return t.getAiDocumentsStore(t,{...e,[D]:t[D],[_]:t[_]},i,a)}function z(t,e){const i=H(t?.[D]);return i?.length?i:U(t,e)}async function Q(t,e,i,a,c,p){await M(t,w,async r=>{const m=`${B(e+r.content)}.json`,g=A(L.join(a,m)),f=r.locale===C?c:r.locale;b(g)||await x(g,JSON.stringify({...r,rbacTeams:i||[],version:p,locale:f}),"utf-8")})}export{Lt as prepareAiSearchDocuments};
