import*as p from"workerpool";import{withPathPrefix as f}from"@redocly/theme/core/utils";import{envConfig as l}from"../config/env-config.js";import{telemetry as a}from"../telemetry/index.js";import{TimeoutExceededError as E}from"./errors/timeout-exceeded.js";import{serializeRequest as _}from"./helpers/serialize-request.js";import{apiRoutesWorkers as A,API_ROUTES_WORKER_KEY as T}from"../workers/api-routes-worker-pool.js";import{API_FUNCTIONS_REQUEST_HANDLER_ID as u}from"../plugins/api-functions/index.js";const g=1e4,h=15;async function U(e,r,t){a.initialize();const s=r.get("auth"),i=await t.resolveRouteStaticData(e)||{},n=f(e.slug);try{const{status:o,headers:d,body:c}=await A.exec(T,[{serverOutDir:t.serverOutDir,slug:n,requestHandlerId:e.requestHandlerId,maxResponseSizeMB:h,ctxData:{user:{teams:s.teams,email:s.claims.email,claims:s.claims,idpAccessToken:s.idpAccessToken,idpId:s.claims.idpId,isAuthenticated:s.isAuthenticated},config:t.config,outdir:t.outdir,baseUrl:new URL(r.req.url).origin},staticData:{...i,props:{...i.props,routeSlug:n,outdir:t.outdir}},req:await _(r.req.raw),sqldRemoteDatabaseUrl:l.SQLD_REMOTE_DATABASE_URL,sqldRemoteDatabaseAuthToken:l.SQLD_REMOTE_DATABASE_AUTH_TOKEN}],{timeout:g});R({requestHandlerId:e.requestHandlerId,status:o,ctx:r});const m=c.data?Buffer.from(c.data):null;return new Response(m,{status:o,headers:d})}catch(o){throw M({requestHandlerId:e.requestHandlerId,error:o}),o instanceof p.Promise.TimeoutError?new E("Timeout exceeded"):o}}function R({requestHandlerId:e,status:r,ctx:t}){e.startsWith(u)?a.sendApiFunctionCalledMessage([{object:"api_function",error:null,handler:e,status:r}]):a.sendMockServerCalledMessage([{object:"mock_server",error:null,handler:e,headers:{"user-agent":t.req.header("user-agent")??null},status:r}])}function M({requestHandlerId:e,error:r}){const t={handler:e,message:r?.message??null,stack:r?.stack??null};e.startsWith(u)?a.sendApiFunctionErrorMessage([{object:"api_function",...t}]):a.sendMockServerErrorMessage([{object:"mock_server",...t}])}export{U as runApiRoutesWorker,M as sendTelemetryErrorMessage};
