import{writeFileSync as Y}from"node:fs";import*as f from"path";import q from"@markdoc/markdoc";import{withoutHash as Q}from"@redocly/theme/core/utils";import{DEFAULT_LOCALE_PLACEHOLDER as w,SIDEBAR_PREFIX as ee,CONFIG_FILE_NAME as W}from"../../../constants/index.js";import{CATALOG_OUTPUT_FILE_NAME as te}from"../../constants/common.js";import{collectItemsLinkedToSidebars as ae,resolveItems as V}from"../nav-utils.js";import{collectPropValueDeep as _,findDeepFirst as T,isDefined as G,partition as re}from"../../../shared/jsUtils.js";import{logger as M,readEnvVariable as oe,reporter as R}from"../../utils/index.js";import{isLocalLink as ie,normalizeRouteSlug as H,slash as se}from"../../../shared/utils.js";import{getInnerText as ne}from"../../../shared/markdoc.js";import{getSidebarReferences as le,hasCircularDependency as ce}from"./utils.js";import{getLocaleFromRelativePath as fe}from"../../fs/utils/get-locale-from-relative-path.js";import{parsePathVersions as de}from"../config-parser/loaders/versions-config-loader.js";import{isSystemRouteSlug as ue}from"../../utils/system-routes.js";async function Ae({contentDir:d}){return{id:"sidebars",async afterRoutesCreated(a,n){const{cache:c,fs:l}=n,y=a.getConfig(),v=new Map,S=new Set,x=[w,...l.localeFolders],N=new Map;let A=(await l.scan(/sidebars.yaml$/)).map(({relativePath:t})=>t).filter(t=>!pe(y.ignore??[],t)&&t);const $=await le(n,d,A),Z=re(A.filter(t=>!$.has(t)),t=>de(t)?.versionFolderPath||t),J=await ae(y?.navbar,a,n,{navFile:W});let F;const E=ce($);E&&Array.isArray(E)&&R.panicOnBuildContentError(`Sidebar references have circular dependency. Please check your sidebar files.
            Circular dependency chain: ${E.reverse().join(" -> ")}
          `);for(const t of Z){const u=(await Promise.all(t.map(async e=>{const i=(await c.load(e,"yaml")).data;if(!Array.isArray(i)){R.panicOnBuildContentError('Invalid sidebar contents at %s, items should be an array, got "%s"',e,typeof i);return}return{items:i,sidebarRelativePath:e,locale:fe(e)}}))).filter(G),r=(await D(u))?.firstLink;F||(F=r)}const j=Object.entries(y?.catalogClassic??{});for(const t of x){for(const[e,i]of j)await z(e,i,t);const u={},r=new Set;for(const e of a.getAllRoutesForLocale(t).values())if(S.has(e.slug)&&e.fsPath&&!r.has(e.fsPath)){r.add(e.fsPath);let o=f.posix.dirname(e.fsPath);const g=f.parse(o).root;do u[o]=(u[o]||0)+1,o=f.dirname(o);while(o&&o!="."&&g!=o)}for(const e of a.getAllRoutesForLocale(t).values()){if(v.has(e.slug))continue;const i=S.has(e.slug),o=f.dirname(e.fsPath),g=u[o]===1,b=(e.baseSlug||e.slug).replaceAll("/","_");i&&g?await D([{items:[{directory:o}],sidebarRelativePath:"sidebar.yaml_"+b,locale:t}]):e.getSidebar!==void 0&&await D([{items:[{page:e.fsPath}],sidebarRelativePath:"sidebar.yaml_"+b,locale:t}])}for(const[e,i]of j)await z(e,i,t,!0)}if(A.length===0)for(const t of x){M.verbose("Creating default sidebar");const u=t===w,r=`sidebars.yaml${u?"":"_"+t}`,e=u?"":`${l.localizationFolder}/${t}`,i=(await D([{items:[{directory:`./${e}`}],sidebarRelativePath:r,locale:t,ignoredRoutes:S}]))?.firstLink;F||(F=i)}if(!a.getRouteBySlug("/")&&!a.getConfig().redirects?.["/"]){const u=a.getAllRoutes().find(e=>!ue(e.slug)),r=F?F.link:u?.baseSlug??null;if(r){const e=Q(r);a.addRedirect("/",{to:e,type:302}),M.info("Creating default redirect for index page => %s",e)}}const B=oe("REDOCLY_METADATA_OUTPUT_FOLDER");B&&(M.info("Writing catalog data..."),Y(f.join(B,te),JSON.stringify(Object.fromEntries(N.entries()))));async function D(t){if(t.length===0)return;const r=(await Promise.all(t.map(async({items:g,locale:b,sidebarRelativePath:P,ignoredRoutes:I})=>{const L=await V(g,f.dirname(f.join(d,P)),a,n,{locale:b,ignoredRoutes:I,navFile:P});if(!L){R.panicOnBuild("Failed to resolve sidebar configuration. Make sure %rp is valid",P);return}return L}))).flat().filter(G),e=_(r,"routeSlug"),i=t[0].sidebarRelativePath,o=await a.createSharedData(K(i),{relatedNavbarItem:J?.get(i),items:r});for(const g of e)a.addRouteSharedData(g,"sidebar",o),v.set(H(g),r);return{firstLink:T(r,g=>!!g.link),resolved:r}}async function z(t,u,r,e=!1){const i=structuredClone(u);r&&r!==w&&i.items.forEach(s=>{s.directory=f.posix.join(l.localizationFolder||"",r,s.directory||"")});let o=await V(i.items,d,a,n,{groupCustomSidebars:!0,locale:r,navFile:W});if(o&&(o=me(o)),!o){R.panicOnBuild(`Failed to resolve catalog configuration. Make sure catalog ${t} has valid config`);return}const g=r===w?"":"/"+r.toLowerCase(),b=r===w?"":`-${r}`,P=H(f.posix.join(g,i.slug));if(e)for(const s of o){const m=T(s.items||[],h=>!!h.routeSlug);if(!m?.routeSlug)continue;const p=v.get(m.routeSlug);if(!p)continue;const O=_(p,"routeSlug"),k="current-catalog-info-"+s.routeSlug+b,C={catalog:{label:i.title,titleTranslationKey:i.titleTranslationKey,link:P},item:{label:s.metadata?.title,link:s.link}};await a.createSharedData(k,C);for(const h of O)a.addRouteSharedData(h,"current-catalog-info",k),S.add(h);const U=T(p,h=>!!h.link&&!h.external&&ie(h.link)&&(!s.version||h.version===s.version));U&&(s.sidebar=[{...U,items:void 0}])}const I={},L=new Set;for(const s of o){if(!(s.routeSlug||s.sidebar?.[0]?.routeSlug)||!s.fsPath||L.has(s.fsPath))continue;L.add(s.fsPath);const p=f.dirname(s.fsPath);I[p]=(I[p]||0)+1}if(e){const s=await a.createSharedData("catalog-"+t+b,o.flatMap(m=>{const p=f.dirname(m.fsPath??""),O=I[p]===1,k=C=>({...C,fsPath:O?p:C.fsPath??""});return m.type==="group"&&m.items?.every(C=>C.type==="group")?(m.items||[]).map(k):k(m)}));a.addRouteSharedData(P,"catalog",s),ge(r,o,N,I)}const X=_(o,"routeSlug");for(const s of X)S.add(s)}}}}function ge(d,a,n,c){if(d===w)for(const l of a){const y=l.routeSlug||l.sidebar?.[0]?.routeSlug;if(!y||!l.fsPath)continue;const v=f.dirname(l.fsPath),S=c[v]===1;n.set(y,{rootFileFsPath:l.fsPath,fsPath:S?v:l.fsPath,metadata:l.metadata||{},title:l.metadata?.title||l.label||"Untitled",version:l.version||"latest"})}}function me(d){const a=n=>{if(!n)return n;const c=q.parse(n);return ne([c])};return d.map(n=>{const c={...n};return c.metadata?.description&&(c.metadata={...c.metadata,description:a(c.metadata.description)}),c})}function K(d){return ee+se(d)}async function Ee(d,a,n){const c=f.posix.join(f.dirname(d),a);return await n.exists(c)?K(c):(R.panicOnBuildContentError(`Failed to create relative path for sidebars.yaml using ${a}`),null)}function pe(d,a){const n=/\/?([a-zA-Z0-9-_]+\/)*sidebars?(-[a-zA-Z0-9-_]+)?\.yaml/;return d.filter(l=>n.test(l)).includes(a)}export{pe as isSidebarIgnored,me as removeMarkdownTags,Ee as resolveSidebarId,Ae as sidebarsPlugin};
