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