import e from"node:path";import{ASYNC_API_DOCS_TEMPLATE_ID as d,GRAPHQL_SPEC_SLUG as F,GRAPHQL_TEMPLATE_ID as U,OPENAPI_DOCS_TEMPLATE_ID as C}from"../../../../constants/common.js";import{isLocalLink as y}from"../../../../utils/path/is-local-link.js";import{normalizeRouteSlug as u}from"../../../../utils/path/normalize-route-slug.js";import{PUBLIC_API_DEFINITIONS_FOLDER as M,DEPRECATED_PUBLIC_API_DEFINITIONS_FOLDER as N}from"../../../constants/common.js";import{getInnerText as W}from"../markdoc/helpers/get-inner-text.js";import{getNodeAttribute as B}from"../markdoc/helpers/get-node-attribute.js";import{setNodeAttributeValue as m}from"../markdoc/helpers/set-node-attribute-value.js";import{MdResolveError as I}from"./md-resolve-error.js";import{getLinkOriginalAttrName as j}from"./utils.js";import{isOpenApiURL as G}from"../../openapi-docs/is-openapi-doc.js";import{parseBaseName as $}from"../../utils.js";import{isMarkdownPage as H}from"../is-markdown-page.js";import{copyStaticFile as V}from"../../../utils/fs.js";const b=i=>[M,N,F].some(r=>i.startsWith(r));async function at(i,r,n,{actions:E,context:c}){const{contentDir:k,outdir:D,getRouteByFsPath:_,slugHasRouteOrRedirect:h}=E,w=j(r),s=i[w]||B(i,r);if(i[w]=s,!y(s)||b(s))return;const[v,t="",g,L]=/^([^\?#]+)?([^#]+)?(.+)?/.exec(s)||[],f=i.type==="image"?"IMAGE":"LINK",p=String(i.attributes.title||i.attributes.alt||W([i])||""),{isOpenapiDetected:O,isOpenapiValid:R}=await G(t,n,E,c);if(O&&!R)throw new I(`OpenAPI route ${s} does not exist`,{rawLink:s,link:t,title:p,brokenLinkType:f});if(e.extname(t)===""){if(t.startsWith("/")){if(!h(u(t)))throw new I(`Route ${t} does not exist`,{rawLink:s,link:t,title:p,brokenLinkType:f});m(i,r,t+(g||"")+(L||""))}if(!s.startsWith("#")&&!t.startsWith("/")&&H(n)){const o=_(n)?.slug;if(!o)return;const{isIndexFile:P}=$(n),A=P?u(e.posix.join(o,t)):u(e.posix.join(o,"../",t));if(!h(u(A)))throw new I(`Route ${t} does not exist`,{rawLink:s,link:A,title:p,brokenLinkType:f});m(i,r,A+(g||"")+(L||""))}return}const a=t.startsWith("/")?t.substring(1):e.posix.join(e.posix.dirname(n),decodeURI(t)),S=t.startsWith("/")?e.posix.join("static",t.substring(1)):"",x=await c.fs.exists(a),T=await c.fs.exists(S),l=_(a);if(!x&&!l&&!T)throw m(i,r,"#"),new I(`File ${a} does not exist`,{rawLink:s,link:a,title:p,brokenLinkType:f});if(l){const o=[C,U,d].includes(l.templateId);m(i,r,(o?l.baseSlug:l.slug)+(L||""))}else if(x){const o=await c.fs.getFileInfo(a);if(!o||o.isVirtual)return;const P=V(k,o.realRelativePath,D);m(i,r,P)}}export{at as resolveLink};
