import u from"path";import{REDOCLY_ROUTE_RBAC as E,REDOCLY_TEAMS_RBAC as w}from"@redocly/config";import{withoutPathPrefix as M,withPathPrefix as q}from"@redocly/theme/core/utils";import{CACHE_CONTROL_NO_CACHE_HEADER_VALUE as _,DEFAULT_IMMUTABLE_CACHE_MAX_AGE as O}from"../../constants/common.js";import{removeTrailingSlash as F}from"../../../utils/url/remove-trailing-slash.js";import{findInIterable as H}from"../../../utils/collection/find-in-iterable.js";import{sanitizeRedirectPathname as v}from"../../../utils/url/sanitize-redirect-pathname.js";import{sanitizePath as z}from"../../../utils/path/sanitize-path.js";import{normalizeRouteSlug as B}from"../../../utils/path/normalize-route-slug.js";import{isPathInFolder as G}from"../../../utils/path/is-path-in-folder.js";import{processRedirects as N}from"./helpers/process-redirects.js";import{renderPage as Y,getServerProps as $}from"../../ssr/index.js";import{canAccessAsset as k,canAccessResource as L}from"../../utils/rbac.js";import{handleErrorPageRender as y,handleUnauthorized as P,handleUnauthorizedAsset as U}from"../utils.js";import{DEFAULT_MAX_AGE_FOR_MIME_TYPE as V,MIME_TYPES as W}from"../mime-types.js";import{fileExistsAsync as X}from"../../utils/index.js";import{getRedirectRoute as Z}from"../utils/legacy-openapi-redirects.js";import{telemetry as j}from"../../../cli/telemetry/index.js";import{telemetry as J}from"../../telemetry/index.js";function Ae(e,I,T){return async o=>{const h=o.get("logger"),l=o.req,i=new URL(l.url),n=M(z(decodeURIComponent(i.pathname))),R=u.parse(n).ext===".md",m=B(n),r=(l.method==="GET"||l.method==="HEAD")&&!R?e.getRouteBySlug(m,{followRedirect:!1})||H(e.routesBySlug?.values(),t=>t.hasClientRoutes&&(n===t.slug||n.startsWith(t.slug+"/"))):void 0,A=e.getRedirect(m);if(A){const t=N({redirect:A,reqUrlSearch:i.search});return J.sendRedirectMessage({from:m,templateId:t.type.toString()}),o.newResponse(null,t.type,{Location:t.location})}const d=process.env.NODE_ENV==="production"?301:302;if(r?.metadata?.type==="openapi"){const t=Z(i.pathname);if(t)return h.info("Legacy OpenAPI docs redirect from "+i.pathname),o.newResponse(null,d,{Location:encodeURI(t)});if(i.pathname.match(/[A-Z]/))return h.warn("Redirect to lowercase route to avoid 404 error"),o.newResponse(null,d,{Location:encodeURI(i.pathname.toLowerCase())})}if(n.endsWith("/")&&n!=="/"){const t=v(new URL(m||"/",o.req.url).pathname);return o.newResponse(null,d,{Location:encodeURI(q((t==="/"?"/":F(t))+i.search))})}const{isAuthenticated:c,teams:f,claims:{email:p}}=o.get("auth");if(r){if(!L(r,{isAuthenticated:c,email:p,teams:f},e.config.rbac,e.config.requiresLogin))return c?y(o,e,{slug:r.slug,[w]:r[w],[E]:r[E]},403):P(o,e,r.slug);const t=await I(r),s=await $(r,o,t,e),{html:b,statusCode:D}=await Y(r,s,o,e,j);return o.html(b,D,{"Cache-Control":_})}const a=u.resolve(e.outdir,"."+n);if(!G(a,e.outdir))return U(o);if(R){const t=n==="index.html.md"?"/":n.replace(/\.md$/,""),s=e.getRouteBySlug(t,{followRedirect:!1});if(s&&!L(s,{isAuthenticated:c,email:p,teams:f},e.config.rbac,e.config.requiresLogin))return P(o,e,n)}if(!k(n,e.getGlobalConfig("rbac"),e.getGlobalConfig("requiresLogin"),e.getGlobalConfig("directoryPaths"),{isAuthenticated:c,email:p,teams:f}))return U(o);const C=W[u.extname(a)]||"text/plain",g=a.match(/assets\/.*\.[a-f0-9]{8,}\..+/)||a.match(/runtime\/chunks\/.*/)?O:V[C],S=g?{"Cache-Control":`public, max-age=${g}, immutable`,Expires:new Date(Date.now()+g*1e3).toUTCString()}:{"Cache-Control":_};if(await X(a)){const t=l.query("download")!=null,s=await T(a);return o.newResponse(s,200,{"Content-Type":C,"Access-Control-Allow-Origin":"*",...S,...t&&{"Content-Disposition":`attachment; filename="${u.basename(a)}"`}})}else return y(o,e,{slug:m},404)}}export{Ae as dynamicRouteHandler};
