import Z from"node:path";import{simplifyAstStructure as ee}from"@redocly/openapi-docs";import{REDOCLY_TEAMS_RBAC as _}from"@redocly/config";import{OPENAPI_DOCS_TEMPLATE_ID as G,PUBLIC_RBAC_SCOPE_ITEM as $}from"../../../constants/common.js";import{DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as te,PUBLIC_API_DEFINITIONS_FOLDER as oe}from"../../constants/common.js";import{OPENAPI_CUSTOM_FIELDS_SERVER_PROPS_GETTER_ID as ae,OPENAPI_SHARED_DATA_PREFIX as H}from"../../constants/plugins/openapi-docs.js";import{slash as re}from"../../../utils/path/slash.js";import{isDevelopMode as U}from"../../utils/envs/is-develop-mode.js";import{searchResolver as se}from"./search/search-resolver.js";import{convertOpenAPIDocs2Sidebar as ie,shouldAddRoute as ne}from"./utils.js";import{getTemplatePath as b}from"./get-template-path.js";import{storeDefinitionBundles as pe}from"./store-definition-bundles.js";import{definitionLoader as ce,definitionsLoader as de}from"./load-definition.js";import{getAiDocumentsStore as le}from"./search/get-ai-search-documents.js";import{fromCurrentDir as ue}from"../../utils/paths.js";import{telemetryTraceStep as me}from"../../../cli/telemetry/helpers/trace-step.js";const L="openapi-spec-download";async function Te(V){let M=[],E={};return{id:"openapi",requiredEntitlements:["openapi"],loaders:{"load-oas-docs":de,"load-oas":ce},processContent:async(e,i)=>{await me("build.plugin.openapi_docs",async d=>{e.createRequestHandler(L,ue(import.meta.url,"./spec-download.api.js")),e.addApiRoute({slug:oe+"/*",requestHandlerId:L,httpMethod:"all",[_]:$,getStaticData:async()=>({props:{}})}),e.addApiRoute({slug:te+"/*",requestHandlerId:L,httpMethod:"all",[_]:$,getStaticData:async()=>({props:{}})});const s=e.createTemplate(G,b("./template/OpenAPIDocs.js")),n=e.registerServerPropsGetter(G,b("./get-server-props.js")),g=e.registerServerPropsGetter(ae,b("./get-server-props-custom-fields.js")),l=await i.getConfig();d?.setAttribute("config",JSON.stringify(l.openapi||{}));const I=l.rules?.["custom-fields-schema"];E={};const u=await e.loadOpenApiDefinitions(i);M=u.map(({markdocChunks:m,relativePath:f,customOutputRelativeFile:r,isVirtual:a,realRelativePath:p})=>({chunks:m,relativePath:f,realRelativePath:p,isVirtual:r!=null||a})),pe(u,e.outdir);const P={};for(const m of u||[]){const{definition:f,config:r,relativePath:a,customOutputRelativeFile:p,contentItems:S,flatItems:D,parser:v,options:w,rawOptions:q,hash:J}=m,k=p||a,o=[],x={},{definition:Q}=v||{},{info:c}=Q||{},O=c?.["x-metadata"],B=!!r.openapi?.excludeFromSearch||!!r.theme?.openapi?.excludeFromSearch||!!l.openapi?.excludeFromSearch||!!l.theme?.openapi?.excludeFromSearch,N={title:c?.title,description:c?.description,summary:c?.summary,...r.metadata,...O},h={untagged:[],tagged:new Map};for(const t of D){const{id:C,href:A,operationDefinition:y}=t;if(y){const{tags:R}=y;if(R)for(const T of R)h.tagged.has(T)||h.tagged.set(T,[]),h.tagged.get(T)?.push(t);else h.untagged.push(t);U()&&(x[`#${y.pointer}`]=t.href)}if(!ne({item:t}))continue;const F=t,Y=F.type==="section"&&!!F.infoDefinition,z=A.split("#")[0]+"/",K=t?.operationDefinition?.[_];o.push({slugSuffix:z,fsPath:k,httpVerb:t?.httpVerb||"",path:a,templateId:s,[_]:K||r.rbac,getAiDocumentsStore:le({parser:v,options:w,info:c,tagOperations:h,openapiContentItem:F,metadata:N,relativePath:a,getSearchFacets:e.getSearchFacets,includeInLLMsTxt:Y,excludeFromSearch:B}),getStaticData:async R=>({props:{dynamicMarkdocComponents:["openapi"],baseSlug:R.baseSlug,seo:t["x-metadata"]?.seo||{title:t.name,description:t.description},itemId:C,disableAutoScroll:!0}})})}o[0]={...o[0],metadata:{type:"openapi",...N},hasClientRoutes:!0,getSidebar:(t,C)=>{const A=[];return ie({contentItems:S,sidebarItems:A,routeSlug:t.slug,navItem:C}),A},getNavText:()=>c?.title,getSearchDocuments:se(v,w,D,e.getSearchFacets,e.setSearchFacets,B)},O?.apiId&&(P[O.apiId]={slug:o[0]?.slug||""});const W=o[0];o[0]=o[o.length-1],o[o.length-1]=W;for(const t of o)e.addRoute({...t,serverPropsGetterIds:I?[n,g]:[n]});const X=U()?a:void 0,j=`${H}${a}`;E[j]={fsPath:k,definition:f,options:q,sourcePath:X,routesMapping:x,hash:J};for(const t of o)e.addRoute({...t,sharedData:[{id:j,key:"openAPIDocsStore"}],serverPropsGetterIds:I?[n,g]:[n]})}e.setGlobalData({apiProducts:P})})},afterRoutesCreated:async(e,i)=>{for(const{chunks:d,relativePath:s,isVirtual:n,realRelativePath:g}of M)await i.cache.load(s,{loader:async function(){await i.cache.load(g,"load-oas");for(const{node:I,markdown:u,pointer:P,key:m,relativePath:f}of d){const[r,...a]=P.split("#"),p=a.join("#"),S=re(Z.relative(V.contentDir,r)),{ast:D}=await e.parseMarkdoc({content:u,relativePath:S,isVirtual:n,cacheId:S+(p?"#"+p:"")},i,{sharedDataIds:[`${H}${f}`]});I[`x-parsed-md-${m}`]={result:ee(D)}}},name:"openapi-markdoc-inline-parser"});for(const[d,s]of Object.entries(E))await e.createSharedData(d,{...s,baseSlug:e.getRouteByFsPath(s.fsPath)?.baseSlug},s.hash)}}}export{Te as openAPIDocsPlugin};
