import{REDOCLY_ROUTE_RBAC as S,REDOCLY_TEAMS_RBAC as g}from"@redocly/config";import{existsSync as A}from"fs";import{rm as B}from"node:fs/promises";import y from"node:path";import{DEFAULT_LOCALE_PLACEHOLDER as H}from"../../../../constants/common.js";import{SEARCH_DATA_EXPORT_FOLDER as D}from"../../../constants/plugins/search.js";import{envConfig as u}from"../../../config/env-config.js";import{logger as s}from"../../../tools/notifiers/logger.js";import{extractTeamsFromScopeItems as M,getRbacTeamsListForResource as P}from"../../../utils/index.js";import{getSearchDocumentGroup as U}from"../utils.js";import{telemetry as V}from"../../../../cli/telemetry/index.js";import{telemetryTraceStep as R}from"../../../../cli/telemetry/helpers/trace-step.js";async function Q(C,r,f){await R("build.plugin.search.prepare_search_documents",async()=>{s.info("Preparing search documents and create indexes...");const n=u.SEARCH_DEV_DEBUG?y.join(r.contentDir,"..","public","client"):r.outdir;(u.SEARCH_DEV_DEBUG||u.isBuildMode)&&A(`${n}/${D}`)&&await B(`${n}/${D}`,{recursive:!0});const b=s.startTiming(),v=r.getConfig().access?.rbac,F=[H,...C.localeFolders.map(a=>a.toLowerCase())];for(const a of F)await R("build.plugin.search.prepare_search_documents.locale",async c=>{const w=r.getAllRoutesForLocale(a);let h=0,T=0;for(const t of w){if(h++,t.excludeFromSearch)continue;const d=new Map,{product:l}=t,L=await t.getStaticData?.(t,r)||{},i=await t.getSearchDocuments?.(t,{...L,[g]:t[g],[S]:t[S]},r),o=t.versions?.find(m=>m.active),x=P(t,v??{});if(i){if(i&&i.length){T+=i.length;for(const m in i){let e=i[m];const _=M(e?.[g]),E=_?.length?_:x,$=e.tags||[];e={...e,...o&&{version:o.version,isDefaultVersion:o.default,versionFolderId:o.folderId},...l&&{product:l},rbacTeams:E,tags:[...$,...E,...o?o.default?["v:default"]:[`v:${o.folderId}:${o.version}`]:["v:default"],...l?[`p:${l.name}`]:[]],url:e.url&&(e.path&&e.path.length>1?e.url:e.url.split("#")[0])};const p=U(e.facets);if(p){const O=d.get(p)??[];d.set(p,[...O,e])}}}for(const[m,e]of d)await f.addDocuments(e,{locale:a,group:m,outDir:n})}}c?.setAttribute("locale",a),c?.setAttribute("totalDocuments",h),c?.setAttribute("totalSearchDocuments",T)});if(f.cleanupFacetValues(r),s.infoTime(b,"Search indexes created"),u.SEARCH_DEV_DEBUG||u.isBuildMode){s.info("Writing out search data...");const a=s.startTiming();await f.export(n);const c=s.infoTime(a,"Search data written");c&&V.sendTimingPerformedMessage(c),A(`${n}/${D}`)||s.warn("No content available for search. Consider hiding search in config.")}})}export{Q as prepareSearchDocuments};
