import s from"node:path";import{bundle as R,createConfig as I,getTotals as B}from"@redocly/openapi-core";import{CONFIG_FILE_NAME as J}from"../../../constants/common.js";import{deepMerge as L}from"../../../utils/object/deep-merge.js";import{pluralize as $}from"../../../utils/string/pluralize.js";import{getAllApiConfigsByPath as M}from"../get-api-config.js";import{injectDecoratorIntoConfig as W}from"../openapi-docs/decorators.js";import{ExternalResolver as _}from"../../fs/utils/external-ref-resolver.js";async function Y(o,{fs:n,logger:d,cache:u,getConfig:l,isPathIgnored:f}){let i;try{i=(await u.load(o,"yaml")).data}catch{return[]}if(!i?.arazzo)return d.verbose(`${o} file is not Arazzo document. Skipping`),[];const p=[],r=n.getFileInfo(o),t=await l(s.posix.dirname(o)),x=M(t?.apis,o,t.configPath),D=await f(o);for(const c of x){if(!c.output&&D)continue;const k=t.configPath?s.posix.dirname(t.configPath):".",a=c.output?s.posix.join(k,c.output):o;r&&c.output&&!await n.exists(a)&&n.addVirtualFile(a,r);const m=L(t,{rbac:void 0},c),v=s.resolve(n.cwd,t.realConfigPath||J),w=new _(n),O=await I(W(m,a,n.cwd),{configPath:v,externalRefResolver:w}),h=s.resolve(n.cwd,o),g={config:O,base:s.dirname(h),doc:{source:{absoluteRef:h},parsed:JSON.parse(JSON.stringify(i))}},{bundle:{parsed:N},problems:z,visitorsData:P}=await R({...g,dereference:!0,externalRefResolver:w}),{bundle:{parsed:S}}=await R({...g,doc:{...g.doc,parsed:JSON.parse(JSON.stringify(i))}}),V=P["markdown/markdown"]?.markdocChunks??[],e=B(z);let b=[e.errors&&`${e.errors} ${$(e.errors,"error","errors")}`,e.warnings&&`${e.warnings} ${$(e.warnings,"warning","warnings")}`,e.ignored&&`${e.ignored} ignored`].filter(Boolean).join(", ");if(e.errors){const C=z.find(F=>F.severity==="error");throw new Error(`${b} while bundling ${a} definition.

${C?.message} at ${C?.location?.[0]?.pointer}

`)}e.warnings&&d.warn(`${b} while bundling %rp definition`,a);const j=y(N,t.metadata),A=y(S,t.metadata),E={document:j,documentWithReferences:A,config:m,relativePath:a,realRelativePath:r?.realRelativePath||a,customOutputRelativeFile:c.output&&a,markdocChunks:V,isVirtual:r?.isVirtual??!1};p.push(E)}return p}async function Z(o,n){const{fs:d,cache:u,getConfig:l}=n,f=[];for(const i of await d.scan(/(\.ya?ml|\.json)$/)){if(!await l(s.posix.dirname(i.relativePath)))continue;let r;try{r=await u.load(i.relativePath,"arazzo-doc")}catch{continue}r.data?.length&&f.push(...r.data.map(t=>({...t,isVirtual:i.isVirtual||t.isVirtual,hash:r.compoundHash})))}return f}function y(o,n){return n?{...o,info:{...o.info,...n}}:o}export{Y as arazzoDocLoader,Z as arazzoDocsLoader};
