import a from"picomatch";import{resolve as $}from"path";import{access as x,readFile as E,constants as F}from"fs/promises";import{logger as w}from"../../../utils/index.js";import{removeTrailingSlash as P}from"../../../../shared/utils.js";const l="llms.txt",u="Table of contents";async function I(e,t,n={title:l,description:void 0},o){if(!t)return{title:n.title||l,description:n.description,details:void 0,sections:[{title:u,description:void 0,llmstxts:e}]};const s=t.title||n.title||l,r=t.description||n.description,i=await g(t,o),c=t.sections?.map(d=>{const{title:f,description:h,excludeFiles:L,includeFiles:m}=d,T=p(e,{excludeFiles:L,includeFiles:m});return{title:f,description:h,llmstxts:T}});return{title:s,description:r,details:i,sections:c||[{title:u,description:void 0,llmstxts:p(e,{includeFiles:["**/*"],excludeFiles:[]})}]}}async function g(e,t){const n=await t.getConfig();if(e?.details?.path&&n.configPath)try{const o=await t.fs.getFileInfo(n.configPath);if(!o)throw new Error(`Config file ${n.configPath} not found`);const s=$(t.fs.cwd,o.dirname,e.details.path);return await x(s,F.R_OK),E(s,"utf-8")}catch{throw new Error(`${e.details.path} is not accessible`)}if(e?.details?.content)return e.details.content}function p(e,t){const{excludeFiles:n,includeFiles:o}=t,s=n?.map(i=>a(i)),r=o?.map(i=>a(i));return e.filter(i=>s?.some(d=>d(i.fsPath))?!1:r?.some(d=>d(i.fsPath)))}async function R(e,t,n={title:l,description:void 0},o){const s=await I(e,t,n,o),r=[`# ${s.title}

`];return s.description&&r.push(`> ${s.description}

`),s.details&&r.push(`${s.details}

`),s.sections.forEach(i=>{if(!i.llmstxts.length){w.warn(`llms.txt: No links found for section "${i.title}". Please check the includeFiles/excludeFiles patterns.`);return}r.push(`## ${i.title}
`),i.description?r.push(`${i.description.replace(/\n+$/,"")}

`):r.push(`
`),i.llmstxts.forEach(c=>{r.push(` - ${y({title:c.title,description:c.description,slug:M(c.slug)})}`)}),r.push(`
`)}),r.join("")}function y({title:e,description:t,slug:n}){return`[${e}](${P(process.env.REDOCLY_PUBLIC_URL||"")}${encodeURI(n)})${t?`: ${t}`:""}
`}function S(e){if(e?.details?.path&&e?.details?.content)throw new Error('"details.path" and "details.content" are mutually exclusive. Please use only one of them.')}function M(e){return`${e}${e==="/"?"index.html.md":".md"}`}export{R as generateLLMsTxt,M as getLLMsTxtMdSlug,y as llmsTxtLink,S as validateLLMsTxtConfig};
