import*as g from"workerpool";import{MOCK_SERVER_REQUEST_HANDLER_ID as d}from"@redocly/portal-plugin-mock-server";import{withPathPrefix as S}from"@redocly/theme/core/utils";import{logger as u}from"../tools/notifiers/logger.js";import{telemetry as r}from"../telemetry/index.js";import{TimeoutExceededError as f}from"./errors/timeout-exceeded.js";import{serializeRequest as y}from"./helpers/serialize-request.js";import{apiRoutesWorkers as R,API_ROUTES_WORKER_KEY as T}from"../workers/api-routes-worker-pool.js";import{API_FUNCTIONS_REQUEST_HANDLER_ID as i}from"../plugins/api-functions/index.js";const I=1e4,_=10,h={[i]:r.sendApiFunctionCalledMessage.bind(r),[d]:r.sendMockServerCalledMessage.bind(r)},M={[i]:r.sendApiFunctionErrorMessage.bind(r),[d]:r.sendMockServerErrorMessage.bind(r)};async function v(e,o,s){r.initialize();const t=o.get("auth"),n=await s.resolveRouteStaticData(e)||{},c=S(e.slug);try{const{status:a,headers:m,body:l,loggerStickyState:p}=await R.exec(T,[{serverOutDir:s.serverOutDir,slug:c,requestHandlerId:e.requestHandlerId,maxResponseSizeMB:_,ctxData:{user:{teams:t.teams,email:t.claims.email,claims:t.claims,idpAccessToken:t.idpAccessToken,idpId:t.claims.idpId,isAuthenticated:t.isAuthenticated},config:s.config},staticData:{...n,props:{...n.props,routeSlug:c,outdir:s.outdir}},req:await y(o.req.raw),loggerStickyState:u.getStickyState()}],{timeout:I});u.setStickyState(p),k({requestHandlerId:e.requestHandlerId,body:l,headers:m,status:a});const E=l.data?Buffer.from(l.data):null;return new Response(E,{status:a,headers:m})}catch(a){throw A({requestHandlerId:e.requestHandlerId,error:a}),a instanceof g.Promise.TimeoutError?new f("Timeout exceeded"):a}}function k({requestHandlerId:e,body:o,headers:s,status:t}){const n=e.startsWith(i)?i:d,c=h[n];c({error:null,handler:e,body:o,headers:s,status:t})}function A({requestHandlerId:e,error:o}){const s=e.startsWith(i)?i:d,t=M[s];t({handler:e,message:o?.message,stack:o?.stack??null})}export{v as runApiRoutesWorker,A as sendTelemetryErrorMessage};
