UNPKG

lacis

Version:

Zero-dependency TypeScript web framework

26 lines (17 loc) 39.8 kB
import Q,{join}from'path';import Je from'fs/promises';import {existsSync}from'fs';import J from'cluster';import Te,{IncomingMessage,ServerResponse}from'http';import pt from'https';import*as x from'os';import x__default from'os';import {EventEmitter}from'events';import {Socket}from'net';var N={beforeRequest:[],afterRequest:[],onError:[]},z={onNotFound:[],onShutdown:[]},$=new Map,L=new Map;function ge(t,e){return N[t].push(e),{remove:()=>{let r=N[t].indexOf(e);r!==-1&&N[t].splice(r,1);}}}function xe(t,e,r,n){return t.has(e)||t.set(e,{beforeRequest:[],afterRequest:[],onError:[]}),t.get(e)[r].push(n),{remove:()=>{let o=t.get(e);if(!o)return;let s=o[r].indexOf(n);s!==-1&&o[r].splice(s,1);}}}function Ge(t,e,r){return xe($,t==="/"?"/":t.replace(/\/+$/,""),e,r)}function Ye(t,e,r){return xe(L,t==="/"?"/":t.replace(/\/+$/,""),e,r)}function re(t,e,r){let n=t.get(e);n&&(r.beforeRequest.push(...n.beforeRequest),r.afterRequest.push(...n.afterRequest),r.onError.push(...n.onError));}function Qe(t){let e=t==="/"?"/":t.replace(/\/+$/,""),r=e.split("/").filter(Boolean),n={beforeRequest:[...N.beforeRequest],afterRequest:[...N.afterRequest],onError:[...N.onError]};re($,"/",n),e==="/"&&re(L,"/",n);let o="";for(let s of r)o+="/"+s,re($,o,n),o===e&&re(L,o,n);return n}function H(){return N.beforeRequest.length>0||N.afterRequest.length>0||N.onError.length>0||$.size>0||L.size>0}async function k(t,e,r,n){let o=e.url?.split("?")[0]||"/",s=Qe(o);if(s[t].length===0)return true;for(let i of s[t])try{if(await i(e,r,n)===!1)return !1}catch(l){if(t!=="onError")try{for(let a of s.onError)await a(e,r,{error:l,phase:t});}catch(a){console.error("Error in error handler:",a);}return false}return true}function Ke(t,e,r){e.has(r)||e.set(r,{beforeRequest:[],afterRequest:[],onError:[]});let n=e.get(r);for(let o of ["beforeRequest","afterRequest","onError"])if(t[o]){let s=Array.isArray(t[o])?t[o]:[t[o]];n[o].push(...s);}}async function ye(t){$.clear(),L.clear();async function e(r,n=""){try{let o=await Je.readdir(r,{withFileTypes:!0});for(let[s,i]of [["+middleware.global.ts",$],["+middleware.global.js",$],["+middleware.ts",L],["+middleware.js",L]]){let l=o.find(a=>a.name===s);if(l)try{let c=await import(`${Q.resolve(Q.join(r,l.name))}?update=${Date.now()}`);Ke(c,i,n);}catch(a){console.error(`Error loading middleware for ${n}:`,a);}}for(let s of o)s.isDirectory()&&await e(Q.join(r,s.name),`${n==="/"?"":n}/${s.name}`);}catch(o){console.error(`Error scanning directory ${r}:`,o);}}await e(t,"/");}function kt(){return $}function Y(t){if(t?.length)for(let e of t){let r=e.type==="cascade"?Ge:Ye;for(let n of ["beforeRequest","afterRequest","onError"]){let o=e.module[n];if(!o)continue;let s=Array.isArray(o)?o:[o];for(let i of s)r(e.path,n,i);}}}function U(t){t&&(t.onNotFound&&z.onNotFound.push(t.onNotFound),t.onShutdown&&z.onShutdown.push(t.onShutdown));}function j(){return z.onNotFound.length>0}async function F(t,e){for(let r of z.onNotFound)if(await r(t,e),e.headersSent)return}async function Ot(){for(let t of z.onShutdown)try{await t();}catch(e){console.error("Error in onShutdown hook:",e);}}function xt(){N.beforeRequest=[],N.afterRequest=[],N.onError=[],$.clear(),L.clear(),z.onNotFound=[],z.onShutdown=[];}function D(t){if(t)for(let e of ["beforeRequest","afterRequest","onError"]){let r=t[e];if(r){let n=Array.isArray(r)?r:[r];for(let o of n)ge(e,o);}}}function Ze(t,e){return !e||e==="*"?true:typeof e=="string"?t===e:Array.isArray(e)?e.includes(t):e instanceof RegExp?e.test(t):typeof e=="function"?e(t):false}function Xe(t){let e=(t.methods??["GET","POST","PUT","DELETE","PATCH","OPTIONS"]).join(", "),r=(t.allowedHeaders??["Content-Type","Authorization"]).join(", "),n=t.exposedHeaders?.join(", "),o=t.maxAge!=null?String(t.maxAge):null,s=!t.origin||t.origin==="*";return async(i,l)=>{let a=i.getHeader("origin");if(!a||!Ze(a,t.origin))return;let c=s&&!t.credentials;if(l.setHeader("Access-Control-Allow-Origin",c?"*":a),c||l.setHeader("Vary","Origin"),t.credentials&&l.setHeader("Access-Control-Allow-Credentials","true"),n&&l.setHeader("Access-Control-Expose-Headers",n),i.method==="OPTIONS")return l.setHeader("Access-Control-Allow-Methods",e),l.setHeader("Access-Control-Allow-Headers",r),o&&l.setHeader("Access-Control-Max-Age",o),l.status(204),l.end(),false}}function B(t){t&&ge("beforeRequest",Xe(t));}function g(...t){J.isPrimary&&console.log(...t);}function nt(t){let e=t.match(/^\[(\w+)(\??)]/);return e?{name:e[1],isParam:true,isOptional:e[2]==="?"}:{name:t,isParam:false,isOptional:false}}var ot=1e3,at=100,we=class{rootNode;cachedRoutes;routeCount;lastLoaded;verbose;constructor(){this.rootNode=this.createNode(),this.cachedRoutes=new Map,this.routeCount=0,this.lastLoaded=0,this.verbose=false;}createNode(){return {handlers:Object.create(null),staticChildren:new Map,paramChild:null,wildcardHandler:null,isEndpoint:false}}addRoute(e,r,n){let o=r.split("/").filter(Boolean),s=this.rootNode;for(let i of o){let l=nt(i);if(l.isParam){if(!s.paramChild)s.paramChild={name:l.name,node:this.createNode(),isOptional:l.isOptional};else if(s.paramChild.name!==l.name)throw new Error(`Route conflict: param name "[${l.name}]" conflicts with existing "[${s.paramChild.name}]" at the same path position. Use the same param name for all methods at this level.`);s=s.paramChild.node;}else {if(i==="*")return s.wildcardHandler||(s.wildcardHandler=Object.create(null)),s.wildcardHandler[e]=n,this.cachedRoutes.clear(),this;s.staticChildren.has(i)||s.staticChildren.set(i,this.createNode()),s=s.staticChildren.get(i);}}return s.isEndpoint=true,s.handlers[e]||this.routeCount++,s.handlers[e]=n,this.cachedRoutes.clear(),this}findRoute(e,r){let n=r==="/"?"/":r.replace(/\/+$/,""),o=e+":"+n,s=this.cachedRoutes.get(o);if(s)return this.cachedRoutes.delete(o),this.cachedRoutes.set(o,s),s;let i=n==="/"?[]:n.split("/").filter(Boolean),l=Object.create(null),a=this.traverse(this.rootNode,i,e,l,0)??{handler:null,params:Object.create(null)};if(a.handler!==null||a.allowedMethods?.length){if(this.cachedRoutes.size>=ot){let c=0;for(let u of this.cachedRoutes.keys())if(this.cachedRoutes.delete(u),++c>=at)break}this.cachedRoutes.set(o,a);}return a}traverse(e,r,n,o,s){if(s===r.length){if(e.isEndpoint){let c=e.handlers[n]??(n==="HEAD"?e.handlers.GET:void 0)??e.handlers[""];if(c)return {handler:c,params:Object.assign(Object.create(null),o)};let u=Object.keys(e.handlers).filter(h=>h!=="");return {handler:null,params:Object.create(null),allowedMethods:u}}let a=e.paramChild;if(a?.isOptional&&a.node.isEndpoint){let c=a.node.handlers[n]??(n==="HEAD"?a.node.handlers.GET:void 0)??a.node.handlers[""];if(c)return {handler:c,params:Object.assign(Object.create(null),o)}}return null}let i=r[s],l=e.staticChildren.get(i);if(l){let a=this.traverse(l,r,n,o,s+1);if(a)return a}if(e.paramChild){let{name:a,node:c}=e.paramChild;o[a]=i;let u=this.traverse(c,r,n,o,s+1);if(u)return u;delete o[a];}if(e.wildcardHandler){let a=e.wildcardHandler[n]??e.wildcardHandler[""],c=r.slice(s).join("/");if(a)return {handler:a,params:Object.assign(Object.create(null),o,{"*":c})};let u=Object.keys(e.wildcardHandler).filter(h=>h!=="");if(u.length>0)return {handler:null,params:Object.assign(Object.create(null),o,{"*":c}),allowedMethods:u}}return null}async loadRoutes(e){this.rootNode=this.createNode(),this.cachedRoutes.clear(),this.routeCount=0,await ye(e);let r=this;async function n(o,s=[]){try{let i=await Je.readdir(o,{withFileTypes:!0}),l=i.find(a=>!a.isDirectory()&&(a.name==="index.ts"||a.name==="index.js"));if(l)try{let c=await import(`${Q.resolve(Q.join(o,l.name))}?update=${Date.now()}`),u=["GET","POST","PUT","DELETE","PATCH"],h="/"+s.join("/"),y=!1;for(let R of u)typeof c[R]=="function"&&(r.addRoute(R,h,c[R]),y=!0);!y&&typeof c.default=="function"&&r.addRoute("GET",h,c.default),r.verbose&&g(`Route loaded: ${h}`);}catch(a){console.error(`Error loading index in ${o}:`,a);}for(let a of i)if(a.isDirectory()){let c=a.name.match(/^\[(\w+)(\??)]/),u=c?`[${c[1]}${c[2]}]`:a.name;await n(Q.join(o,a.name),[...s,u]);}}catch(i){console.error(`Error scanning directory ${o}:`,i);}}return await n(e),this.lastLoaded=Date.now(),this.verbose&&g(`Loading completed: ${this.routeCount} routes`),true}getRoutes(){let e=[];return this.collectRoutes(this.rootNode,[],e),e}collectRoutes(e,r,n){if(e.isEndpoint){let o=r.length===0?"/":"/"+r.join("/");for(let[s,i]of Object.entries(e.handlers))s!==""&&n.push({method:s,path:o,handler:i});}for(let[o,s]of e.staticChildren)this.collectRoutes(s,[...r,o],n);if(e.paramChild){let{name:o,isOptional:s,node:i}=e.paramChild;this.collectRoutes(i,[...r,s?`:${o}?`:`:${o}`],n);}if(e.wildcardHandler){let o="/"+[...r,"*"].join("/");for(let[s,i]of Object.entries(e.wildcardHandler))s!==""&&n.push({method:s,path:o,handler:i});}}getStats(){return {routeCount:this.routeCount,lastLoaded:this.lastLoaded,uptime:Date.now()-this.lastLoaded,cacheSize:this.cachedRoutes.size}}setVerbose(e){return this.verbose=e,this}reset(){this.rootNode=this.createNode(),this.cachedRoutes=new Map,this.routeCount=0;}},V=new we;function se(t){return t&&typeof t=="object"&&"error"in t}function Z(t){for(let{path:e,handlers:r}of t){let n=e.replace(/:(\w+\??)/g,(o,s)=>s.endsWith("?")?`[${s.slice(0,-1)}?]`:`[${s}]`);for(let[o,s]of Object.entries(r))typeof s=="function"&&V.addRoute(o,n,s);}}async function ne(t){let e=join(t,"_manifest.js");if(existsSync(e)){V.reset();let r=await import(e);Z(r.routes),r.middlewares?Y(r.middlewares):await ye(t);return}return V.loadRoutes(t)}function W(t,e="GET"){let r=V.findRoute(e,t);return r.handler?{handler:r.handler,params:r.params}:r.allowedMethods?.length?{error:"Method Not Allowed",status:405,allowedMethods:r.allowedMethods}:null}function Bt(t){let e=process.env.NODE_ENV==="production",r=process.env.ROUTES_DIR??t??(e?"dist/routes":"routes"),n=e&&!Q.isAbsolute(r)&&!r.startsWith("dist/")?Q.join("dist",r):r;return Q.resolve(process.cwd(),n)}function Wt(){return V.getStats()}function zt(t){V.setVerbose(t);}function Vt(){V.reset();}var q={OK:200,CREATED:201,NO_CONTENT:204,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,CONFLICT:409,UNPROCESSABLE_ENTITY:422,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504},Ae={400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",422:"Unprocessable Entity",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable",504:"Gateway Timeout"};function O(t){let e=t.code||q.INTERNAL_SERVER_ERROR,r=t.message||Ae[e]||"Unknown Error",n=t.name||`HttpError${e}`,o=new Error(r);return Error.captureStackTrace?.(o,O),{name:n,code:e,message:r,details:t.details,expose:t.expose!==void 0?t.expose:e<500,log:t.log!==void 0?t.log:e>=500,stack:o.stack}}function it(t){let r={error:t.expose?t.message:Ae[t.code]||"Internal Server Error",code:t.code};return t.expose&&t.details?{...r,details:t.details}:r}function Ne(t,e){e.headersSent||(e.statusCode=t.code,e.setHeader("Content-Type","application/json"),e.end(JSON.stringify(it(t)))),t.log&&dt(t);}function dt(t){let e={name:t.name,message:t.message,code:t.code,details:t.details,stack:t.stack};t.code>=500?g("\u274C ERROR:",JSON.stringify(e,null,2)):g("\u26A0\uFE0F WARNING:",JSON.stringify(e,null,2));}function Yt(t,e){return O({name:"BadRequestError",code:q.BAD_REQUEST,message:t,details:e})}function Qt(t,e){return O({name:"UnauthorizedError",code:q.UNAUTHORIZED,message:t,details:e})}function Kt(t,e){return O({name:"ForbiddenError",code:q.FORBIDDEN,message:t,details:e})}function Zt(t,e){return O({name:"NotFoundError",code:q.NOT_FOUND,message:t,details:e})}function Xt(t,e){return O({name:"MethodNotAllowedError",code:q.METHOD_NOT_ALLOWED,message:t,details:e})}function er(t,e){return O({name:"ConflictError",code:q.CONFLICT,message:t,details:e})}function tr(t,e){return O({name:"ValidationError",code:q.UNPROCESSABLE_ENTITY,message:t,details:e,expose:true})}function rr(t,e){return O({name:"RateLimitError",code:q.TOO_MANY_REQUESTS,message:t,details:e})}function lt(t,e){return O({name:"InternalServerError",code:q.INTERNAL_SERVER_ERROR,message:t,details:e})}function ut(t,e){return O({name:"ServiceUnavailableError",code:q.SERVICE_UNAVAILABLE,message:t,details:e})}function ct(t,e){return O({name:"GatewayTimeoutError",code:q.GATEWAY_TIMEOUT,message:t,details:e})}function qe(t){if(t&&typeof t=="object"&&typeof t.code=="number"&&"message"in t)return t;let e=t?.message||"Unknown error occurred",r=t?.stack?{stack:t.stack}:void 0,n=t?.code||t?.statusCode;return n==="ECONNREFUSED"||n==="ENOTFOUND"?ut(`Service connection failed: ${e}`,r):n==="ETIMEDOUT"?ct(`Request timed out: ${e}`,r):typeof n=="number"&&n>=400&&n<600?O({code:n,message:e,details:r}):lt(e,r)}function Ie(t){return !!(t&&typeof t=="object"&&typeof t.code=="number"&&"message"in t&&"name"in t)}function $e(t,e={},r={},n){let o=false,s=0,i={},l=[],a=[],c=[],u=null;r.onMessage&&l.push(r.onMessage),r.onClose&&a.push(r.onClose),r.onError&&c.push(r.onError),r.onEvent&&Object.entries(r.onEvent).forEach(([f,m])=>{i[f]||(i[f]=[]),i[f].push(m);});let h=e.reconnectInterval||3e3,y=e.maxRetries||3,R=e.disableReconnect||false,w=e.body,p=e.contentType||(w?"application/json":void 0),d=e.method||(w?"POST":"GET");if(typeof t!="string"){let f=t;return o=true,f.on("data",m=>{S(m.toString());}),f.on("end",()=>{o=false;}),f.on("error",m=>{o=false,console.error("SSE Error:",m);}),b()}if(typeof t=="string")return new Promise((f,m)=>{I().then(()=>f(b())).catch(m);});function S(f){let m=f,C=m.split(` `);m=C.pop()||"";for(let M of C){let A=M.split(` `),E="",v="";for(let _ of A)_.startsWith("event:")?v=_.slice(6).trim():_.startsWith("data:")&&(E=_.slice(5).trim());if(E)try{let _=JSON.parse(E);v&&i[v]?i[v].forEach(K=>K(_)):l.forEach(K=>K(_));}catch{v&&i[v]?i[v].forEach(_=>_(E)):l.forEach(_=>_(E));}}}function b(){return {onMessage(f){return l.push(f),this},onEvent(f,m){return i[f]||(i[f]=[]),i[f].push(m),this},onClose(f){return a.push(f),this},close(){u&&(u.destroy(),u=null),o=false,a.forEach(f=>f());}}}async function I(){if(!o){o=true;try{await T();}catch(f){!R&&s<y?(s++,setTimeout(()=>{I();},h)):c.forEach(m=>m(f));}}}async function T(){return new Promise((f,m)=>{let C=new URL(t);e.params&&(typeof e.params=="object"?Object.entries(e.params).forEach(([E,v])=>{C.searchParams.append(E,String(v));}):typeof e.params=="string"&&new URLSearchParams(e.params).forEach((v,_)=>{C.searchParams.append(_,v);}));let M={hostname:C.hostname,port:C.port||(C.protocol==="https:"?443:80),path:C.pathname+C.search,method:d,headers:{Accept:"text/event-stream",...n?.headers||{},"Cache-Control":"no-cache",Connection:"keep-alive",...p&&{"Content-Type":p},...w&&typeof w=="string"&&{"Content-Length":Buffer.byteLength(w).toString()},...w&&typeof w!="string"&&{"Content-Length":Buffer.byteLength(JSON.stringify(w)).toString()}}};u=(C.protocol==="https:"?pt:Te).request(M,E=>{if(E.statusCode!==200){o=false,m(new Error(`Server responded with status: ${E.statusCode}`));return}E.setEncoding("utf8"),E.on("data",S),E.on("end",()=>{o=false,u?.destroy(),u=null,a.forEach(v=>v()),f(null);}),E.on("close",()=>{o=false,u?.destroy(),u=null,a.forEach(v=>v()),f(null);}),E.on("error",v=>{o=false,u?.destroy(),u=null,a.forEach(_=>_()),m(v);});}),u.on("error",E=>{o=false,u?.destroy(),u=null,m(E);}),w&&(typeof w=="string"?u.write(w):u.write(JSON.stringify(w))),u.end();})}return b()}var Re=class{constructor(e,r){this._res=e;this._timeoutId=setTimeout(()=>e.end(),r),e.on("close",()=>clearTimeout(this._timeoutId));}_res;_timeoutId;send(e){return this._res.writableEnded?false:this._res.write(`data: ${e} `)}json(e){return this._res.writableEnded?false:this._res.write(`data: ${JSON.stringify(e)} `)}event(e,r){return this._res.writableEnded?false:(this._res.write(`event: ${e} `),this._res.write(`data: ${JSON.stringify(r)} `))}comment(e){return this._res.writableEnded?false:this._res.write(`: ${e} `)}id(e){return this._res.writableEnded?false:this._res.write(`id: ${e} `)}retry(e){return this._res.writableEnded?false:this._res.write(`retry: ${e} `)}close(e="Connection closed"){clearTimeout(this._timeoutId),this._res.write(`: ${e} `),this._res.end();}error(e,r,n=500,o){clearTimeout(this._timeoutId),this._res.write(`event: ${e} `),this._res.write(`data: ${JSON.stringify({message:r,code:n,details:o??null})} `),this._res.end();}};function Pe(t,e){let r=e?.headers?.["Cache-Control"]??"no-cache",n=e?.headers?.Connection??"keep-alive",o=e?.timeout??3e5;return t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":r,Connection:n,...e?.headers??{}}),new Re(t,o)}var ht=10485760,ae=class{_parsed=null;_raw;constructor(e){this._raw=e;}_parse(){if(this._parsed!==null)return this._parsed;if(this._parsed={},!this._raw)return this._parsed;for(let e of this._raw.split(";")){let r=e.indexOf("=");if(r===-1)continue;let n=e.slice(0,r).trim(),o=e.slice(r+1).trim();if(n){let s=o.startsWith('"')&&o.endsWith('"')?o.slice(1,-1):o;try{this._parsed[n]=decodeURIComponent(s);}catch{this._parsed[n]=s;}}}return this._parsed}get(e){return this._parse()[e]}all(){return {...this._parse()}}},ie=class{_pending=[];set(e,r,n={}){return this._pending.push({name:e,value:r,opts:n}),this}delete(e,r={}){return this.set(e,"",{...r,maxAge:0,expires:new Date(0)})}serialize(){return this._pending.map(({name:e,value:r,opts:n})=>{let o=`${e}=${encodeURIComponent(r)}`,s=n.path!==void 0?n.path:"/";return s&&(o+=`; Path=${s}`),n.domain&&(o+=`; Domain=${n.domain}`),n.maxAge!=null&&(o+=`; Max-Age=${n.maxAge}`),n.expires&&(o+=`; Expires=${n.expires.toUTCString()}`),n.httpOnly&&(o+="; HttpOnly"),n.secure&&(o+="; Secure"),n.sameSite&&(o+=`; SameSite=${n.sameSite}`),o})}};function Le(t){if(typeof t.get=="function")return t.get("cookie")??void 0;let e=t.cookie;return Array.isArray(e)?e.join("; "):e}function X(t){return class extends t{_zreqCookies;getHeader(e){let r=this.headers;if(typeof r.get=="function")return r.get(e)??void 0;let n=r[e.toLowerCase()];return Array.isArray(n)?n[0]:n}get cookies(){return this._zreqCookies||(this._zreqCookies=new ae(Le(this.headers))),this._zreqCookies}json(){return this.body().then(e=>JSON.parse(e.toString()))}form(){return new Promise((e,r)=>{let n=this.headers,o=typeof n.get=="function"?n.get("content-type")??"":n["content-type"]??"";if(!o.startsWith("multipart/form-data")){r(new Error("Content-Type is not multipart/form-data"));return}let s=o.match(/boundary=(.+)$/);if(!s){r(new Error("Boundary not found"));return}let i=s[1].trim();this.body().then(l=>{let a={},c=Buffer.from(`--${i}`),u=[],h=0,y;for(;(y=l.indexOf(c,h))!==-1;)u.push(l.subarray(h,y)),h=y+c.length;u.push(l.subarray(h));for(let R=1;R<u.length-1;R++){let w=u[R].subarray(2),p=w.indexOf(`\r \r `);if(p===-1)continue;let d=w.subarray(0,p).toString(),S=w.subarray(p+4,w.length-2),b=d.match(/Content-Disposition: form-data; name="([^"]+)"(?:; filename="([^"]+)")?/i);if(b)if(b[2]){let I=d.match(/Content-Type:\s*([^\r\n]+)/i);a[b[1]]={filename:b[2],mimetype:I?I[1].trim():"application/octet-stream",data:S,size:S.length};}else a[b[1]]=S.toString("utf-8");}e(a);}).catch(r);})}createSSEClient(e,r){return $e(this,e,r)}}}function de(){let t=[],e=0,r=false;return new Promise((n,o)=>{this.on("data",s=>{if(e+=s.length,e>ht){r=true,this.destroy(),o(Object.assign(new Error("Payload Too Large"),{code:413}));return}t.push(s);}).on("end",()=>{r||(r=true,n(Buffer.concat(t)));}).on("error",s=>{r||(r=true,o(s));});})}function Ue(t,e){let r=t.serialize();r.length>0&&!e.headersSent&&e.setHeader("Set-Cookie",r);}function ee(t){return class extends t{_zresCookies;get cookies(){return this._zresCookies||(this._zresCookies=new ie),this._zresCookies}end(e){return this._zresCookies&&Ue(this._zresCookies,this),super.end(e)}status(e){return this.statusCode=e,this}send(e){return typeof e=="string"?(this.setHeader("Content-Type","text/plain"),this.end(e)):this.json(e),this}json(e){return this.setHeader("Content-Type","application/json"),this.end(JSON.stringify(e)),this}html(e){return this.setHeader("Content-Type","text/html; charset=utf-8"),this.end(e),this}redirect(e,r=302){return this.statusCode=r,this.setHeader("Location",e),this.end(),this}initSSE(e){return Pe(this,e)}}}var Ee=class{params={};headers={};body(){return de.call(this)}},oe=X(Ee).prototype,Ce=class{statusCode=200;headersSent=false;setHeader(e,r){}end(e){}write(e){}},mt=ee(Ce).prototype;function le(t){t.body=de,t.json=oe.json,t.form=oe.form,t.getHeader=oe.getHeader,t.createSSEClient=oe.createSSEClient,t.cookies=new ae(Le(t.headers));}function ue(t){let e=t.indexOf("?");return e===-1?t:t.slice(0,e)}function ce(t){let e=t.indexOf("?");return e===-1?{}:Object.fromEntries(new URLSearchParams(t.slice(e+1)).entries())}async function P(t,e,r){let n=Ie(r)?r:qe(r);n.log&&console.error("[lacis] Error:",r),H()&&await k("onError",t,e,{error:n}),e.headersSent||Ne(n,e);}function fe(t){let e=mt;t.status=e.status,t.send=e.send,t.json=e.json,t.html=e.html,t.redirect=e.redirect,t.initSSE=e.initSSE;let r=new ie;t.cookies=r;let n=t.end.bind(t);t.end=function(...o){return Ue(r,this),n(...o)};}var pe=null;function yt(t={}){let e=new EventEmitter,r={sampleInterval:t.sampleInterval||5e3,reportInterval:t.reportInterval||6e4,resetInterval:t.resetInterval||1440*60*1e3,enableHistogram:t.enableHistogram!==void 0?t.enableHistogram:true,logToConsole:t.logToConsole!==void 0?t.logToConsole:true,thresholds:{cpu:t.thresholds?.cpu||80,memory:t.thresholds?.memory||80,responseTime:t.thresholds?.responseTime||1e3,errorRate:t.thresholds?.errorRate||5}},n=Date.now(),o={requestCount:0,activeRequests:0,errorCount:0,responseTimes:[],responseTimesBucket:Array(100).fill(0),statusCodes:{},lastReport:n,lastReset:n},s=c(),i=[],l=process.cpuUsage(),a={cpu:false,memory:false,responseTime:false,errorRate:false};function c(){return {timestamp:Date.now(),uptime:process.uptime(),requestCount:0,activeRequests:0,errorCount:0,responseTimes:{min:0,max:0,avg:0,count:0,sum:0},statusCodes:{},memory:process.memoryUsage(),cpu:{usage:0,system:0,user:0},systemLoad:x.loadavg(),systemMemory:{total:x.totalmem(),free:x.freemem(),used:x.totalmem()-x.freemem()}}}function u(){let f=o.responseTimes;if(f.length===0)return {min:0,max:0,avg:0,count:0,sum:0};let m=1/0,C=-1/0,M=0;for(let v of f)m=Math.min(m,v),C=Math.max(C,v),M+=v;let A=M/f.length,E={min:m,max:C,avg:A,count:f.length,sum:M};if(r.enableHistogram){let v=[...f].sort((_,K)=>_-K);E.p50=v[Math.floor(v.length*.5)],E.p90=v[Math.floor(v.length*.9)],E.p99=v[Math.floor(v.length*.99)];}return E}function h(){let f=Date.now(),m=process.uptime(),C=process.memoryUsage(),M=process.cpuUsage(l);l=process.cpuUsage();let E=(M.user+M.system)/1e3/r.sampleInterval*100;s={timestamp:f,uptime:m,requestCount:o.requestCount,activeRequests:o.activeRequests,errorCount:o.errorCount,responseTimes:u(),statusCodes:{...o.statusCodes},memory:C,cpu:{usage:E,system:M.system,user:M.user},systemLoad:x.loadavg(),systemMemory:{total:x.totalmem(),free:x.freemem(),used:x.totalmem()-x.freemem()}},i.push({...s}),i.length>100&&i.shift(),w(),J.isWorker&&process.send&&process.send({type:"metrics",metrics:s});}function y(){if(!r.logToConsole||J.isPrimary===false)return;let f={rss:(s.memory.rss/1024/1024).toFixed(2),heapTotal:(s.memory.heapTotal/1024/1024).toFixed(2),heapUsed:(s.memory.heapUsed/1024/1024).toFixed(2)},m=Date.now()-o.lastReport,C=(s.requestCount/(m/1e3)).toFixed(2),M=s.requestCount?(s.errorCount/s.requestCount*100).toFixed(2):"0.00";g(` \u{1F4CA} Server Performance Metrics \u{1F4CA}`),g(`Uptime: ${p(s.uptime)}`),g(`Load: ${s.systemLoad[0].toFixed(2)}, ${s.systemLoad[1].toFixed(2)}, ${s.systemLoad[2].toFixed(2)}`),g(`Requests: ${s.requestCount} total, ${C} req/sec`),g(`Active Requests: ${s.activeRequests}`),g(`Errors: ${s.errorCount} (${M}%)`),s.responseTimes.count>0&&(g(`Response Times: avg ${s.responseTimes.avg.toFixed(2)}ms, min ${s.responseTimes.min}ms, max ${s.responseTimes.max}ms`),s.responseTimes.p50&&g(`Response Time Percentiles: p50 ${s.responseTimes.p50}ms, p90 ${s.responseTimes.p90}ms, p99 ${s.responseTimes.p99}ms`)),g(`Memory: ${f.rss}MB (RSS), ${f.heapUsed}MB / ${f.heapTotal}MB (Heap)`),g(`CPU Usage: ${s.cpu.usage.toFixed(2)}%`),Object.keys(s.statusCodes).length>0&&(g("Status Codes:"),Object.entries(s.statusCodes).sort(([A],[E])=>parseInt(A)-parseInt(E)).forEach(([A,E])=>{g(` ${A}: ${E}`);})),g(""),o.lastReport=Date.now();}function R(){let f=Date.now();o.requestCount=0,o.activeRequests=0,o.errorCount=0,o.responseTimes=[],o.responseTimesBucket=Array(100).fill(0),o.statusCodes={},o.lastReport=f,o.lastReset=f,g("\u{1F504} Performance metrics have been reset");}function w(){let f=s.memory.heapUsed/s.memory.heapTotal*100,m=s.requestCount?s.errorCount/s.requestCount*100:0,C=s.responseTimes.avg;s.cpu.usage>r.thresholds.cpu&&!a.cpu?(a.cpu=true,e.emit("alarm","cpu",`High CPU usage: ${s.cpu.usage.toFixed(2)}%`)):s.cpu.usage<=r.thresholds.cpu&&a.cpu&&(a.cpu=false,e.emit("alarm-clear","cpu",`CPU usage returned to normal: ${s.cpu.usage.toFixed(2)}%`)),f>r.thresholds.memory&&!a.memory?(a.memory=true,e.emit("alarm","memory",`High memory usage: ${f.toFixed(2)}%`)):f<=r.thresholds.memory&&a.memory&&(a.memory=false,e.emit("alarm-clear","memory",`Memory usage returned to normal: ${f.toFixed(2)}%`)),C>r.thresholds.responseTime&&!a.responseTime?(a.responseTime=true,e.emit("alarm","responseTime",`High response time: ${C.toFixed(2)}ms`)):C<=r.thresholds.responseTime&&a.responseTime&&(a.responseTime=false,e.emit("alarm-clear","responseTime",`Response time returned to normal: ${C.toFixed(2)}ms`)),m>r.thresholds.errorRate&&!a.errorRate?(a.errorRate=true,e.emit("alarm","errorRate",`High error rate: ${m.toFixed(2)}%`)):m<=r.thresholds.errorRate&&a.errorRate&&(a.errorRate=false,e.emit("alarm-clear","errorRate",`Error rate returned to normal: ${m.toFixed(2)}%`));}function p(f){let m=Math.floor(f/86400),C=Math.floor(f%86400/3600),M=Math.floor(f%3600/60),A=Math.floor(f%60),E=[];return m>0&&E.push(`${m}d`),C>0&&E.push(`${C}h`),M>0&&E.push(`${M}m`),(A>0||E.length===0)&&E.push(`${A}s`),E.join(" ")}function d(){let f=setInterval(h,r.sampleInterval),m=setInterval(y,r.reportInterval),C=setInterval(R,r.resetInterval);return {stop:()=>{clearInterval(f),clearInterval(m),clearInterval(C);}}}function S(){let f=Date.now();return o.activeRequests++,{end:(m,C=false)=>{let M=Date.now()-f;return o.activeRequests--,o.requestCount++,o.responseTimes.push(M),o.responseTimes.length>1e3&&o.responseTimes.shift(),o.statusCodes[m]=(o.statusCodes[m]||0)+1,(C||m>=500)&&o.errorCount++,M}}}function b(){return !Object.values(a).some(f=>f)}function I(){let f=s.memory.heapUsed/s.memory.heapTotal*100,m=s.requestCount?s.errorCount/s.requestCount*100:0;return {status:b()?"healthy":"unhealthy",uptime:s.uptime,responseTimes:{avg:s.responseTimes.avg,p90:s.responseTimes.p90||null,p99:s.responseTimes.p99||null},memory:{usedMB:Math.round(s.memory.heapUsed/1024/1024),totalMB:Math.round(s.memory.heapTotal/1024/1024),percent:f.toFixed(2)},cpu:s.cpu.usage.toFixed(2),requests:{total:s.requestCount,active:s.activeRequests,errors:s.errorCount,errorRate:m.toFixed(2)},alerts:Object.entries(a).filter(([C,M])=>M).map(([C])=>C)}}let T=d();return {trackRequest:S,getMetrics:()=>({...s}),getMetricsHistory:()=>[...i],getHealthMetrics:I,isHealthy:b,stop:T.stop,on:e.on.bind(e),once:e.once.bind(e),off:e.off.bind(e)}}function Fe(t){if(!pe){let e=yt(t),r=e.stop;e.stop=()=>{r(),pe=null;},pe=e;}return pe}function Se(t={}){let e=t.reportInterval??5e3,r={workers:new Map,workerIds:[]};function n(){if(!J.isWorker)return;let c=process.cpuUsage(),u=()=>{if(!process.send)return;let h=process.memoryUsage(),y=process.cpuUsage(c);c=process.cpuUsage();let R=(y.user+y.system)/(e*1e3),w={type:"stats",stats:{pid:process.pid,load:R,lastUsed:Date.now(),memoryUsage:h}};process.send(w);};u(),setInterval(u,e).unref();}function o(){let c=J.fork();r.workers.set(c.id,{pid:c.process.pid,load:0,lastUsed:Date.now(),memoryUsage:{rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}}),r.workerIds.push(c.id),g(`Worker ${c.process.pid} started`);}let s=false,i=[];function l(c=x.cpus().length){if(!J.isPrimary)return n();g(`\u{1F9F5} Launching ${c} workers...`);for(let u=0;u<c;u++)o();J.on("message",(u,h)=>{if(h.type==="stats"&&"stats"in h){let y=r.workers.get(u.id);y&&Object.assign(y,h.stats);}}),J.on("exit",(u,h,y)=>{if(r.workers.delete(u.id),r.workerIds=r.workerIds.filter(R=>R!==u.id),s){i.forEach(R=>R());return}g(`Worker ${u.process.pid} died (${y||h}). Restarting...`),setTimeout(()=>o(),1e3);});}function a(c){s=true;let u=Object.keys(J.workers??{});if(u.length===0){c?.();return}let h=u.length;i.push(()=>{h--,h===0&&c?.();});for(let y of u)J.workers?.[y]?.kill();}return {start:l,shutdown:a,getWorkerStats:()=>Array.from(r.workers.entries()),getActiveWorkerCount:()=>r.workerIds.length}}var be=class extends Te.IncomingMessage{params={};body=de},ve=class extends X(be){},Me=class extends ee(Te.ServerResponse){},Be={name:"node",createHandler:t=>{if(typeof t!="string")throw new Error("nodeAdapter requires a routesDir string, not a ServerlessConfig.");let e=t;return async(r={})=>{let{port:n=3e3,defaultHeaders:o,isDev:s,cluster:i,monitoring:l={enabled:false}}=r,a=null;s&&l.enabled&&(a=Fe({sampleInterval:l.sampleInterval||5e3,reportInterval:l.reportInterval||6e4,thresholds:l.thresholds,logToConsole:true}),J.isPrimary&&(g("\u{1F4CA} Development performance monitoring enabled"),a.on("alarm",(u,h)=>{g(`\u26A0\uFE0F ALERT: ${h}`);}),a.on("alarm-clear",(u,h)=>{g(`\u2705 RESOLVED: ${h}`);})));let c=o?Object.entries(o):[];if(i?.enabled&&J.isPrimary){let u=i.workers??x__default.cpus().length,h=r.httpsOptions?"https":"http";if(g(`\u{1F9F5} Starting server with ${u} workers`),J.schedulingPolicy!==void 0)try{J.schedulingPolicy=J.SCHED_RR;}catch{}let y=Se();return y.start(u),g(`\u{1F680} Server running at ${h}://localhost:${n}/`+(s?" (dev)":"")),s&&a&&g(`\u{1F4CA} Performance monitoring available at http://localhost:${n}/health`),{close:R=>{a&&a.stop(),y.shutdown(R);}}}if(J.isWorker||!i?.enabled){r.routes||await ne(e),B(r.cors),D(r.middleware),U(r.hooks);let u=async(p,d,S)=>{try{if(s&&a&&p.url==="/health"){d.setHeader("Content-Type","application/json"),d.end(JSON.stringify(a.getHealthMetrics())),S?.end(200);return}let b=p.url||"/",I=ue(b);if(p.query=ce(b),H()&&(await k("beforeRequest",p,d)===!1||d.headersSent)){S?.end(d.statusCode||204);return}let T=W(I,p.method||"GET");if(!T){if(j()&&(await F(p,d),d.headersSent)){S?.end(d.statusCode);return}d.status(404).json({error:"Route not found"}),S?.end(404);return}if("error"in T){let f=T.status||500;d.status(f).json({error:T.error}),S?.end(f,!0);return}p.params=T.params,await T.handler(p,d),H()&&await k("afterRequest",p,d),d.headersSent||d.end(),S?.end(d.statusCode||200);}catch(b){await P(p,d,b),d.headersSent||d.status(500).json({error:"Internal Server Error"}),S?.end(d.statusCode||500,true);}},h=(p,d)=>{let S=s&&a?a.trackRequest():null;if(c.length>0)for(let b=0;b<c.length;b++)d.setHeader(c[b][0],c[b][1]);u(p,d,S).catch(b=>{s&&console.error("Fatal error:",b),d.headersSent||(d.statusCode=500,d.end("Server Error")),S?.end(500,true);});},y={IncomingMessage:ve,ServerResponse:Me},R=r.httpsOptions?pt.createServer({...y,...r.httpsOptions},h):Te.createServer(y,h);R.on("clientError",(p,d)=>{d.destroyed||d.destroy();});let w=r.httpsOptions?"https":"http";return J.isWorker&&Se().start(),R.listen(n,()=>{i?.enabled?s&&g(`Worker ${process.pid} is listening on port ${n}`):(g(`\u{1F680} Server running at ${w}://localhost:${n}/`+(s?" (dev)":"")),s&&a&&g(`\u{1F4CA} Performance monitoring available at http://localhost:${n}/health`));}),R}return null}}};var We={name:"vercel",createHandler:t=>{if(typeof t=="string")throw new Error("vercelAdapter.createHandler() requires a ServerlessConfig object, not a routesDir string. Import your routes manifest and pass { routes } instead.");let e=null,r=()=>e||(e=(async()=>{Z(t.routes),B(t.cors),D(t.middleware),Y(t.middlewares),U(t.hooks);})(),e);return async(n,o)=>{await r(),le(n),fe(o);let s=n,i=o;try{if(H()&&(await k("beforeRequest",s,i)===!1||i.headersSent))return;let l=W(ue(s.url??"/"),s.method??"GET");if(!l){if(j()&&(await F(s,i),i.headersSent))return;i.status(404).json({error:"Route not found"});return}if(se(l)){i.status(l.status??500).json({error:l.error});return}s.params=l.params,await l.handler(s,i),H()&&await k("afterRequest",s,i);}catch(l){await P(s,i,l),i.headersSent||i.status(500).json({error:"Internal server error"});}}}};function he(t,e,r,n){let o=Object.keys(r).length>0;return {statusCode:t,headers:e,...o?{multiValueHeaders:r}:{},body:n}}var ze={name:"netlify",createHandler:t=>{if(typeof t=="string")throw new Error("netlifyAdapter.createHandler() requires a ServerlessConfig object. Run `lacis build` to generate routes/_manifest.ts and pass { routes } instead.");let e=null,r=()=>e||(e=(async()=>{Z(t.routes),B(t.cors),D(t.middleware),Y(t.middlewares),U(t.hooks);})(),e);return async(n,o)=>{await r();let s=n.queryStringParameters?"?"+new URLSearchParams(n.queryStringParameters).toString():"",i=n.path+s,l=new IncomingMessage(new Socket);if(l.url=i,l.method=n.httpMethod,l.headers=n.headers,n.body){let p=n.isBase64Encoded?"base64":"utf-8";l.push(Buffer.from(n.body,p));}l.push(null);let a="",c={},u={},h=false,y=new ServerResponse(l);y.writeHead=function(p,d){return y.statusCode=p,d&&(c={...c,...d}),this},y.setHeader=function(p,d){let S=p.toLowerCase();return Array.isArray(d)?(u[S]=d.map(String),c[S]=String(d[0])):c[S]=String(d),this},y.getHeader=function(p){return c[p.toLowerCase()]},y.end=function(p){return h=true,p!==void 0&&(a=typeof p=="string"?p:p.toString()),this},Object.defineProperty(y,"headersSent",{get:()=>h}),le(l),fe(y);let R=l,w=y;R.query=n.queryStringParameters??{};try{if(H()&&(await k("beforeRequest",R,w)===!1||h))return he(w.statusCode,c,u,a);let p=W(n.path,n.httpMethod);return p?se(p)?{statusCode:p.status??500,body:JSON.stringify({error:p.error})}:(R.params=p.params,await p.handler(R,w),H()&&await k("afterRequest",R,w),he(w.statusCode,c,u,a)):j()&&(await F(R,w),h)?he(w.statusCode,c,u,a):{statusCode:404,body:JSON.stringify({error:"Route not found"})}}catch(p){return await P(R,w,p),h?he(w.statusCode,c,u,a):{statusCode:500,body:JSON.stringify({error:"Internal server error"})}}}}};var vt=10485760,Mt=new TextEncoder,_e=class{params={};url;method;headers;socket={setTimeout:e=>{}};connection;_req;constructor(e,r,n,o){this._req=e,this.url=r+n,this.method=e.method,this.headers=e.headers,this.connection={remoteAddress:o};}setTimeout(e){}text(){return this._req.text()}body(){return this._req.arrayBuffer().then(e=>{if(e.byteLength>vt)throw Object.assign(new Error("Payload Too Large"),{code:413});return Buffer.from(e)})}},He=class extends X(_e){json(){return this._req.json()}},ke=class{statusCode=200;headersSent=false;get finished(){return this.headersSent}get writableEnded(){return this.headersSent}_body=null;_headers=null;_sseReadable=null;_sseWriter=null;_sseWindowClosed=false;_listeners=null;on(e,r){return (e==="finish"||e==="close")&&(this._listeners||(this._listeners=[]),this._listeners.push(r)),this}once(e,r){return this.on(e,r)}emit(e){if((e==="finish"||e==="close")&&this._listeners)for(let r=0;r<this._listeners.length;r++)this._listeners[r]();return true}setHeader(e,r){if(this._headers||(this._headers=[]),Array.isArray(r))for(let n of r)this._headers.push(e,n);else this._headers.push(e,r);return this}getHeader(e){if(!this._headers)return;let r=e.toLowerCase();for(let n=0;n<this._headers.length;n+=2)if(this._headers[n].toLowerCase()===r)return this._headers[n+1]}removeHeader(e){if(!this._headers)return this;let r=e.toLowerCase();for(let n=0;n<this._headers.length;n+=2)if(this._headers[n].toLowerCase()===r){this._headers.splice(n,2);break}return this}hasHeader(e){if(!this._headers)return false;let r=e.toLowerCase();for(let n=0;n<this._headers.length;n+=2)if(this._headers[n].toLowerCase()===r)return true;return false}writeHead(e,r){if(this.statusCode=e,r)for(let[n,o]of Object.entries(r))this.setHeader(n,o);return this}write(e){return this._sseWriter?(this._sseWriter.write(Mt.encode(String(e))),true):(this._body=(this._body??"")+e,true)}end(e){if(e!==void 0&&this.write(e),this._sseWriter&&this._sseWriter.close(),this.headersSent=true,this._listeners)for(let r=0;r<this._listeners.length;r++)this._listeners[r]();return this}_initSseStream(){if(this._sseWindowClosed)throw new Error("[lacis/bun] initSSE() must be called synchronously before any `await` in your handler.");let{readable:e,writable:r}=new TransformStream;this._sseReadable=e,this._sseWriter=r.getWriter();}_closeSseWindow(){this._sseWindowClosed=true;}},Oe=class extends ee(ke){initSSE(e){return this._initSseStream(),super.initSSE(e)}},Ve={name:"bun",createHandler:t=>{if(typeof t!="string")throw new Error("bunAdapter requires a routesDir string, not a ServerlessConfig.");let e=t;return async(r={})=>{let{isDev:n,port:o=3e3,defaultHeaders:s,cluster:i}=r,l=parseInt(process.env.LACIS_BUN_WORKER??"0"),a=l>0;if(i?.enabled&&!a){let h=i.workers??x__default.cpus().length;g(`\u{1F9F5} Starting Bun server with ${h} workers (reusePort)`);let y=Array.from({length:h},()=>Bun.spawn(process.argv,{env:{...process.env,LACIS_BUN_WORKER:String(process.pid)},stdout:"ignore",stderr:"inherit"}));return g(`\u{1F680} Server running at http://localhost:${o}/`),{close:R=>{for(let w of y)w.kill();R?.();}}}if(a){let h=setInterval(()=>{try{process.kill(l,0);}catch{clearInterval(h),process.exit(0);}},2e3);h.unref();}g("\u{1F680} Bun high-performance mode enabled"),r.routes||await ne(e),B(r.cors),D(r.middleware),U(r.hooks);let c=s?Object.entries(s):[],u=Bun.serve({port:o,reusePort:a,async fetch(h,y){let R=new URL(h.url),w=R.pathname,p=new He(h,w,R.search,y?.requestIP(h)?.address??"");p.query=ce(R.search);let d=new Oe;try{for(let T=0;T<c.length;T++)d.setHeader(c[T][0],c[T][1]);if(H()&&(!await k("beforeRequest",p,d)||d.headersSent))return te(d);let S=W(w,h.method);if(!S)return j()&&(await F(p,d),d.headersSent)?te(d):new Response(JSON.stringify({error:"Route not found"}),{status:404,headers:{"Content-Type":"application/json"}});if("error"in S)return H()&&await k("onError",p,d),new Response(JSON.stringify({error:S.error}),{status:S.status||500,headers:{"Content-Type":"application/json"}});p.params=S.params;let b=null,I=(async()=>{await S.handler(p,d),H()&&await k("afterRequest",p,d),d.headersSent||d.end();})().catch(T=>{b=T,n&&console.error("Server error:",T),d._sseReadable&&!d.headersSent&&d.end();});return d._closeSseWindow(),d._sseReadable?te(d,d._sseReadable):(await I,b&&(await P(p,d,b),!d.headersSent)?new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}}):te(d))}catch(S){return await P(p,d,S),d.headersSent?te(d):new Response(JSON.stringify({error:"Internal Server Error"}),{status:500,headers:{"Content-Type":"application/json"}})}}});return g(`\u{1F680} Server started on http://localhost:${o}${n?" (dev)":""}`),{close:()=>{u.stop();}}}}};function te(t,e){let r=e??t._body;if(!t._headers)return new Response(r,{status:t.statusCode});let n=new Headers;for(let o=0;o<t._headers.length;o+=2){let s=t._headers[o],i=t._headers[o+1];s.toLowerCase()==="set-cookie"?n.append(s,i):n.set(s,i);}return new Response(r,{status:t.statusCode,headers:n})}var Tt={node:Be,vercel:We,netlify:ze,bun:Ve};function ss(t="node"){let e=Tt[t];if(!e)throw new Error(`Platform "${t}" not supported`);return e} export{B as A,q as B,O as C,Ne as D,dt as E,Yt as F,Qt as G,Kt as H,Zt as I,Xt as J,er as K,tr as L,rr as M,lt as N,ut as O,ct as P,qe as Q,Ie as R,$e as S,Pe as T,Be as U,We as V,ze as W,Ve as X,ss as Y,ge as a,Ge as b,Ye as c,Qe as d,H as e,k as f,ye as g,kt as h,Y as i,U as j,j as k,F as l,Ot as m,xt as n,D as o,g as p,V as q,se as r,Z as s,ne as t,W as u,Bt as v,Wt as w,zt as x,Vt as y,Xe as z};