import{join as c}from"path";import{transformSync as l}from"esbuild";import{REDOCLY_ROUTE_RBAC as p}from"@redocly/config";import{removeTrailingSlash as d}from"../../../utils/url/remove-trailing-slash.js";import{removeLeadingSlash as m}from"../../../utils/url/remove-leading-slash.js";import{logger as u}from"../../tools/notifiers/logger.js";import{envConfig as g}from"../../config/env-config.js";import{USER_DEFINED_API_FUNCTIONS_COUNTER_KEY as h}from"../../../server/store.js";import{parseRouteFsPathForHono as F}from"./helpers/parse-route-fs-path-for-hono.js";import{telemetryTraceStep as A}from"../../../cli/telemetry/helpers/trace-step.js";const f="api-functions",P=/\bexport\s+default\b|\bexport\s*\{[^}]*\b(?:default\s*[,}]|\w+\s+as\s+default\b)/;async function E(t,o){let i;try{i=await o.fs.read(t),l(i,{loader:t.endsWith(".js")?"js":"ts"})}catch(e){const a=e instanceof Error?e.message:String(e);return u.warn(`Skipping API function ${t} because it cannot be parsed: ${a}`),!1}if(!P.test(i)){const e=`API function ${t} does not export a default function. Add 'export default function (request, context) { ... }' to define an API function.`;return g.isDevelopMode?(u.warn(e),!0):(u.warn(`Skipping ${e}`),!1)}return!0}function R(t){return m(d(t))}function I(t){return`^${R(t)}`}function _(t){const o=t.map(I);return o.push(".*@api"),new RegExp(`(${o.join("|")})/.*.(ts|js)$`)}async function H(){return{id:"ApiFunctions",requiredEntitlements:["apiFunctions"],async processContent(t,o){await A("build.plugin.api_functions",async i=>{const e=await o.getConfig();i?.setAttribute("config",JSON.stringify(e.apiFunctions||{}));const a=_(e.apiFunctions?.folders||[]),s=[];for(const n of o.fs.scan(a)){if(n.isVirtual)continue;const r=F(n.relativePath);r&&await E(n.relativePath,o)&&s.push({requestHandlerId:`${f}:${r.handler}`,fullPath:c(t.contentDir,r.handler),slug:r.path,httpMethod:r.method,fsPath:n.relativePath})}t.clearRequestHandlersByPrefix(`${f}:`);for(const n of s)t.createRequestHandler(n.requestHandlerId,n.fullPath),t.addApiRoute({requestHandlerId:n.requestHandlerId,slug:n.slug,fsPath:n.fsPath,httpMethod:n.httpMethod,[p]:{fsPath:n.fsPath,slug:n.slug}});i?.setAttribute("definedApiFunctions",String(s.length)),t.setGlobalConfig({[h]:s.length})})}}}export{f as API_FUNCTIONS_REQUEST_HANDLER_ID,H as apiFunctionsPlugin};
