import{Hono as f}from"hono";import{TrieRouter as m}from"hono/router/trie-router";import{Logger as w}from"../tools/notifiers/logger.js";import{envConfig as l}from"../config/env-config.js";import{importApiRoutesHandler as D}from"./import-api-routes-handlers.js";import{getBodyWithSizeCheck as q}from"./helpers/get-body-with-size-check.js";import{setupLogger as R}from"./helpers/setup-logger.js";import{telemetry as d}from"../telemetry/index.js";import{KvService as g}from"../persistence/kv/services/kv-service.js";import{enhanceContext as h}from"./helpers/enhance-context.js";const u=new w,y=8e3,A=100;async function T(e){d.initialize(),R(u,e.requestHandlerId);const n=new f({router:new m}),s=await H(e),o=async()=>g.getInstance({baseDbDir:e.serverOutDir,sqldRemoteDatabaseUrl:e.sqldRemoteDatabaseUrl,sqldRemoteDatabaseAuthToken:e.sqldRemoteDatabaseAuthToken});n.all(e.slug,async t=>{if(typeof s!="function"){const a=`API function "${e.slug}" does not export a default function. Add 'export default function (request, context) { ... }' to the file.`;return u.error(`[${e.requestHandlerId}] ${a}`),l.isDevelopMode?t.text(a,500):t.newResponse(null,404)}const r=await s(t.req.raw,h({honoCtx:t,ctx:e.ctxData,telemetry:d,getKv:o}),e.staticData);return r instanceof Response?r:typeof r=="string"?t.text(r):t.json(r)}),n.onError((t,r)=>{if(u.error(`[${e.requestHandlerId}] ${t.message} ${t.stack}`),t instanceof SyntaxError)return r.text(t.message,500);throw t});const i=await n.request(e.req.url,e.req),c=await q(i,e.maxResponseSizeMB);return{status:i.status,headers:Object.fromEntries(i.headers.entries()),body:c}}async function p(e){const n=Date.now()+(l.isDevelopMode?y:0);let s;for(;;){try{const{requestHandlers:o}=await D(e.serverOutDir),i=o?.[e.requestHandlerId];if(typeof i=="function")return i;s=new Error(`Request handler "${e.requestHandlerId}" is not available yet.`)}catch(o){s=o}if(Date.now()>=n)throw s;await new Promise(o=>setTimeout(o,A))}}async function H(e){return(await(await p(e))()).default}export{T as executeApiRoute};
