import{REDOCLY_TEAMS_RBAC as w}from"@redocly/config";import{basename as _,join as q}from"node:path";import C from"@markdoc/markdoc";import{joinSectionContent as J}from"../../../plugins/markdown/search/join-section-content.js";import{toMarkdown as G}from"../../../plugins/markdown/search/to-markdown.js";import{AstToSearchNodeTransformer as z}from"../../../plugins/markdown/search/walk-sections.js";import{createRenderTagFn as B}from"../../../plugins/markdown/search/create-render-tag-fn.js";import{canDownloadApiDefinition as v,isResourcePubliclyAccessible as V}from"../../../utils/rbac.js";import{PUBLIC_API_DEFINITIONS_FOLDER as Y}from"../../../constants/common.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as H}from"../../../../constants/common.js";import{getLlmsTxtMdPathBySlug as I}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{AiSearchIndexer as K}from"../ai-search-indexer.js";import{getLocaleFromRelativePath as Q}from"../../../fs/utils/get-locale-from-relative-path.js";import{extractDocumentSearchFacets as W}from"./search-facets.js";import{formatDocumentMetadata as X}from"../../search/utils.js";import{llmsTxtLink as M}from"../../search/llmstxt/index.js";import{replaceFileExtension as Z}from"../store-definition-bundles.js";const k=new Map,xe=({parser:s,options:c,info:n,tagOperations:r,relativePath:t,openapiContentItem:e,metadata:i,getSearchFacets:u,includeInLLMsTxt:a,excludeFromSearch:f})=>async(o,p,l,j)=>{if(f)return;const P=await o.getNavText?.()||_(o.fsPath),D=new K(s,c,o.baseSlug||o.slug),d=D.addItem(e);if(!d)return;const O=await l.getConfig(),b=Array.isArray(d.title)?d.title.join(" "):d.title;let g,m,y=k.get(t);if((e.type==="tag"||e.type==="section"&&e.infoDefinition)&&!y){const{all:A,publiclyAccessible:$}=ae(r.tagged,D,O),{all:S,publiclyAccessible:T}=ue(r.untagged,D,O);k.set(t,{taggedSearchDocuments:new Map(A),untaggedSearchDocuments:S,publiclyAccessibleTaggedSearchDocuments:new Map($),publiclyAccessibleUntaggedSearchDocuments:T})}y=k.get(t);const h="#";switch(e.type){case"operation":const A=D.getOperation(e);g=m=se({title:b,security:s.definition.security,document:d,version:d.version||n.version,headingLevel:h,operation:A});break;case"section":if(e.infoDefinition){y=k.get(t),m=await N({parser:s,info:n,staticData:p,relativePath:t,headingLevel:h,pageName:P,config:O}),m+=`
`;for(const[S,T]of y?.publiclyAccessibleTaggedSearchDocuments?.entries()||[]){if(!T.length)continue;const U=s.definition.tags?.find(L=>L.name===S);m+=x({title:U?.["x-displayName"]||S,description:U?.description,operationSearchDocuments:T,headingLevel:`${h}#`})}const $=y?.publiclyAccessibleUntaggedSearchDocuments||[];$.length&&(m+=x({title:"Other",description:void 0,operationSearchDocuments:$,headingLevel:`${h}#`})),g=await N({parser:s,info:n,staticData:p,relativePath:t,headingLevel:h,pageName:P,config:O})}else if(e.ast){const $=new C.Ast.Node("document",{},e.ast),S=Array.from(new z({ast:$,partials:{},renderTag:B(j.markdocOptions.tags),getInnerContent:G,skipConditionals:!0}).transform());m=g=J(S)}break;case"tag":m=x({title:b,description:e.description,operationSearchDocuments:y?.publiclyAccessibleTaggedSearchDocuments.get(e.name)||[],headingLevel:h}),g=x({title:b,description:e.description,operationSearchDocuments:[],headingLevel:h});break;case"rsrc":case"prompt":case"tool":m=ce({title:b,description:e.description,name:e.name,xMcpConfig:s.definition["x-mcp"],headingLevel:h}),g=m;break}return{async getLLMsTxts(){return[{title:e.name,description:e.type==="tag"?e.description:void 0,content:m||"",slug:o.slug,fsPath:o.fsPath,includeInLLMsTxt:a}]},async getSearchDocuments(){if(e.type==="operation"||e.type==="section"&&(e.infoDefinition||e.ast)||e.type==="tag"){const A=Q(o.fsPath),$=W({...d,...i},n,u);return[{title:b,description:Array.isArray(d.text)?d.text.join(" "):d.text,content:g||"",url:d.url??o.slug,fsPath:o.fsPath,locale:A,product:o.product?.name,rbacTeams:d.rbacTeams,facets:$}]}return[]}}};async function N({parser:s,info:c,staticData:n,relativePath:r,pageName:t,headingLevel:e,config:i}){const u=X(c["x-metadata"]);let a=c.title?`${e} ${c.title}

`:`${e} ${t}

`;return a+=c.description?`${c.description}

`:"",a+=c.summary?`${c.summary}

`:"",a+=c.version?`Version: ${c.version}
`:"",a+=c.license?`License: ${c.license.name}
`:"",e=`${e}#`,a+=u.length?`Metadata:
${u}
`:"",a+=`
`,a+=ee({parser:s,headingLevel:e}),a+=te({parser:s,headingLevel:e}),a+=await ne({info:c,staticData:n,relativePath:r,pageName:t,headingLevel:e,config:i}),a}function x({title:s="",description:c,operationSearchDocuments:n,headingLevel:r}){let t=`${r} ${s}

`;return c&&(t+=`${c}

`),n.length&&n.forEach(e=>{const i=Array.isArray(e.title)?e.title.join(" "):e.title;t+=`${r}# ${i}${e.deprecated?" (deprecated)":""}

`,t+=` - ${M({title:`${e.httpMethod?.toUpperCase()} ${e.httpPath}`,description:Array.isArray(e.text)?e.text.join(" "):e.text,slug:I(e.url)})}`,t+=`
`}),t}function ee({parser:s,headingLevel:c}){const{servers:n}=s.definition;if(n&&n.length){let r=`${c} Servers

`;return n.forEach(t=>{r+=t.description?`${t.description}
`:"",r+=`\`\`\`
${t.url}
\`\`\`

`,t.variables&&(r+=`Variables:
`,Object.entries(t.variables).forEach(([e,i])=>{r+=`- \`${e}\`${i.description?`: ${i.description}`:""}
`,r+=i.default?`Default: ${JSON.stringify(i.default)}
`:"",r+=i.enum?`Enum: ${i.enum.map(u=>JSON.stringify(u)).join(", ")}
`:""}),r+=`
`)}),r}return""}async function ne({info:s,staticData:c,relativePath:n,pageName:r,headingLevel:t,config:e}){const i=q(c.props?.outdir||"",Y,Z(n,".yaml")),u=e.access?.rbac,a=e.access?.requiresLogin;if(v(i,u??{},a??!1,{isAuthenticated:!1,teams:[H]})){let f=`${t} Download OpenAPI description

`;return f+=M({title:s.title||r||"OpenAPI definition",description:void 0,slug:i}),f}return""}function te({parser:s,headingLevel:c}){if(!s.definition.components?.securitySchemes)return"";let n=`${c} Security

`;const{securitySchemes:r}=s.definition.components;return Object.keys(r).forEach(t=>{const e=r[t];e&&(n+=`${c}# ${t}

`,n+=e.description?`${e.description}

`:"",e.type&&(n+=`Type: ${e.type}
`),e.openIdConnectUrl&&(n+=`OpenID Connect URL: ${e.openIdConnectUrl}
`),e.in&&(n+=`In: ${e.in}
`),e.name&&(n+=`Name: ${e.name}
`),e.scheme&&(n+=`Scheme: ${e.scheme}
`),e.bearerFormat&&(n+=`Bearer Format: ${e.bearerFormat}
`),e.flows?.implicit?.authorizationUrl&&(n+=`Authorization URL: ${e.flows.implicit?.authorizationUrl}
`),e.flows?.implicit?.scopes&&(n+=`Scopes:
`,Object.entries(e.flows?.implicit?.scopes||{}).forEach(([i,u])=>{n+=`- \`${i}\`: ${u}
`})),e.flows?.password?.tokenUrl&&(n+=`Token URL: ${e.flows.password?.tokenUrl}
`),e.flows?.password?.scopes&&(n+=`Scopes:
`,Object.entries(e.flows?.password?.scopes||{}).forEach(([i,u])=>{n+=`- \`${i}\`: ${u}
`})),n+=`
`)}),n}function se({title:s,security:c,document:n,version:r,headingLevel:t,operation:e}){const{text:i,httpMethod:u,httpPath:a,deprecated:f}=n,o=oe(n.parameters||[],`${t}#`),p=re(`${t}#`,n.parameters,e);let l=s?`${t} ${s}${f?" (deprecated)":""}

`:"";return l+=i?`${i}

`:"",l+=`Endpoint: ${u?.toUpperCase()} ${a}
`,l+=r?`Version: ${r}
`:"",l+=n.security?.length?`Security: ${n.security.join(", ")}
`:c?.length?`Security: ${c.map(j=>j.id).join(", ")}
`:"",l+=`
`,l+=o?`${o}
`:"",l+=`
`,l+=`${p.join(`
`)}`,l}function ce({title:s,name:c,xMcpConfig:n,headingLevel:r}){const t=n?.tools.find(i=>i.name===c);if(!t)return"";let e=`${r} ${s}

`;return e+=t.description?`${t.description}

`:"",e+=`${r}# Input schema:

`,e+=`\`\`\`json
${JSON.stringify(t.inputSchema,null,2)}
\`\`\`

`,t.outputSchema&&(e+=`${r}# Output schema:

`,e+=`\`\`\`json
${JSON.stringify(t.outputSchema,null,2)}
\`\`\`

`),e}function re(s,c,n){return!c&&!n||!n?.responses?[]:n?.responses.filter(t=>!t.content?.mediaTypes[0]?.schema).map(t=>`${s} ${R(`response ${t.code} fields`)}
`)}function ie(s,c,n,r){const t=JSON.stringify(s),e=r.get(t);return e?`${n}Enum: same as ${e} (${s.length} values)
`:(r.set(t,c),`${n}Enum: ${s.map(i=>JSON.stringify(i)).join(", ")}
`)}function E(s,c,n,r){const t=`${c}  `,e=s.oneOf,u=[...s.path||[],s.name].join("."),a=Array.isArray(s.description)?s.description.join(" "):s.description,f=!!e&&e.variants.length>1;let o=`${c}- \`${u}\` (${s.type}${s.required?", required":""})`;if(f&&(o+=e.discriminator?` \u2014 one of (discriminator: ${e.discriminator}):`:" \u2014 one of:"),o+=`
`,o+=a?`${t}${a.trim()}
`:"",s.enum){const p=r?`\`${u}\` in "${r}"`:`\`${u}\``;o+=ie(s.enum,p,t,n)}else s.example&&(o+=`${t}Example: ${s.example}
`);if(f)for(const p of e.variants){o+=`${c}  - ${p.title}:
`;for(const l of p.parameters)o+=E(l,`${c}    `,n,p.title)}else if(e)for(const p of e.variants[0].parameters)o+=E(p,`${c}  `,n);return o}function oe(s,c){const n={};for(const e of s){const i=`${e.place}${e.mediaType?` (${e.mediaType})`:""}`;n[i]=[...n[i]||[],e]}const r=new Map;return Object.entries(n).map(([e,i])=>{const u=i.map(a=>E(a,"  ",r));return`${c} ${R(e)}:

${u.join(`
`)}`}).join(`
`)}function ae(s,c,n){const r=[],t=[];return s.forEach((e,i)=>{const u=[],a=[];e.forEach(f=>{const o=c.addItem(f);o&&(u.push(o),F({[w]:f[w],slug:o.url},n)&&a.push(o))}),r.push([i,u]),t.push([i,a])}),{all:r,publiclyAccessible:t}}function ue(s,c,n){const r=[],t=[];return s.forEach(e=>{const i=c.addItem(e);i&&(r.push(i),F({[w]:e[w],slug:i.url},n)&&t.push(i))}),{all:r,publiclyAccessible:t}}function R(s){return s.charAt(0).toUpperCase()+s.slice(1)}function F(s,c){return c.access?.requiresLogin?!0:V(s,c)}export{xe as getAiDocumentsStore};
