import*as d from"path";import{convertSwagger2OpenAPI as Y}from"@redocly/openapi-docs/lib/utils/convertSwagger2OpenAPI.js";import{bundle as Z,createConfig as oo,getTotals as no,resolvePlugins as eo}from"@redocly/openapi-core";import{normalizeOptions as to,OpenAPIParser as io,buildContentItems as ro}from"@redocly/openapi-docs";import{combineUrls as x}from"@redocly/theme/core/utils";import{CONFIG_FILE_NAME as F}from"../../../constants/common.js";import{PUBLIC_API_DEFINITIONS_FOLDER as R}from"../../constants/common.js";import{MAX_BUNDLING_ERRORS_TO_PRINT as ao}from"../../constants/plugins/openapi-docs.js";import{unique as so}from"../../../utils/array/unique.js";import{deepMerge as N}from"../../../utils/object/deep-merge.js";import{pluralize as v}from"../../../utils/string/pluralize.js";import{replaceEnvVariablesDeep as co}from"../../utils/envs/replace-env-variables-deep.js";import{logger as L}from"../../tools/notifiers/logger.js";import{reporter as b}from"../../tools/notifiers/reporter.js";import{injectDecoratorIntoConfig as fo}from"./decorators.js";import{getAllApiConfigsByPath as lo}from"../get-api-config.js";import{normalizeFeedbackOptions as po}from"./utils.js";import{replaceFileExtension as M}from"./store-definition-bundles.js";import{ExternalResolver as uo}from"../../fs/utils/external-ref-resolver.js";async function Ao(o,u){const{fs:i,cache:O,getConfig:g,isPathIgnored:m}=u;if(d.posix.basename(o)===F)return[];let a;try{a=(await O.load(o,"yaml")).data}catch{return[]}if(!a?.openapi&&!a?.swagger)return L.verbose(`${o} file is not definition. Skipping`),[];const p=await g("."),s=await i.getFileInfo(o),n=await g(d.posix.dirname(o)),T=lo(n?.apis,o,n.configPath),E=[],U=await m(o);for(const c of T){if(!c.output&&U)continue;const V=N({decorators:p.decorators},n,{rbac:void 0},c),{resolvedObj:r}=co(V);if(r.decorators&&typeof r.decorators!="object"){b.panicOnBuildContentError(`'decorators' must be an object at redocly.yaml, got '${typeof r.decorators}'`);continue}if(r.plugins&&!Array.isArray(r.plugins)){b.panicOnBuildContentError(`'plugins' must be an array at redocly.yaml, got '${typeof r.plugins}'`);continue}const z=n.configPath?d.posix.dirname(n.configPath):".",e=c.output?d.posix.join(z,c.output):o;if(await m(e))continue;s&&c.output&&!await i.exists(e)&&i.addVirtualFile(e,s);const G=d.resolve(i.cwd,n.realConfigPath||F),S=new uo(i),C=await oo(fo(r,e),{configPath:G,externalRefResolver:S});p.plugins&&p.configPath!==n.configPath&&(C.plugins=so([...C.plugins||[],...await eo(p.plugins,i.cwd)],f=>f.id));const D=d.resolve(i.cwd,o),J={config:C,base:d.dirname(D),doc:{source:{absoluteRef:D},parsed:JSON.parse(JSON.stringify(a))},externalRefResolver:S},{bundle:{parsed:y},problems:_,visitorsData:q}=await Z(J),H=q["markdown/markdown"]?.markdocChunks??[],t=no(_);let j=[t.errors&&`${t.errors} ${v(t.errors,"error","errors")}`,t.warnings&&`${t.warnings} ${v(t.warnings,"warning","warnings")}`,t.ignored&&`${t.ignored} ignored`].filter(Boolean).join(", ");if(t.errors){const f=_.filter(l=>l.severity==="error");let $=`${j} while bundling ${e} definition:
`;const P=Math.min(f.length,ao);for(let l=0;l<P;l++){const B=f[l];$+=`${B.message} at ${B.location?.[0]?.pointer??""}
`}if(f.length>P){const l=f.length-P;$+=`... and ${l} more ${v(l,"error","errors")}`}b.panicOnBuild($)}t.warnings&&L.warn(`${j} while bundling %rp definition`,e);const w=mo(y.swagger!==void 0?await Y(y):y,n.metadata),h=N(p.openapi||{},n.openapi||{},c.openapi||c?.theme?.openapi||{});h.showSchemaCatalogLinks&&(w["x-schema-catalog-link"]=x(R,e));const X=w["x-feedback"]||h.feedback||n.feedback,A={...h,feedback:po(X),hideSidebar:!0,disableRouter:!0,mockServer:r?.mockServer||p?.mockServer,downloadUrls:h.downloadUrls||[{url:x(R,`${M(e,".json")}?download`)},{url:x(R,`${M(e,".yaml")}?download`)}]},I=to(A);let k;try{k=new io(w,void 0,I)}catch(f){b.panicOnBuild(f);continue}const{contentItems:K,flatItems:Q}=ro(k,I),W={definition:w,config:r,relativePath:e,realRelativePath:s?.realRelativePath||e,customOutputRelativeFile:c.output&&e,markdocChunks:H,contentItems:K,flatItems:Q,options:I,rawOptions:A,parser:k};E.push(W)}return E}async function Bo(o,u){const{fs:i,cache:O,getConfig:g}=u,m=[];for(const a of await i.scan(/(\.ya?ml|\.json)$/)){if(!await g(d.posix.dirname(a.relativePath)))continue;const s=await O.load(a.relativePath,"load-oas");s.data&&s.data.length&&m.push(...s.data.map(n=>({...n,isVirtual:a.isVirtual||n.isVirtual,hash:s.compoundHash})))}return m}function mo(o,u){return u?{...o,info:{...o.info,"x-metadata":{...o.info["x-metadata"],...u}}}:o}export{Ao as definitionLoader,Bo as definitionsLoader};
