molnos 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,20 @@
1
1
  // MolnOS Core - See LICENSE file for copyright and license details.
2
- import{existsSync as U}from"node:fs";import{join as F}from"node:path";import{mkdir as Bt,writeFile as Y,readFile as wt,unlink as Vt}from"node:fs/promises";import{pathToFileURL as zt}from"node:url";import{getRandomValues as vt}from"node:crypto";var q=class{options;defaultLength=16;defaultOnlyLowerCase=!1;defaultStyle="extended";defaultUrlSafe=!0;constructor(e){if(this.options={},e)for(let[t,r]of Object.entries(e))this.options[t]=this.generateConfig(r)}add(e){if(!e?.name)throw new Error("Missing name for the ID configuration");let t=this.generateConfig(e);this.options[e.name]=t}remove(e){if(!e?.name)throw new Error("Missing name for the ID configuration");delete this.options[e.name]}create(e,t,r,n){let s=this.generateConfig({length:e,style:t,onlyLowerCase:r,urlSafe:n});return this.generateId(s)}custom(e){if(this.options[e])return this.generateId(this.options[e]);throw new Error(`No configuration found with name: ${e}`)}generateConfig(e){return{name:e?.name||"",length:e?.length||this.defaultLength,onlyLowerCase:e?.onlyLowerCase??this.defaultOnlyLowerCase,style:e?.style||this.defaultStyle,urlSafe:e?.urlSafe??this.defaultUrlSafe}}getCharacterSet(e,t,r){if(e==="hex")return t?"0123456789abcdef":"0123456789ABCDEFabcdef";if(e==="alphanumeric")return t?"abcdefghijklmnopqrstuvwxyz0123456789":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";if(e==="extended")return r?t?"abcdefghijklmnopqrstuvwxyz0123456789-._~":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~":t?"abcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:";throw new Error(`Unknown ID style "${e} provided. Must be one of "extended" (default), "alphanumeric", or "hex".`)}generateId(e){let{length:t,onlyLowerCase:r,style:n,urlSafe:s}=e;if(t<0||t===0)throw new Error("ID length cannot be negative");let o=this.getCharacterSet(n,r,s),i=(2<<Math.log(o.length-1)/Math.LN2)-1,a=Math.ceil(1.6*i*t/o.length),c="";for(;c.length<t;){let d=new Uint8Array(a);vt(d);for(let l=0;l<a;l++){let u=d[l]&i;if(u<o.length&&(c+=o[u],c.length===t))break}}return c}};var xt=8,Ct=40,St=/^[a-zA-Z0-9_-]{1,40}$/;function Et(){return new q().create(xt,"alphanumeric",!1,!0)}function Pt(e){return St.test(e)}function It(e){if(!Pt(e))throw new Error(`Invalid ID format: "${e}". IDs must be 1-${Ct} characters using only alphanumeric characters, underscores, and hyphens.`)}function Q(e){return e?(It(e),e):Et()}var tt=class{requests=new Map;limit;windowMs;constructor(e=100,t=60){this.limit=e,this.windowMs=t*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(e){let t=Date.now(),r=e||"unknown",n=this.requests.get(r);return(!n||n.resetTime<t)&&(n={count:0,resetTime:t+this.windowMs},this.requests.set(r,n)),n.count++,n.count<=this.limit}getRemainingRequests(e){let t=Date.now(),r=e||"unknown",n=this.requests.get(r);return!n||n.resetTime<t?this.limit:Math.max(0,this.limit-n.count)}getResetTime(e){let t=Date.now(),r=e||"unknown",n=this.requests.get(r);return!n||n.resetTime<t?Math.floor((t+this.windowMs)/1e3):Math.floor(n.resetTime/1e3)}cleanup(){let e=Date.now();for(let[t,r]of this.requests.entries())r.resetTime<e&&this.requests.delete(t)}};import{URL as Tt}from"url";var et=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(e){return this.globalMiddlewares.push(e),this}get(e,...t){let r=t.pop();return this.register("GET",e,r,t)}post(e,...t){let r=t.pop();return this.register("POST",e,r,t)}put(e,...t){let r=t.pop();return this.register("PUT",e,r,t)}delete(e,...t){let r=t.pop();return this.register("DELETE",e,r,t)}patch(e,...t){let r=t.pop();return this.register("PATCH",e,r,t)}any(e,...t){let r=t.pop(),n=t;return this.register("GET",e,r,n),this.register("POST",e,r,n),this.register("PUT",e,r,n),this.register("DELETE",e,r,n),this.register("PATCH",e,r,n),this.register("OPTIONS",e,r,n),this}options(e,...t){let r=t.pop();return this.register("OPTIONS",e,r,t)}match(e,t){for(let r of this.routes){if(r.method!==e)continue;let n=this.pathPatterns.get(r.path);if(!n)continue;let s=n.pattern.exec(t);if(!s)continue;let o={};return n.paramNames.forEach((i,a)=>{o[i]=s[a+1]||""}),{route:r,params:o}}return null}async handle(e,t){let r=e.method||"GET",n=new Tt(e.url||"/",`http://${e.headers.host}`),s=n.pathname,o=this.match(r,s);if(!o)return null;let{route:i,params:a}=o,c={};n.searchParams.forEach((u,h)=>{c[h]=u});let d={req:e,res:t,params:a,query:c,body:e.body||{},headers:e.headers,path:s,state:{},raw:()=>t,binary:(u,h="application/octet-stream",f=200)=>({statusCode:f,body:u,headers:{"Content-Type":h,"Content-Length":u.length.toString()},isRaw:!0}),text:(u,h=200)=>({statusCode:h,body:u,headers:{"Content-Type":"text/plain"}}),form:(u,h=200)=>({statusCode:h,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(u,h=200)=>({statusCode:h,body:u,headers:{"Content-Type":"application/json"}}),html:(u,h=200)=>({statusCode:h,body:u,headers:{"Content-Type":"text/html"}}),redirect:(u,h=302)=>({statusCode:h,body:null,headers:{Location:u}}),status:function(u){return{raw:()=>t,binary:(h,f="application/octet-stream")=>({statusCode:u,body:h,headers:{"Content-Type":f,"Content-Length":h.length.toString()},isRaw:!0}),text:h=>({statusCode:u,body:h,headers:{"Content-Type":"text/plain"}}),json:h=>({statusCode:u,body:h,headers:{"Content-Type":"application/json"}}),html:h=>({statusCode:u,body:h,headers:{"Content-Type":"text/html"}}),form:h=>({statusCode:u,body:h,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(h,f=302)=>({statusCode:f,body:null,headers:{Location:h}}),status:h=>this.status(h)}}},l=[...this.globalMiddlewares,...i.middlewares];return this.executeMiddlewareChain(d,l,i.handler)}register(e,t,r,n=[]){return this.routes.push({method:e,path:t,handler:r,middlewares:n}),this.pathPatterns.set(t,this.createPathPattern(t)),this}createPathPattern(e){let t=[],r=e.replace(/\/:[^/]+/g,n=>{let s=n.slice(2);return t.push(s),"/([^/]+)"});return r.endsWith("/*")?(r=`${r.slice(0,-2)}(?:/(.*))?`,t.push("wildcard")):r=r.replace(/\/$/,"/?"),{pattern:new RegExp(`^${r}$`),paramNames:t}}async executeMiddlewareChain(e,t,r){let n=0,s=async()=>{if(n<t.length){let o=t[n++];return o(e,s)}return r(e)};return s()}};var $=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:At(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function At(e){return e==="true"||e===!0}var B=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as jt,readFileSync as Ft}from"node:fs";var V=class{config={};options=[];validators=[];autoValidate=!0;constructor(e){let t=e?.configFilePath,r=e?.args||[],n=e?.config||{};this.options=e?.options||[],this.validators=e?.validators||[],e?.autoValidate!==void 0&&(this.autoValidate=e.autoValidate),this.config=this.createConfig(t,r,n)}deepMerge(e,t){let r={...e};for(let n in t)t[n]!==void 0&&(t[n]!==null&&typeof t[n]=="object"&&!Array.isArray(t[n])&&n in e&&e[n]!==null&&typeof e[n]=="object"&&!Array.isArray(e[n])?r[n]=this.deepMerge(e[n],t[n]):t[n]!==void 0&&(r[n]=t[n]));return r}setValueAtPath(e,t,r){let n=t.split("."),s=e;for(let i=0;i<n.length-1;i++){let a=n[i];!(a in s)||s[a]===null?s[a]={}:typeof s[a]!="object"&&(s[a]={}),s=s[a]}let o=n[n.length-1];s[o]=r}getValueAtPath(e,t){let r=t.split("."),n=e;for(let s of r){if(n==null)return;n=n[s]}return n}createConfig(e,t=[],r={}){let n={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(n,a.path,a.defaultValue);let s={};if(e&&jt(e))try{let a=Ft(e,"utf8");s=JSON.parse(a),console.log(`Loaded configuration from ${e}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let o=this.parseCliArgs(t),i=this.deepMerge({},n);return i=this.deepMerge(i,s),i=this.deepMerge(i,r),i=this.deepMerge(i,o),i}parseCliArgs(e){let t={},r=e[0]?.endsWith("node")||e[0]?.endsWith("node.exe")?2:0;for(;r<e.length;){let n=e[r++],s=this.options.find(o=>o.flag===n);if(s)if(s.isFlag)this.setValueAtPath(t,s.path,!0);else if(r<e.length&&!e[r].startsWith("-")){let o=e[r++];if(s.parser)try{o=s.parser(o)}catch(i){console.error(`Error parsing value for ${s.flag}: ${i instanceof Error?i.message:String(i)}`);continue}if(s.validator){let i=s.validator(o);if(i!==!0&&typeof i=="string"){console.error(`Invalid value for ${s.flag}: ${i}`);continue}if(i===!1){console.error(`Invalid value for ${s.flag}`);continue}}this.setValueAtPath(t,s.path,o)}else console.error(`Missing value for option ${n}`)}return t}validate(){for(let e of this.validators){let t=this.getValueAtPath(this.config,e.path),r=e.validator(t,this.config);if(r===!1)throw new B(e.message);if(typeof r=="string")throw new B(r)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(e,t){let r=this.getValueAtPath(this.config,e);return r!==void 0?r:t}setValue(e,t){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=this.getValueAtPath(this.config,e)||{};if(typeof r=="object"&&!Array.isArray(r)){let n=this.deepMerge(r,t);this.setValueAtPath(this.config,e,n);return}}this.setValueAtPath(this.config,e,t)}getHelpText(){let e=`Available configuration options:
2
+ import{existsSync as q}from"node:fs";import{join as k}from"node:path";import{mkdir as Ye,writeFile as se,readFile as Pe,unlink as Ke}from"node:fs/promises";import{pathToFileURL as Te}from"node:url";var oe=class{requests=new Map;limit;windowMs;constructor(t=100,e=60){this.limit=t,this.windowMs=e*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return(!n||n.resetTime<e)&&(n={count:0,resetTime:e+this.windowMs},this.requests.set(r,n)),n.count++,n.count<=this.limit}getRemainingRequests(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return!n||n.resetTime<e?this.limit:Math.max(0,this.limit-n.count)}getResetTime(t){let e=Date.now(),r=t||"unknown",n=this.requests.get(r);return!n||n.resetTime<e?Math.floor((e+this.windowMs)/1e3):Math.floor(n.resetTime/1e3)}cleanup(){let t=Date.now();for(let[e,r]of this.requests.entries())r.resetTime<t&&this.requests.delete(e)}};import{URL as Ie}from"url";var ae=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(t){return this.globalMiddlewares.push(t),this}get(t,...e){let r=e.pop();return this.register("GET",t,r,e)}post(t,...e){let r=e.pop();return this.register("POST",t,r,e)}put(t,...e){let r=e.pop();return this.register("PUT",t,r,e)}delete(t,...e){let r=e.pop();return this.register("DELETE",t,r,e)}patch(t,...e){let r=e.pop();return this.register("PATCH",t,r,e)}any(t,...e){let r=e.pop(),n=e;return this.register("GET",t,r,n),this.register("POST",t,r,n),this.register("PUT",t,r,n),this.register("DELETE",t,r,n),this.register("PATCH",t,r,n),this.register("OPTIONS",t,r,n),this}options(t,...e){let r=e.pop();return this.register("OPTIONS",t,r,e)}match(t,e){for(let r of this.routes){if(r.method!==t)continue;let n=this.pathPatterns.get(r.path);if(!n)continue;let s=n.pattern.exec(e);if(!s)continue;let i={};return n.paramNames.forEach((o,a)=>{i[o]=s[a+1]||""}),{route:r,params:i}}return null}async handle(t,e){let r=t.method||"GET",n=new Ie(t.url||"/",`http://${t.headers.host}`),s=n.pathname,i=this.match(r,s);if(!i)return null;let{route:o,params:a}=i,c={};n.searchParams.forEach((u,d)=>{c[d]=u});let f={req:t,res:e,params:a,query:c,body:t.body||{},headers:t.headers,path:s,state:{},raw:()=>e,binary:(u,d="application/octet-stream",p=200)=>({statusCode:p,body:u,headers:{"Content-Type":d,"Content-Length":u.length.toString()},isRaw:!0}),text:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/plain"}}),form:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"application/json"}}),html:(u,d=200)=>({statusCode:d,body:u,headers:{"Content-Type":"text/html"}}),redirect:(u,d=302)=>({statusCode:d,body:null,headers:{Location:u}}),status:function(u){return{raw:()=>e,binary:(d,p="application/octet-stream")=>({statusCode:u,body:d,headers:{"Content-Type":p,"Content-Length":d.length.toString()},isRaw:!0}),text:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/plain"}}),json:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/json"}}),html:d=>({statusCode:u,body:d,headers:{"Content-Type":"text/html"}}),form:d=>({statusCode:u,body:d,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(d,p=302)=>({statusCode:p,body:null,headers:{Location:d}}),status:d=>this.status(d)}}},l=[...this.globalMiddlewares,...o.middlewares];return this.executeMiddlewareChain(f,l,o.handler)}register(t,e,r,n=[]){return this.routes.push({method:t,path:e,handler:r,middlewares:n}),this.pathPatterns.set(e,this.createPathPattern(e)),this}createPathPattern(t){let e=[],r=t.replace(/\/:[^/]+/g,n=>{let s=n.slice(2);return e.push(s),"/([^/]+)"});return r.endsWith("/*")?(r=`${r.slice(0,-2)}(?:/(.*))?`,e.push("wildcard")):r=r.replace(/\/$/,"/?"),{pattern:new RegExp(`^${r}$`),paramNames:e}}async executeMiddlewareChain(t,e,r){let n=0,s=async()=>{if(n<e.length){let i=e[n++];return i(t,s)}return r(t)};return s()}};var M=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:Fe(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function Fe(t){return t==="true"||t===!0}var V=class extends Error{constructor(t){super(t),this.name="ValidationError",this.message=t||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as Ae,readFileSync as Re}from"node:fs";var z=class{config={};options=[];validators=[];autoValidate=!0;constructor(t){let e=t?.configFilePath,r=t?.args||[],n=t?.config||{};this.options=t?.options||[],this.validators=t?.validators||[],t?.autoValidate!==void 0&&(this.autoValidate=t.autoValidate),this.config=this.createConfig(e,r,n)}deepMerge(t,e){let r={...t};for(let n in e)e[n]!==void 0&&(e[n]!==null&&typeof e[n]=="object"&&!Array.isArray(e[n])&&n in t&&t[n]!==null&&typeof t[n]=="object"&&!Array.isArray(t[n])?r[n]=this.deepMerge(t[n],e[n]):e[n]!==void 0&&(r[n]=e[n]));return r}setValueAtPath(t,e,r){let n=e.split("."),s=t;for(let o=0;o<n.length-1;o++){let a=n[o];!(a in s)||s[a]===null?s[a]={}:typeof s[a]!="object"&&(s[a]={}),s=s[a]}let i=n[n.length-1];s[i]=r}getValueAtPath(t,e){let r=e.split("."),n=t;for(let s of r){if(n==null)return;n=n[s]}return n}createConfig(t,e=[],r={}){let n={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(n,a.path,a.defaultValue);let s={};if(t&&Ae(t))try{let a=Re(t,"utf8");s=JSON.parse(a),console.log(`Loaded configuration from ${t}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let i=this.parseCliArgs(e),o=this.deepMerge({},n);return o=this.deepMerge(o,s),o=this.deepMerge(o,r),o=this.deepMerge(o,i),o}parseCliArgs(t){let e={},r=t[0]?.endsWith("node")||t[0]?.endsWith("node.exe")?2:0;for(;r<t.length;){let n=t[r++],s=this.options.find(i=>i.flag===n);if(s)if(s.isFlag)this.setValueAtPath(e,s.path,!0);else if(r<t.length&&!t[r].startsWith("-")){let i=t[r++];if(s.parser)try{i=s.parser(i)}catch(o){console.error(`Error parsing value for ${s.flag}: ${o instanceof Error?o.message:String(o)}`);continue}if(s.validator){let o=s.validator(i);if(o!==!0&&typeof o=="string"){console.error(`Invalid value for ${s.flag}: ${o}`);continue}if(o===!1){console.error(`Invalid value for ${s.flag}`);continue}}this.setValueAtPath(e,s.path,i)}else console.error(`Missing value for option ${n}`)}return e}validate(){for(let t of this.validators){let e=this.getValueAtPath(this.config,t.path),r=t.validator(e,this.config);if(r===!1)throw new V(t.message);if(typeof r=="string")throw new V(r)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(t,e){let r=this.getValueAtPath(this.config,t);return r!==void 0?r:e}setValue(t,e){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let r=this.getValueAtPath(this.config,t)||{};if(typeof r=="object"&&!Array.isArray(r)){let n=this.deepMerge(r,e);this.setValueAtPath(this.config,t,n);return}}this.setValueAtPath(this.config,t,e)}getHelpText(){let t=`Available configuration options:
3
3
 
4
- `;for(let t of this.options)e+=`${t.flag}${t.isFlag?"":" <value>"}
5
- `,t.description&&(e+=` ${t.description}
6
- `),t.defaultValue!==void 0&&(e+=` Default: ${JSON.stringify(t.defaultValue)}
7
- `),e+=`
8
- `;return e}};var z={int:e=>{let t=e.trim();if(!/^[+-]?\d+$/.test(t))throw new Error(`Cannot parse "${e}" as an integer`);let r=Number.parseInt(t,10);if(Number.isNaN(r))throw new Error(`Cannot parse "${e}" as an integer`);return r},float:e=>{let t=e.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)){if(t==="Infinity"||t==="-Infinity")return t==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${e}" as a number`)}let r=Number.parseFloat(t);if(Number.isNaN(r))throw new Error(`Cannot parse "${e}" as a number`);return r},boolean:e=>{let t=e.trim().toLowerCase();if(["true","yes","1","y"].includes(t))return!0;if(["false","no","0","n"].includes(t))return!1;throw new Error(`Cannot parse "${e}" as a boolean`)},array:e=>e.split(",").map(t=>t.trim()),json:e=>{try{return JSON.parse(e)}catch{throw new Error(`Cannot parse "${e}" as JSON`)}}};var b=$(),rt=e=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:b.port},{flag:"--host",path:"host",defaultValue:b.host},{flag:"--https",path:"useHttps",defaultValue:b.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:b.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:b.sslCert},{flag:"--key",path:"sslKey",defaultValue:b.sslKey},{flag:"--ca",path:"sslCa",defaultValue:b.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:b.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:b.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:b.allowedDomains,parser:z.array},{flag:"--debug",path:"debug",defaultValue:b.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:b.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:b.requestTimeout}],config:e});function nt(e,t){let r=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new Error("Invalid multipart/form-data: missing boundary");let n=r[1]||r[2],s=Buffer.from(`--${n}`),o=Buffer.from(`--${n}--`),i={},a={},c=Rt(e,s);for(let d of c){if(d.length===0||d.equals(o.subarray(s.length)))continue;let l=$t(d);if(!l)continue;let{name:u,filename:h,contentType:f,data:m}=l;if(h){let p={filename:h,contentType:f||"application/octet-stream",data:m,size:m.length};a[u]?Array.isArray(a[u])?a[u].push(p):a[u]=[a[u],p]:a[u]=p}else{let p=m.toString("utf8");i[u]?Array.isArray(i[u])?i[u].push(p):i[u]=[i[u],p]:i[u]=p}}return{fields:i,files:a}}function Rt(e,t){let r=[],n=0;for(;n<e.length;){let s=e.indexOf(t,n);if(s===-1)break;n!==s&&r.push(e.subarray(n,s)),n=s+t.length,n<e.length&&e[n]===13&&e[n+1]===10&&(n+=2)}return r}function $t(e){let t=Buffer.from(`\r
4
+ `;for(let e of this.options)t+=`${e.flag}${e.isFlag?"":" <value>"}
5
+ `,e.description&&(t+=` ${e.description}
6
+ `),e.defaultValue!==void 0&&(t+=` Default: ${JSON.stringify(e.defaultValue)}
7
+ `),t+=`
8
+ `;return t}};var G={int:t=>{let e=t.trim();if(!/^[+-]?\d+$/.test(e))throw new Error(`Cannot parse "${t}" as an integer`);let r=Number.parseInt(e,10);if(Number.isNaN(r))throw new Error(`Cannot parse "${t}" as an integer`);return r},float:t=>{let e=t.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e)){if(e==="Infinity"||e==="-Infinity")return e==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${t}" as a number`)}let r=Number.parseFloat(e);if(Number.isNaN(r))throw new Error(`Cannot parse "${t}" as a number`);return r},boolean:t=>{let e=t.trim().toLowerCase();if(["true","yes","1","y"].includes(e))return!0;if(["false","no","0","n"].includes(e))return!1;throw new Error(`Cannot parse "${t}" as a boolean`)},array:t=>t.split(",").map(e=>e.trim()),json:t=>{try{return JSON.parse(t)}catch{throw new Error(`Cannot parse "${t}" as JSON`)}}};var b=M(),ce=t=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:b.port},{flag:"--host",path:"host",defaultValue:b.host},{flag:"--https",path:"useHttps",defaultValue:b.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:b.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:b.sslCert},{flag:"--key",path:"sslKey",defaultValue:b.sslKey},{flag:"--ca",path:"sslCa",defaultValue:b.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:b.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:b.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:b.allowedDomains,parser:G.array},{flag:"--debug",path:"debug",defaultValue:b.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:b.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:b.requestTimeout}],config:t});function ue(t,e){let r=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new Error("Invalid multipart/form-data: missing boundary");let n=r[1]||r[2],s=Buffer.from(`--${n}`),i=Buffer.from(`--${n}--`),o={},a={},c=je(t,s);for(let f of c){if(f.length===0||f.equals(i.subarray(s.length)))continue;let l=$e(f);if(!l)continue;let{name:u,filename:d,contentType:p,data:h}=l;if(d){let g={filename:d,contentType:p||"application/octet-stream",data:h,size:h.length};a[u]?Array.isArray(a[u])?a[u].push(g):a[u]=[a[u],g]:a[u]=g}else{let g=h.toString("utf8");o[u]?Array.isArray(o[u])?o[u].push(g):o[u]=[o[u],g]:o[u]=g}}return{fields:o,files:a}}function je(t,e){let r=[],n=0;for(;n<t.length;){let s=t.indexOf(e,n);if(s===-1)break;n!==s&&r.push(t.subarray(n,s)),n=s+e.length,n<t.length&&t[n]===13&&t[n+1]===10&&(n+=2)}return r}function $e(t){let e=Buffer.from(`\r
9
9
  \r
10
- `),r=e.indexOf(t);if(r===-1)return null;let n=e.subarray(0,r),s=e.subarray(r+4),i=n.toString("utf8").split(`\r
11
- `),a="",c="",d,l;for(let h of i){let f=h.toLowerCase();if(f.startsWith("content-disposition:")){a=h.substring(20).trim();let m=a.match(/name="([^"]+)"/);m&&(c=m[1]);let p=a.match(/filename="([^"]+)"/);p&&(d=p[1])}else f.startsWith("content-type:")&&(l=h.substring(13).trim())}if(!c)return null;let u=s;return u.length>=2&&u[u.length-2]===13&&u[u.length-1]===10&&(u=u.subarray(0,u.length-2)),{disposition:a,name:c,filename:d,contentType:l,data:u}}import{readFileSync as P}from"fs";import G from"http";import Ot from"http2";import Ht from"https";var J=class{config;rateLimiter;router;shutdownHandlers=[];constructor(e){let t=new V(rt(e||{})).get();t.debug&&console.log("Using configuration:",t),this.config=t,this.router=new et;let r=t.rateLimit.requestsPerMinute||$().rateLimit.requestsPerMinute;this.rateLimiter=new tt(r,60),t.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(e){return this.router.use(e),this}get(e,...t){return this.router.get(e,...t),this}post(e,...t){return this.router.post(e,...t),this}put(e,...t){return this.router.put(e,...t),this}delete(e,...t){return this.router.delete(e,...t),this}patch(e,...t){return this.router.patch(e,...t),this}any(e,...t){return this.router.any(e,...t),this}options(e,...t){return this.router.options(e,...t),this}start(){let e=this.createServer(),{port:t,host:r}=this.config;return this.setupGracefulShutdown(e),e.listen(t,r,()=>{let n=e.address(),s=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${s}://${n.address!=="::"?n.address:"localhost"}:${n.port}`)}),e}createServer(){let e=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let t={key:P(this.config.sslKey),cert:P(this.config.sslCert),...this.config.sslCa?{ca:P(this.config.sslCa)}:{}};return Ot.createSecureServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let t={key:P(this.config.sslKey),cert:P(this.config.sslCert),...this.config.sslCa?{ca:P(this.config.sslCa)}:{}};return Ht.createServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}return G.createServer(e)}async rateLimitMiddleware(e,t){let r=e.req.socket.remoteAddress||"unknown";return e.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),e.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(r).toString()),e.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(r).toString()),this.rateLimiter.isAllowed(r)?t():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(e,t){let r=Date.now(),n=e.method||"UNKNOWN",s=e.url||"/unknown",o=this.config.debug;try{if(this.setCorsHeaders(t,e),this.setSecurityHeaders(t,this.config.useHttps),o&&console.log(`${n} ${s}`),e.method==="OPTIONS"){if(t instanceof G.ServerResponse)t.statusCode=204,t.end();else{let a=t;a.writeHead(204),a.end()}return}try{e.body=await this.parseBody(e)}catch(a){return o&&console.error("Body parsing error:",a.message),this.respond(t,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let i=await this.router.handle(e,t);return i?i._handled?void 0:this.respond(t,i):this.respond(t,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(i){return console.error("Server error:",i),this.respond(t,{statusCode:500,body:{error:"Internal Server Error",message:o?i.message:"An unexpected error occurred"}})}finally{o&&this.logDuration(r,n,s)}}logDuration(e,t,r){let n=Date.now()-e;console.log(`${t} ${r} completed in ${n}ms`)}async parseBody(e){return new Promise((t,r)=>{let n=[],s=0,o=this.config.maxBodySize,i=!1,a=null,c=this.config.debug,d=e.headers["content-type"]||"";c&&console.log("Content-Type:",d),this.config.requestTimeout>0&&(a=setTimeout(()=>{i||(i=!0,c&&console.log("Request timeout exceeded"),r(new Error("Request timeout")))},this.config.requestTimeout));let l=()=>{a&&(clearTimeout(a),a=null)};e.on("data",u=>{if(!i){if(s+=u.length,c&&console.log(`Received chunk: ${u.length} bytes, total size: ${s}`),s>o){i=!0,l(),c&&console.log(`Body size exceeded limit: ${s} > ${o}`),r(new Error("Request body too large"));return}n.push(u)}}),e.on("end",()=>{if(!i){i=!0,l(),c&&console.log(`Request body complete: ${s} bytes`);try{if(n.length>0){let u=Buffer.concat(n);if(d.includes("application/json"))try{let h=u.toString("utf8");t(JSON.parse(h))}catch(h){r(new Error(`Invalid JSON in request body: ${h.message}`))}else if(d.includes("application/x-www-form-urlencoded")){let h=u.toString("utf8"),f={};new URLSearchParams(h).forEach((m,p)=>{f[p]=m}),t(f)}else if(d.includes("multipart/form-data"))try{let h=nt(u,d);t(h)}catch(h){r(new Error(`Invalid multipart form data: ${h.message}`))}else this.isBinaryContentType(d)?t(u):t(u.toString("utf8"))}else t({})}catch(u){r(new Error(`Invalid request body: ${u}`))}}}),e.on("error",u=>{i||(i=!0,l(),r(new Error(`Error reading request body: ${u.message}`)))}),e.on("close",()=>{l()})})}isBinaryContentType(e){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(r=>e.includes(r))}setCorsHeaders(e,t){let r=t.headers.origin,{allowedDomains:n=["*"]}=this.config;!r||n.length===0||n.includes("*")?e.setHeader("Access-Control-Allow-Origin","*"):n.includes(r)&&(e.setHeader("Access-Control-Allow-Origin",r),e.setHeader("Vary","Origin")),e.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(e,t=!1){let r={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((t||this.config.useHttp2)&&(r["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),e instanceof G.ServerResponse)Object.entries(r).forEach(([n,s])=>{e.setHeader(n,s)});else{let n=e;Object.entries(r).forEach(([s,o])=>{n.setHeader(s,o)})}}respond(e,t){let r={...t.headers||{}};(s=>typeof s.writeHead=="function"&&typeof s.end=="function")(e)?(e.writeHead(t.statusCode,r),t.body===null||t.body===void 0?e.end():t.isRaw||typeof t.body=="string"?e.end(t.body):e.end(JSON.stringify(t.body))):(console.warn("Unexpected response object type without writeHead/end methods"),e.writeHead?.(t.statusCode,r),t.body===null||t.body===void 0?e.end?.():t.isRaw||typeof t.body=="string"?e.end?.(t.body):e.end?.(JSON.stringify(t.body)))}setupGracefulShutdown(e){let t=i=>{console.log("Shutting down MikroServe server..."),i&&console.error("Error:",i),this.cleanupShutdownHandlers(),e.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(i?1:0))})},r=()=>t(),n=()=>t(),s=i=>t(i),o=i=>t(i);this.shutdownHandlers=[r,n,s,o],process.on("SIGINT",r),process.on("SIGTERM",n),process.on("uncaughtException",s),process.on("unhandledRejection",o)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[e,t,r,n]=this.shutdownHandlers;process.removeListener("SIGINT",e),process.removeListener("SIGTERM",t),process.removeListener("uncaughtException",r),process.removeListener("unhandledRejection",n),this.shutdownHandlers=[]}}};var y=class extends Error{constructor(t){super(),this.name="ValidationError",this.message=t||"Invalid input",this.cause={statusCode:400}}};var O=class extends Error{constructor(t){super(),this.name="NotFoundError",this.message=t||"Resource not found",this.cause={statusCode:404}}};var A=class extends Error{constructor(t){super(),this.name="InvalidMethodError",this.message=t||"Invalid HTTP method",this.cause={statusCode:400}}};var H=class extends Error{constructor(t){super(),this.name="ServiceRequestError",this.message=t||"Service request failed",this.cause={statusCode:502}}};var M=class{generatePermissionsFromBindings(t){let r=[];for(let n of t){let s=n.service;for(let o of n.permissions){if(!o.resource){r.push(`${s}.*`);continue}let i=o.resource,a=o.actions||["*"];if(o.targets&&o.targets.length>0)for(let c of a)for(let d of o.targets)r.push(`${s}.${i}.${c}:${d}`);else for(let c of a)r.push(`${s}.${i}.${c}`)}}return[...new Set(r)]}validateBindings(t){let r=["databases","storage","observability","sites","functions"];for(let n of t){if(!r.includes(n.service))throw new y(`Invalid service: ${n.service}. Must be one of: ${r.join(", ")}`);if(!n.permissions||n.permissions.length===0)throw new y("Bindings must have at least one permission");for(let s of n.permissions)if(s.targets&&s.targets.length>0){if(!s.resource)throw new y("Action-level bindings (with targets) must specify resource");if(!s.actions||s.actions.length===0)throw new y("Action-level bindings (with targets) must specify actions")}}}};var _=class{constructor(t,r,n){this.baseUrl=t;this.authToken=r;this.bindings=n}async request(t,r,n,s){let o=`${this.baseUrl}${r}`;if(s){let u=new URLSearchParams(s);o+=`?${u.toString()}`}let i={"Content-Type":"application/json"};this.authToken&&(i.Authorization=`Bearer ${this.authToken}`),this.bindings&&this.bindings.length>0&&(i["X-Function-Bindings"]=JSON.stringify(this.bindings));let a={method:t,headers:i};n&&(a.body=JSON.stringify(n));let c=await fetch(o,a),d=c.headers.get("content-type"),l;if(d?.includes("application/json")){let u=await c.text();u?l=JSON.parse(u):l=null}else l=await c.text();if(!c.ok)throw new H(`Service request failed (${c.status}): ${typeof l=="string"?l:JSON.stringify(l)}`);return l}},W=class extends _{async get(t,r){return this.request("POST","/get",{tableName:t,key:r})}async write(t,r,n,s,o){return this.request("POST","/write",{tableName:t,key:r,value:n,expiration:s,dictionaryName:o})}async delete(t,r){return this.request("DELETE","/delete",void 0,{tableName:t,key:r})}async listTables(){return this.request("GET","/tables")}async getTableSize(t){return this.request("GET","/table",void 0,{tableName:t})}async getTableInfo(t){return this.request("GET",`/tables/${t}`)}async createTable(t){return this.request("POST",`/tables/${t}`)}async deleteTable(t){return this.request("DELETE",`/tables/${t}`)}},k=class{constructor(t,r){this.serviceBaseUrls=t;this.authToken=r}createBindings(t){let r={};for(let n of t){let s=this.serviceBaseUrls[n.service];s&&n.service==="databases"&&(r.databases=new W(s,this.authToken,t))}return r}};import{EventEmitter as Mt}from"node:events";var X=class e{static instance;constructor(){}static getInstance(){return e.instance||(e.instance=new Mt,e.instance.setMaxListeners(100)),e.instance}};function Z(){return X.getInstance()}function st(e){let t=Z();try{t.emit("function.log",e)}catch(r){console.error("Failed to emit function log event:",r)}}async function I(e){return e.body||{}}var j=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:r,errors:n}=this.validate(e.properties,t),s=this.compileErrors(r,n),o=this.isSuccessful(r,s);return{errors:s,success:o}}compileErrors(e,t){let r=e.filter(n=>n.success===!1);return[...t,...r].flatMap(n=>n)}isSuccessful(e,t){return e.every(r=>r.success===!0)&&t.length===0}validate(e,t,r=[],n=[]){let s=e?.additionalProperties??!0,o=e?.required||[];n=this.checkForRequiredKeysErrors(o,t,n),n=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),n,s);for(let i in e){let a=o.includes(i)&&i!=="required",c=e[i],d=t[i],l=c.additionalProperties??!0;a&&(n=this.checkForRequiredKeysErrors(c.required||[],d,n)),this.isDefined(d)&&(this.handleValidation(i,d,c,r),n=this.checkForDisallowedProperties(Object.keys(d),Object.keys(c),n,l),this.handleNestedObject(d,c,r,n))}return{results:r,errors:n}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,r){if(!this.areRequiredKeysPresent(e,t)){let n=t?Object.keys(t):[],s=this.findNonOverlappingElements(e,n),o=s.length>0?`Missing the required key: '${s.join(", ")}'!`:`Missing values for required keys: '${n.filter(i=>!t[i]).join(", ")}'!`;r.push({key:"",value:t,success:!1,error:o})}return r}checkForDisallowedProperties(e,t,r,n){if(!n){let s=this.findNonOverlappingElements(e,t);s.length>0&&r.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${s.join(", ")}'!`})}return r}handleValidation(e,t,r,n){this.updatePropertyPath(e);let s=this.validateProperty(this.propertyPath,r,t);n.push(...s);let o=(a,c)=>{a.forEach(d=>{let l=this.validateProperty(this.propertyPath,c.items,d);n.push(...l)}),this.updatePropertyPath()},i=a=>{let c=Object.keys(a),d=this.propertyPath;c.forEach(l=>{if(this.updatePropertyPath(l,d),this.isArray(a[l])&&r[l]?.items!=null)o(a[l],r[l]);else{let u=this.validateProperty(this.propertyPath,r[l],a[l]);n.push(...u)}})};this.isArray(t)&&r.items!=null?o(t,r):this.isObject(t)?i(t):this.updatePropertyPath()}handleNestedObject(e,t,r,n){if(this.isObject(e)){let s=this.getNestedObjects(e);for(let o of s){let i=t[o],a=e[o];i&&typeof a=="object"&&this.validate(i,a,r,n)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(r=>!t.includes(r))}areRequiredKeysPresent(e,t=[]){return e.every(r=>Object.keys(t).includes(r)?this.isDefined(t[r]):!1)}validateProperty(e,t,r){return this.validateInput(t,r).map(s=>{let{success:o,error:i}=s;return{key:e,value:r,success:o,error:i??""}})}validateInput(e,t){if(e){let r=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],n=[];for(let s of r)s.condition()&&!s.validator()&&n.push({success:!1,error:s.error});return n}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(r=>{switch(r){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let r in e){let n=e[r];t.properties.required.push(r),Array.isArray(n)?t.properties[r]=this.generateArraySchema(n):typeof n=="object"&&n!==null?t.properties[r]=this.generateNestedObjectSchema(n):t.properties[r]=this.generatePropertySchema(n)}return t}generateArraySchema(e){let t={type:"array"},r=e.filter(n=>n);if(r.length>0){let n=r[0];r.every(o=>typeof o==typeof n)?typeof n=="object"&&!Array.isArray(n)?t.items=this.generateNestedObjectSchema(n):t.items=this.generatePropertySchema(n):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let r in e){let n=e[r];t.required.push(r),typeof n=="object"&&!Array.isArray(n)&&n!==null?t[r]=this.generateNestedObjectSchema(n):t[r]=this.generatePropertySchema(n)}return t}generatePropertySchema(e){let t=typeof e,r={type:t};return t==="string"&&(r.minLength=1),r}};function w(e,t="An error occurred"){let r=e?.message||e||t,n=e?.cause?.statusCode||e?.statusCode||400;return{message:r,status:n}}function ot(e,t,r={}){let n=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let i=new Error("Unauthorized: User or roles missing");throw i.cause={statusCode:403},i}let s=e.roles.flatMap(i=>i?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(d=>typeof d=="string"?d:d&&typeof d=="object"&&d.actions?d.actions:[]))||[]);if(!n.every(i=>s.includes(i)||s.includes("*")?!0:s.some(a=>{if(a.endsWith(".*")){let c=a.slice(0,-2);return i.startsWith(`${c}.`)}return!1}))){let i=new Error("Unauthorized");throw i.cause={statusCode:403},i}return!0}function it(e,t,r,n,s){let o=e.find(c=>c.service===t);if(!o){let c=new Error(`Function bindings do not include access to service: ${t}`);throw c.cause={statusCode:403},c}if(!o.permissions||o.permissions.length===0)return;for(let c of o.permissions)if(!(c.resource&&c.resource!==r)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(n)){if(c.targets&&c.targets.length>0){if(!s)return;if(!c.targets.includes(s))continue}return}}let i=s?`:${s}`:"",a=new Error(`Function bindings do not allow: ${t}.${r}.${n}${i}`);throw a.cause={statusCode:403},a}async function v(e,t,r,n,s,o,i){if(!t)return null;let a=e.state.user;if(!a){let d=e.headers.authorization;if(!d){let u=new Error("Unauthorized: No authentication provided");throw u.cause={statusCode:401},u}let l=d.replace(/^Bearer\s+/i,"");if(a=await t.getUserFromToken(l),!a){let u=new Error("Unauthorized: Invalid token");throw u.cause={statusCode:401},u}}ot(a,r,{});let c=e.headers["x-function-bindings"];if(c)try{let d=Array.isArray(c)?c[0]:c,l=JSON.parse(d);it(l,n,s,o,i)}catch(d){if(d.cause?.statusCode===403)throw d;let l=new Error("Invalid function bindings header");throw l.cause={statusCode:400},l}return a}var at={properties:{id:{type:"string",minLength:1,maxLength:40,pattern:"^[a-zA-Z0-9_-]{1,40}$"},name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"},context:{type:"string",minLength:1}},required:["name","code"],additionalProperties:!1};var Lt=new j(!0);async function ct(e,t,r){try{let n=await I(e),s=Lt.test(at,n);if(!s.success)return e.json({error:"Invalid input",details:s.errors},400);await v(e,r,"functions.function.create","functions","function","create");let{id:o,name:i,code:a,methods:c,bindings:d,passAllHeaders:l,allowUnauthenticated:u}=n,h=await t.deployFunction(i,a,c,d,l,u,o);return e.json({success:!0,function:h},201)}catch(n){let{message:s,status:o}=w(n,"Error deploying function");return e.json({error:s},o)}}async function ut(e,t,r){try{let n=e.params.functionId;if(!n)return e.json({error:"functionId is required"},400);let s=t.getFunction(n);return s?(s.allowUnauthenticated!==!0&&await v(e,r,"functions.function.execute","functions","function","execute",n),await t.executeFunction(n,e)):e.json({error:"Not Found",message:"Function not found"},404)}catch(n){let{message:s,status:o}=w(n,"Error executing function");return e.json({error:s},o)}}var lt={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var Ut=new j(!0);async function dt(e,t,r){try{let n=e.params.functionId,s=await I(e);if(!n)return e.json({error:"functionId is required"},400);let o=Ut.test(lt,s);if(!o.success)return e.json({error:"Invalid input",details:o.errors},400);await v(e,r,"functions.function.update","functions","function","update",n);let{code:i,methods:a,bindings:c,passAllHeaders:d,allowUnauthenticated:l}=s,u=await t.updateFunction(n,{code:i,methods:a,bindings:c,passAllHeaders:d,allowUnauthenticated:l});return u?e.json({success:!0,function:u},200):e.json({error:"Function not found"},404)}catch(n){let{message:s,status:o}=w(n,"Error updating function");return e.json({error:s},o)}}async function ft(e,t,r){try{let n=e.params.functionId;return n?(await v(e,r,"functions.function.delete","functions","function","delete",n),await t.deleteFunction(n)?e.json({success:!0,message:"Function deleted"},200):e.json({error:"Function not found"},404)):e.json({error:"functionId is required"},400)}catch(n){let{message:s,status:o}=w(n,"Error deleting function");return e.json({error:s},o)}}async function ht(e,t,r){try{let n=e.params.functionId;if(!n)return e.json({error:"functionId is required"},400);await v(e,r,"functions.function.get","functions","function","read",n);let s=t.getFunction(n);return s?e.json({success:!0,function:s},200):e.json({error:"Function not found"},404)}catch(n){let{message:s,status:o}=w(n,"Error getting function");return e.json({error:s},o)}}async function pt(e,t,r,n){try{await v(e,r,"functions.function.get","functions","function","read");let s=t.getFunctions(),o=e.query.context;if(o&&n){let i=e.headers.authorization?.replace(/^Bearer\s+/i,""),a=await n.listResourcesByType(o,"function",i);s=s.filter(c=>a.includes(c.id))}return e.json({success:!0,count:s.length,functions:s},200)}catch(s){let{message:o,status:i}=w(s,"Error listing functions");return e.json({error:o},i)}}import{readFileSync as Nt,existsSync as qt}from"node:fs";function T(){let e=process.env.MOLNOS_RUNTIME_CONFIG,t={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!e||!qt(e))return t;try{let r=Nt(e,"utf-8");return JSON.parse(r)}catch(r){return console.error("[loadRuntimeConfig] Failed to load runtime config:",r),t}}function mt(e,t){let r={enabled:!1,requestsPerMinute:0};if(!t)return r;let n=t.services?.[e];return n||(t.global?t.global:r)}function gt(e,t){let r=e?.api?.port;if(!r)throw new Error('Missing "port" input when create API service!');let n=T(),s=e?.dataPath||n.molnos.dataPath,o=e?.api?.host||n.server.host,i=e?.identityApiUrl!==void 0?e.identityApiUrl:n.identity.apiUrl,a=e?.contextApiUrl!==void 0?e.contextApiUrl:n.context.apiUrl,c=e?.debug||!1,d;return t&&(d=mt(t,n.molnos.rateLimit)),{dataPath:s,api:{port:r,host:o},...i?{identityApiUrl:i}:{},...a?{contextApiUrl:a}:{},...d?{rateLimit:d}:{},debug:c}}var L=class{baseUrl;authToken;constructor(t,r){this.baseUrl=t.replace(/\/$/,""),this.authToken=r}async createCustomRole(t,r,n,s){let o=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:t,name:r,description:n,permissions:s})});if(!o.ok){let i=`Failed to create role: ${o.statusText}`;try{i=(await o.json()).error||i}catch{i=await o.text().catch(()=>o.statusText)||i}throw new Error(i)}}async updateRole(t,r){let n=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let s=await n.json();throw new Error(s.error||`Failed to update role: ${n.statusText}`)}}async deleteRole(t){let r=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete role: ${r.statusText}`)}}async addServiceAccount(t,r,n){let s=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:t,description:r,roles:n})});if(!s.ok){let i=`Failed to create service account: ${s.statusText}`;try{i=(await s.json()).error||i}catch{i=await s.text().catch(()=>s.statusText)||i}throw new Error(i)}let o=await s.json();return{id:o.id,apiKey:o.apiKey}}async deleteIdentity(t){let r=await fetch(`${this.baseUrl}/identity/service-accounts/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete service account: ${r.statusText}`)}}async getUserFromToken(t){try{let r=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return r.ok?await r.json():null}catch{return null}}getHeaders(){let t={"Content-Type":"application/json"};return this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),t}};function yt(e){return e?new L(e):null}var D=class{baseUrl;constructor(t){this.baseUrl=t.replace(/\/$/,"")}async listResourcesByType(t,r,n){let s=`${this.baseUrl}/contexts/${encodeURIComponent(t)}`;try{let o={"Content-Type":"application/json"};n&&(o.Authorization=`Bearer ${n}`);let i=await fetch(s,{method:"GET",headers:o});if(!i.ok)return[];let c=(await i.json()).context?.resources||{};switch(r){case"function":return c.functions||[];case"database":return c.databases||[];case"storage":return c.storage||[];case"site":return c.sites||[];default:return[]}}catch{return[]}}};function bt(e){return e?new D(e):null}var K=class{functionsDir;functions=new Map;debug;bindingService;constructor(t){this.functionsDir=t.functionsDir||F(process.cwd(),"functions-data"),this.debug=t.debug||!1,this.bindingService=new M}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions()}getFunction(t){return this.functions.get(t)}getFunctions(){return Array.from(this.functions.values()).map(t=>({name:t.name,endpoint:t.endpoint,id:t.id,filePath:t.filePath,methods:t.methods,...t.bindings?{bindings:t.bindings}:{},...t.passAllHeaders!==void 0?{passAllHeaders:t.passAllHeaders}:{},...t.allowUnauthenticated!==void 0?{allowUnauthenticated:t.allowUnauthenticated}:{},createdAt:t.createdAt,updatedAt:t.updatedAt}))}async ensureFunctionsDirExists(){U(this.functionsDir)||await Bt(this.functionsDir,{recursive:!0})}async loadExistingFunctions(){try{let t=F(this.functionsDir,"functions.json");if(U(t)){let r=await wt(t,"utf8"),n=JSON.parse(r);for(let s of n)U(s.filePath)&&this.functions.set(s.id,s)}}catch{}}async saveFunctionsMetadata(){try{let t=F(this.functionsDir,"functions.json"),r=Array.from(this.functions.values());await Y(t,JSON.stringify(r,null,2),"utf8")}catch{}}async deployFunction(t,r,n,s,o,i,a){if(!t||typeof t!="string")throw new y("Function name is required and must be a string");if(!r||typeof r!="string")throw new y("Function code is required and must be a string");if(n!==void 0){if(!Array.isArray(n))throw new y("Methods must be an array");let f=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let m of n)if(!f.includes(m.toUpperCase()))throw new A(`Invalid HTTP method: ${m}. Must be one of: ${f.join(", ")}`)}s&&s.length>0&&this.bindingService.validateBindings(s);let c=Q(a),d=F(this.functionsDir,`${c}.mjs`),l=this.wrapFunctionCode(r);await Y(d,l,"utf8");let u=Date.now(),h={id:c,name:t,filePath:d,endpoint:`/functions/run/${c}`,...n&&n.length>0?{methods:n.map(f=>f.toUpperCase())}:{},...s?{bindings:s}:{},...o!==void 0?{passAllHeaders:o}:{},...i!==void 0?{allowUnauthenticated:i}:{},createdAt:u,updatedAt:u};return this.functions.set(c,h),await this.saveFunctionsMetadata(),h}async updateFunction(t,r){let n=this.functions.get(t);if(!n)throw new O(`Function with ID ${t} not found`);let{code:s,methods:o,bindings:i,passAllHeaders:a,allowUnauthenticated:c}=r;if(s===void 0&&o===void 0&&i===void 0&&a===void 0&&c===void 0)throw new y("At least one parameter (code, methods, bindings, passAllHeaders, or allowUnauthenticated) must be provided");if(s!==void 0&&(typeof s!="string"||!s))throw new y("Function code must be a non-empty string");if(o!==void 0){if(!Array.isArray(o))throw new y("Methods must be an array");let d=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let l of o)if(!d.includes(l.toUpperCase()))throw new A(`Invalid HTTP method: ${l}. Must be one of: ${d.join(", ")}`)}if(s!==void 0){let d=this.wrapFunctionCode(s);await Y(n.filePath,d,"utf8")}return o!==void 0&&(o.length>0?n.methods=o.map(d=>d.toUpperCase()):delete n.methods),i!==void 0&&(i.length>0&&this.bindingService.validateBindings(i),n.bindings=i.length>0?i:void 0),a!==void 0&&(a?n.passAllHeaders=!0:delete n.passAllHeaders),c!==void 0&&(n.allowUnauthenticated=c),n.updatedAt=Date.now(),this.functions.set(t,n),await this.saveFunctionsMetadata(),n}async deleteFunction(t){let r=this.functions.get(t);if(!r)return!1;try{return U(r.filePath)&&await Vt(r.filePath),this.functions.delete(t),await this.saveFunctionsMetadata(),!0}catch(n){throw console.error(`Error deleting function ${t}:`,n.message),n}}wrapFunctionCode(t){let r=t;if(/export\s+default\s+\w+/.test(t))return`// FunctionsService generated module
10
+ `),r=t.indexOf(e);if(r===-1)return null;let n=t.subarray(0,r),s=t.subarray(r+4),o=n.toString("utf8").split(`\r
11
+ `),a="",c="",f,l;for(let d of o){let p=d.toLowerCase();if(p.startsWith("content-disposition:")){a=d.substring(20).trim();let h=a.match(/name="([^"]+)"/);h&&(c=h[1]);let g=a.match(/filename="([^"]+)"/);g&&(f=g[1])}else p.startsWith("content-type:")&&(l=d.substring(13).trim())}if(!c)return null;let u=s;return u.length>=2&&u[u.length-2]===13&&u[u.length-1]===10&&(u=u.subarray(0,u.length-2)),{disposition:a,name:c,filename:f,contentType:l,data:u}}import{readFileSync as I}from"fs";import _ from"http";import He from"http2";import ke from"https";var J=class{config;rateLimiter;router;shutdownHandlers=[];constructor(t){let e=new z(ce(t||{})).get();e.debug&&console.log("Using configuration:",e),this.config=e,this.router=new ae;let r=e.rateLimit.requestsPerMinute||M().rateLimit.requestsPerMinute;this.rateLimiter=new oe(r,60),e.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(t){return this.router.use(t),this}get(t,...e){return this.router.get(t,...e),this}post(t,...e){return this.router.post(t,...e),this}put(t,...e){return this.router.put(t,...e),this}delete(t,...e){return this.router.delete(t,...e),this}patch(t,...e){return this.router.patch(t,...e),this}any(t,...e){return this.router.any(t,...e),this}options(t,...e){return this.router.options(t,...e),this}start(){let t=this.createServer(),{port:e,host:r}=this.config;return this.setupGracefulShutdown(t),t.listen(e,r,()=>{let n=t.address(),s=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${s}://${n.address!=="::"?n.address:"localhost"}:${n.port}`)}),t}createServer(){let t=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let e={key:I(this.config.sslKey),cert:I(this.config.sslCert),...this.config.sslCa?{ca:I(this.config.sslCa)}:{}};return He.createSecureServer(e,t)}catch(e){throw e.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${e.message}`):e}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let e={key:I(this.config.sslKey),cert:I(this.config.sslCert),...this.config.sslCa?{ca:I(this.config.sslCa)}:{}};return ke.createServer(e,t)}catch(e){throw e.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${e.message}`):e}}return _.createServer(t)}async rateLimitMiddleware(t,e){let r=t.req.socket.remoteAddress||"unknown";return t.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),t.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(r).toString()),t.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(r).toString()),this.rateLimiter.isAllowed(r)?e():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(t,e){let r=Date.now(),n=t.method||"UNKNOWN",s=t.url||"/unknown",i=this.config.debug;try{if(this.setCorsHeaders(e,t),this.setSecurityHeaders(e,this.config.useHttps),i&&console.log(`${n} ${s}`),t.method==="OPTIONS"){if(e instanceof _.ServerResponse)e.statusCode=204,e.end();else{let a=e;a.writeHead(204),a.end()}return}try{t.body=await this.parseBody(t)}catch(a){return i&&console.error("Body parsing error:",a.message),this.respond(e,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let o=await this.router.handle(t,e);return o?o._handled?void 0:this.respond(e,o):this.respond(e,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(o){return console.error("Server error:",o),this.respond(e,{statusCode:500,body:{error:"Internal Server Error",message:i?o.message:"An unexpected error occurred"}})}finally{i&&this.logDuration(r,n,s)}}logDuration(t,e,r){let n=Date.now()-t;console.log(`${e} ${r} completed in ${n}ms`)}async parseBody(t){return new Promise((e,r)=>{let n=[],s=0,i=this.config.maxBodySize,o=!1,a=null,c=this.config.debug,f=t.headers["content-type"]||"";c&&console.log("Content-Type:",f),this.config.requestTimeout>0&&(a=setTimeout(()=>{o||(o=!0,c&&console.log("Request timeout exceeded"),r(new Error("Request timeout")))},this.config.requestTimeout));let l=()=>{a&&(clearTimeout(a),a=null)};t.on("data",u=>{if(!o){if(s+=u.length,c&&console.log(`Received chunk: ${u.length} bytes, total size: ${s}`),s>i){o=!0,l(),c&&console.log(`Body size exceeded limit: ${s} > ${i}`),r(new Error("Request body too large"));return}n.push(u)}}),t.on("end",()=>{if(!o){o=!0,l(),c&&console.log(`Request body complete: ${s} bytes`);try{if(n.length>0){let u=Buffer.concat(n);if(f.includes("application/json"))try{let d=u.toString("utf8");e(JSON.parse(d))}catch(d){r(new Error(`Invalid JSON in request body: ${d.message}`))}else if(f.includes("application/x-www-form-urlencoded")){let d=u.toString("utf8"),p={};new URLSearchParams(d).forEach((h,g)=>{p[g]=h}),e(p)}else if(f.includes("multipart/form-data"))try{let d=ue(u,f);e(d)}catch(d){r(new Error(`Invalid multipart form data: ${d.message}`))}else this.isBinaryContentType(f)?e(u):e(u.toString("utf8"))}else e({})}catch(u){r(new Error(`Invalid request body: ${u}`))}}}),t.on("error",u=>{o||(o=!0,l(),r(new Error(`Error reading request body: ${u.message}`)))}),t.on("close",()=>{l()})})}isBinaryContentType(t){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(r=>t.includes(r))}setCorsHeaders(t,e){let r=e.headers.origin,{allowedDomains:n=["*"]}=this.config;!r||n.length===0||n.includes("*")?t.setHeader("Access-Control-Allow-Origin","*"):n.includes(r)&&(t.setHeader("Access-Control-Allow-Origin",r),t.setHeader("Vary","Origin")),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(t,e=!1){let r={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((e||this.config.useHttp2)&&(r["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),t instanceof _.ServerResponse)Object.entries(r).forEach(([n,s])=>{t.setHeader(n,s)});else{let n=t;Object.entries(r).forEach(([s,i])=>{n.setHeader(s,i)})}}respond(t,e){let r={...e.headers||{}};(s=>typeof s.writeHead=="function"&&typeof s.end=="function")(t)?(t.writeHead(e.statusCode,r),e.body===null||e.body===void 0?t.end():e.isRaw||typeof e.body=="string"?t.end(e.body):t.end(JSON.stringify(e.body))):(console.warn("Unexpected response object type without writeHead/end methods"),t.writeHead?.(e.statusCode,r),e.body===null||e.body===void 0?t.end?.():e.isRaw||typeof e.body=="string"?t.end?.(e.body):t.end?.(JSON.stringify(e.body)))}setupGracefulShutdown(t){let e=o=>{console.log("Shutting down MikroServe server..."),o&&console.error("Error:",o),this.cleanupShutdownHandlers(),t.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(o?1:0))})},r=()=>e(),n=()=>e(),s=o=>e(o),i=o=>e(o);this.shutdownHandlers=[r,n,s,i],process.on("SIGINT",r),process.on("SIGTERM",n),process.on("uncaughtException",s),process.on("unhandledRejection",i)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[t,e,r,n]=this.shutdownHandlers;process.removeListener("SIGINT",t),process.removeListener("SIGTERM",e),process.removeListener("uncaughtException",r),process.removeListener("unhandledRejection",n),this.shutdownHandlers=[]}}};var v=class extends Error{constructor(e){super(),this.name="ValidationError",this.message=e||"Invalid input",this.cause={statusCode:400}}};var O=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};var R=class extends Error{constructor(e){super(),this.name="InvalidMethodError",this.message=e||"Invalid HTTP method",this.cause={statusCode:400}}};var D=class extends Error{constructor(e){super(),this.name="ServiceRequestError",this.message=e||"Service request failed",this.cause={statusCode:502}}};var L=class{generatePermissionsFromBindings(e){let r=[];for(let n of e){let s=n.service;for(let i of n.permissions){if(!i.resource){r.push(`${s}.*`);continue}let o=i.resource,a=i.actions||["*"];if(i.targets&&i.targets.length>0)for(let c of a)for(let f of i.targets)r.push(`${s}.${o}.${c}:${f}`);else for(let c of a)r.push(`${s}.${o}.${c}`)}}return[...new Set(r)]}validateBindings(e){let r=["databases","storage","observability","sites","functions","events","schemas"];for(let n of e){if(!r.includes(n.service))throw new v(`Invalid service: ${n.service}. Must be one of: ${r.join(", ")}`);if(!n.permissions||n.permissions.length===0)throw new v("Bindings must have at least one permission");for(let s of n.permissions)if(s.targets&&s.targets.length>0){if(!s.resource)throw new v("Action-level bindings (with targets) must specify resource");if(!s.actions||s.actions.length===0)throw new v("Action-level bindings (with targets) must specify actions")}}}};var W=class{constructor(e,r,n){this.baseUrl=e;this.authToken=r;this.bindings=n}async request(e,r,n,s){let i=`${this.baseUrl}${r}`;if(s){let u=new URLSearchParams(s);i+=`?${u.toString()}`}let o={"Content-Type":"application/json"};this.authToken&&(o.Authorization=`Bearer ${this.authToken}`),this.bindings&&this.bindings.length>0&&(o["X-Function-Bindings"]=JSON.stringify(this.bindings));let a={method:e,headers:o};n&&(a.body=JSON.stringify(n));let c=await fetch(i,a),f=c.headers.get("content-type"),l;if(f?.includes("application/json")){let u=await c.text();u?l=JSON.parse(u):l=null}else l=await c.text();if(!c.ok)throw new D(`Service request failed (${c.status}): ${typeof l=="string"?l:JSON.stringify(l)}`);return l}},X=class extends W{async get(e,r){return this.request("POST","/get",{tableName:e,key:r})}async write(e,r,n,s,i){return this.request("POST","/write",{tableName:e,key:r,value:n,expiration:s,dictionaryName:i})}async delete(e,r){return this.request("DELETE","/delete",void 0,{tableName:e,key:r})}async listTables(){return this.request("GET","/tables")}async getTableSize(e){return this.request("GET","/table",void 0,{tableName:e})}async getTableInfo(e){return this.request("GET",`/tables/${e}`)}async createTable(e){return this.request("POST",`/tables/${e}`)}async deleteTable(e){return this.request("DELETE",`/tables/${e}`)}},Z=class{constructor(e){this.eventBus=e}async emit(e,r){await this.eventBus.emit(e,r)}},Y=class{constructor(e){this.schemaRegistry=e}validate(e,r,n){return this.schemaRegistry.validate(e,r,n)}},j=class{constructor(e,r,n,s){this.serviceBaseUrls=e;this.authToken=r;this.eventBus=n;this.schemaRegistry=s}createBindings(e){let r={};for(let n of e)switch(n.service){case"databases":{let s=this.serviceBaseUrls[n.service];if(!s)continue;r.databases=new X(s,this.authToken,e);break}case"events":this.eventBus&&(r.events=new Z(this.eventBus));break;case"schemas":this.schemaRegistry&&(r.schemas=new Y(this.schemaRegistry));break}return r}};var $=class{isSilent;propertyPath="";constructor(t=!1){this.isSilent=t}test(t,e){if(!e)throw new Error("Missing input!");this.updatePropertyPath();let{results:r,errors:n}=this.validate(t.properties,e),s=this.compileErrors(r,n),i=this.isSuccessful(r,s);return{errors:s,success:i}}compileErrors(t,e){let r=t.filter(n=>n.success===!1);return[...e,...r].flatMap(n=>n)}isSuccessful(t,e){return t.every(r=>r.success===!0)&&e.length===0}validate(t,e,r=[],n=[]){let s=t?.additionalProperties??!0,i=t?.required||[];n=this.checkForRequiredKeysErrors(i,e,n),n=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),n,s);for(let o in t){let a=i.includes(o)&&o!=="required",c=t[o],f=e[o],l=c.additionalProperties??!0;a&&(n=this.checkForRequiredKeysErrors(c.required||[],f,n)),this.isDefined(f)&&(this.handleValidation(o,f,c,r),n=this.checkForDisallowedProperties(Object.keys(f),Object.keys(c),n,l),this.handleNestedObject(f,c,r,n))}return{results:r,errors:n}}updatePropertyPath(t,e=""){if(!t){this.propertyPath="";return}e&&(this.propertyPath=e),this.propertyPath=`${this.propertyPath}.${t}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(t){return!!(typeof t=="number"&&t===0||t||t===""||typeof t=="boolean")}checkForRequiredKeysErrors(t,e,r){if(!this.areRequiredKeysPresent(t,e)){let n=e?Object.keys(e):[],s=this.findNonOverlappingElements(t,n),i=s.length>0?`Missing the required key: '${s.join(", ")}'!`:`Missing values for required keys: '${n.filter(o=>!e[o]).join(", ")}'!`;r.push({key:"",value:e,success:!1,error:i})}return r}checkForDisallowedProperties(t,e,r,n){if(!n){let s=this.findNonOverlappingElements(t,e);s.length>0&&r.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${s.join(", ")}'!`})}return r}handleValidation(t,e,r,n){this.updatePropertyPath(t);let s=this.validateProperty(this.propertyPath,r,e);n.push(...s);let i=(a,c)=>{a.forEach(f=>{let l=this.validateProperty(this.propertyPath,c.items,f);n.push(...l)}),this.updatePropertyPath()},o=a=>{let c=Object.keys(a),f=this.propertyPath;c.forEach(l=>{if(this.updatePropertyPath(l,f),this.isArray(a[l])&&r[l]?.items!=null)i(a[l],r[l]);else{let u=this.validateProperty(this.propertyPath,r[l],a[l]);n.push(...u)}})};this.isArray(e)&&r.items!=null?i(e,r):this.isObject(e)?o(e):this.updatePropertyPath()}handleNestedObject(t,e,r,n){if(this.isObject(t)){let s=this.getNestedObjects(t);for(let i of s){let o=e[i],a=t[i];o&&typeof a=="object"&&this.validate(o,a,r,n)}}}getNestedObjects(t){return Object.keys(t).filter(e=>{if(this.isObject(t))return e})}findNonOverlappingElements(t,e){return t.filter(r=>!e.includes(r))}areRequiredKeysPresent(t,e=[]){return t.every(r=>Object.keys(e).includes(r)?this.isDefined(e[r]):!1)}validateProperty(t,e,r){return this.validateInput(e,r).map(s=>{let{success:i,error:o}=s;return{key:t,value:r,success:i,error:o??""}})}validateInput(t,e){if(t){let r=[{condition:()=>t.type,validator:()=>this.isCorrectType(t.type,e),error:"Invalid type"},{condition:()=>t.format,validator:()=>this.isCorrectFormat(t.format,e),error:"Invalid format"},{condition:()=>t.minLength,validator:()=>this.isMinimumLength(t.minLength,e),error:"Length too short"},{condition:()=>t.maxLength,validator:()=>this.isMaximumLength(t.maxLength,e),error:"Length too long"},{condition:()=>t.minValue,validator:()=>this.isMinimumValue(t.minValue,e),error:"Value too small"},{condition:()=>t.maxValue,validator:()=>this.isMaximumValue(t.maxValue,e),error:"Value too large"},{condition:()=>t.matchesPattern,validator:()=>this.matchesPattern(t.matchesPattern,e),error:"Pattern does not match"}],n=[];for(let s of r)s.condition()&&!s.validator()&&n.push({success:!1,error:s.error});return n}else this.isSilent||console.warn(`Missing property '${t}' for match '${e}'. Skipping...`);return[{success:!0}]}isCorrectType(t,e){return Array.isArray(t)||(t=[t]),t.some(r=>{switch(r){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"object":return this.isObject(e);case"array":return this.isArray(e)}})}isObject(t){return t!==null&&!this.isArray(t)&&typeof t=="object"&&t instanceof Object&&Object.prototype.toString.call(t)==="[object Object]"}isArray(t){return Array.isArray(t)}isCorrectFormat(t,e){switch(t){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(e);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(e);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(e);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(e);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(e);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(e)}}isMinimumLength(t,e){return Array.isArray(e)?e.length>=t:e?.toString().length>=t}isMaximumLength(t,e){return Array.isArray(e)?e.length<=t:e.toString().length<=t}isMinimumValue(t,e){return e>=t}isMaximumValue(t,e){return e<=t}matchesPattern(t,e){return new RegExp(t).test(e)}schemaFrom(t){let e={properties:{additionalProperties:!1,required:[]}};for(let r in t){let n=t[r];e.properties.required.push(r),Array.isArray(n)?e.properties[r]=this.generateArraySchema(n):typeof n=="object"&&n!==null?e.properties[r]=this.generateNestedObjectSchema(n):e.properties[r]=this.generatePropertySchema(n)}return e}generateArraySchema(t){let e={type:"array"},r=t.filter(n=>n);if(r.length>0){let n=r[0];r.every(i=>typeof i==typeof n)?typeof n=="object"&&!Array.isArray(n)?e.items=this.generateNestedObjectSchema(n):e.items=this.generatePropertySchema(n):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return e}generateNestedObjectSchema(t){let e={type:"object",additionalProperties:!1,required:[]};for(let r in t){let n=t[r];e.required.push(r),typeof n=="object"&&!Array.isArray(n)&&n!==null?e[r]=this.generateNestedObjectSchema(n):e[r]=this.generatePropertySchema(n)}return e}generatePropertySchema(t){let e=typeof t,r={type:e};return e==="string"&&(r.minLength=1),r}};async function F(t){return t.body||{}}function w(t,e="An error occurred"){let r=t?.message||t||e,n=t?.cause?.statusCode||t?.statusCode||400;return{message:r,status:n}}function le(t,e,r={}){let n=Array.isArray(e)?e:[e];if(!t||!t.roles||!Array.isArray(t.roles)){let o=new Error("Unauthorized: User or roles missing");throw o.cause={statusCode:403},o}let s=t.roles.flatMap(o=>o?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(f=>typeof f=="string"?f:f&&typeof f=="object"&&f.actions?f.actions:[]))||[]);if(!n.every(o=>s.includes(o)||s.includes("*")?!0:s.some(a=>{if(a.endsWith(".*")){let c=a.slice(0,-2);return o.startsWith(`${c}.`)}return!1}))){let o=new Error("Unauthorized");throw o.cause={statusCode:403},o}return!0}function de(t,e,r,n,s){let i=t.find(c=>c.service===e);if(!i){let c=new Error(`Function bindings do not include access to service: ${e}`);throw c.cause={statusCode:403},c}if(!i.permissions||i.permissions.length===0)return;for(let c of i.permissions)if(!(c.resource&&c.resource!==r)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(n)){if(c.targets&&c.targets.length>0){if(!s)return;if(!c.targets.includes(s))continue}return}}let o=s?`:${s}`:"",a=new Error(`Function bindings do not allow: ${e}.${r}.${n}${o}`);throw a.cause={statusCode:403},a}import{readFileSync as Me,existsSync as Oe}from"node:fs";function x(){let t=process.env.MOLNOS_RUNTIME_CONFIG,e={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!t||!Oe(t))return e;try{let r=Me(t,"utf-8");return JSON.parse(r)}catch(r){return console.error("[loadRuntimeConfig] Failed to load runtime config:",r),e}}async function S(t,e,r,n,s,i,o){if(!e)return null;let a=t.headers["x-molnos-service-token"];if(a){let l=x();if(l.internalServiceSecret&&a===l.internalServiceSecret)return null}let c=t.state.user;if(!c){let l=t.headers.authorization;if(!l){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let u=l.replace(/^Bearer\s+/i,"");if(c=await e.getUserFromToken(u),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}le(c,r,{});let f=t.headers["x-function-bindings"];if(f)try{let l=Array.isArray(f)?f[0]:f,u=JSON.parse(l);de(u,n,s,i,o)}catch(l){if(l.cause?.statusCode===403)throw l;let u=new Error("Invalid function bindings header");throw u.cause={statusCode:400},u}return c}var fe={properties:{id:{type:"string",minLength:1,maxLength:40,pattern:"^[a-zA-Z0-9_-]{1,40}$"},name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},trigger:{type:"object"},triggers:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["http","event"]},eventName:{type:"string"}},required:["type"]}},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"},context:{type:"string",minLength:1}},required:["name","code"],additionalProperties:!1};var Le=new $(!0);async function he(t,e,r){try{let n=await F(t),s=Le.test(fe,n);if(!s.success)return t.json({error:"Invalid input",details:s.errors},400);await S(t,r,"functions.function.create","functions","function","create");let{id:i,name:o,code:a,methods:c,bindings:f,trigger:l,triggers:u,passAllHeaders:d,allowUnauthenticated:p}=n,h=u||(l?[l]:void 0),g=await e.deployFunction(o,a,c,f,h,d,p,i);return t.json({success:!0,function:g},201)}catch(n){let{message:s,status:i}=w(n,"Error deploying function");return t.json({error:s},i)}}async function pe(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);let s=e.getFunction(n);return s?s.triggers&&s.triggers.length>0&&!s.triggers.some(i=>i.type==="http")?t.json({error:"Not Found",message:"Function not found"},404):(s.allowUnauthenticated!==!0&&await S(t,r,"functions.function.execute","functions","function","execute",n),await e.executeFunction(n,t)):t.json({error:"Not Found",message:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error executing function");return t.json({error:s},i)}}var ge={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},trigger:{type:"object"},triggers:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["http","event"]},eventName:{type:"string"}},required:["type"]}},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var Ue=new $(!0);async function me(t,e,r){try{let n=t.params.functionId,s=await F(t);if(!n)return t.json({error:"functionId is required"},400);let i=Ue.test(ge,s);if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);await S(t,r,"functions.function.update","functions","function","update",n);let{code:o,methods:a,bindings:c,trigger:f,triggers:l,passAllHeaders:u,allowUnauthenticated:d}=s,p=l||(f?[f]:void 0),h=await e.updateFunction(n,{code:o,methods:a,bindings:c,triggers:p,passAllHeaders:u,allowUnauthenticated:d});return h?t.json({success:!0,function:h},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error updating function");return t.json({error:s},i)}}async function ye(t,e,r){try{let n=t.params.functionId;return n?(await S(t,r,"functions.function.delete","functions","function","delete",n),await e.deleteFunction(n)?t.json({success:!0,message:"Function deleted"},200):t.json({error:"Function not found"},404)):t.json({error:"functionId is required"},400)}catch(n){let{message:s,status:i}=w(n,"Error deleting function");return t.json({error:s},i)}}async function ve(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);await S(t,r,"functions.function.get","functions","function","read",n);let s=e.getFunction(n);return s?t.json({success:!0,function:s},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error getting function");return t.json({error:s},i)}}async function be(t,e,r,n){try{await S(t,r,"functions.function.get","functions","function","read");let s=e.getFunctions(),i=t.query.context;if(i&&n){let o=t.headers.authorization?.replace(/^Bearer\s+/i,""),a=await n.listResourcesByType(i,"function",o);s=s.filter(c=>a.includes(c.id))}return t.json({success:!0,count:s.length,functions:s},200)}catch(s){let{message:i,status:o}=w(s,"Error listing functions");return t.json({error:i},o)}}import{EventEmitter as Be}from"node:events";var K=class t{static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new Be,t.instance.setMaxListeners(100)),t.instance}};function Q(){return K.getInstance()}function we(t){let e=Q();try{e.emit("function.log",t)}catch(r){console.error("Failed to emit function log event:",r)}}import{getRandomValues as qe}from"node:crypto";var ee=class{options;defaultLength=16;defaultOnlyLowerCase=!1;defaultStyle="extended";defaultUrlSafe=!0;constructor(t){if(this.options={},t)for(let[e,r]of Object.entries(t))this.options[e]=this.generateConfig(r)}add(t){if(!t?.name)throw new Error("Missing name for the ID configuration");let e=this.generateConfig(t);this.options[t.name]=e}remove(t){if(!t?.name)throw new Error("Missing name for the ID configuration");delete this.options[t.name]}create(t,e,r,n){let s=this.generateConfig({length:t,style:e,onlyLowerCase:r,urlSafe:n});return this.generateId(s)}custom(t){if(this.options[t])return this.generateId(this.options[t]);throw new Error(`No configuration found with name: ${t}`)}generateConfig(t){return{name:t?.name||"",length:t?.length||this.defaultLength,onlyLowerCase:t?.onlyLowerCase??this.defaultOnlyLowerCase,style:t?.style||this.defaultStyle,urlSafe:t?.urlSafe??this.defaultUrlSafe}}getCharacterSet(t,e,r){if(t==="hex")return e?"0123456789abcdef":"0123456789ABCDEFabcdef";if(t==="alphanumeric")return e?"abcdefghijklmnopqrstuvwxyz0123456789":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";if(t==="extended")return r?e?"abcdefghijklmnopqrstuvwxyz0123456789-._~":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~":e?"abcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~!$()*+,;=:";throw new Error(`Unknown ID style "${t} provided. Must be one of "extended" (default), "alphanumeric", or "hex".`)}generateId(t){let{length:e,onlyLowerCase:r,style:n,urlSafe:s}=t;if(e<0||e===0)throw new Error("ID length cannot be negative");let i=this.getCharacterSet(n,r,s),o=(2<<Math.log(i.length-1)/Math.LN2)-1,a=Math.ceil(1.6*o*e/i.length),c="";for(;c.length<e;){let f=new Uint8Array(a);qe(f);for(let l=0;l<a;l++){let u=f[l]&o;if(u<i.length&&(c+=i[u],c.length===e))break}}return c}};var Ve=8,ze=40,Ge=/^[a-zA-Z0-9_-]{1,40}$/;function _e(){return new ee().create(Ve,"alphanumeric",!1,!0)}function Je(t){return Ge.test(t)}function We(t){if(!Je(t))throw new Error(`Invalid ID format: "${t}". IDs must be 1-${ze} characters using only alphanumeric characters, underscores, and hyphens.`)}function te(t){return t?(We(t),t):_e()}import{EventEmitter as Xe}from"events";var re=class{emitter;targets={};options;constructor(t){this.emitter=new Xe,t?.maxListeners===0?this.emitter.setMaxListeners(0):this.emitter.setMaxListeners(t?.maxListeners||10),this.options={errorHandler:t?.errorHandler||(e=>console.error(e)),isSilent:t?.isSilent||!1}}addTarget(t){return(Array.isArray(t)?t:[t]).map(n=>this.targets[n.name]?(this.options.isSilent||console.error(`Target with name '${n.name}' already exists.`),!1):(this.targets[n.name]={name:n.name,url:n.url,headers:n.headers||{},events:n.events||[]},!0)).every(n=>n===!0)}updateTarget(t,e){if(!this.targets[t])return console.error(`Target with name '${t}' does not exist.`),!1;let r=this.targets[t];return e.url!==void 0&&(r.url=e.url),e.headers&&(r.headers={...r.headers,...e.headers}),e.events&&(r.events=e.events),!0}removeTarget(t){return this.targets[t]?(delete this.targets[t],!0):(console.error(`Target with name '${t}' does not exist.`),!1)}addEventToTarget(t,e){if(!this.targets[t])return console.error(`Target with name '${t}' does not exist.`),!1;let r=Array.isArray(e)?e:[e],n=this.targets[t];return r.forEach(s=>{n.events.includes(s)||n.events.push(s)}),!0}on(t,e){return this.emitter.on(t,e),this}off(t,e){return this.emitter.off(t,e),this}once(t,e){return this.emitter.once(t,e),this}async emit(t,e){let r={success:!0,errors:[]},n=(o,a,c)=>({target:o,event:a,error:c}),s=Object.values(this.targets).filter(o=>o.events.includes(t)||o.events.includes("*"));s.filter(o=>!o.url).forEach(o=>{try{this.emitter.emit(t,e)}catch(a){let c=a instanceof Error?a:new Error(String(a));r.errors.push({target:o.name,event:t,error:c}),this.options.errorHandler(c,t,e),r.success=!1}});let i=s.filter(o=>o.url);if(i.length>0){let o=i.map(async a=>{try{let c=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json",...a.headers},body:JSON.stringify({eventName:t,data:e})});if(!c.ok){let f=`HTTP error! Status: ${c.status}: ${c.statusText}`,l=new Error(f);r.errors.push(n(a.name,t,l)),this.options.errorHandler(l,t,e),r.success=!1}}catch(c){let f=c instanceof Error?c:new Error(String(c));r.errors.push(n(a.name,t,f)),this.options.errorHandler(f,t,e),r.success=!1}});await Promise.allSettled(o)}return r}async handleIncomingEvent(t){try{let{eventName:e,data:r}=typeof t=="string"?JSON.parse(t):t;process.nextTick(()=>{try{this.emitter.emit(e,r)}catch(n){this.options.errorHandler(n instanceof Error?n:new Error(String(n)),e,r)}})}catch(e){throw this.options.errorHandler(e instanceof Error?e:new Error(String(e)),"parse_event"),e}}createMiddleware(){return async(t,e,r)=>{if(t.method!=="POST"){r&&r();return}if(t.body)try{await this.handleIncomingEvent(t.body),e.statusCode=202,e.end()}catch(n){e.statusCode=400,e.end(JSON.stringify({error:"Invalid event format"})),r&&r(n)}else{let n="";t.on("data",s=>n+=s.toString()),t.on("end",async()=>{try{await this.handleIncomingEvent(n),e.statusCode=202,e.end()}catch(s){e.statusCode=400,e.end(JSON.stringify({error:"Invalid event format"})),r&&r(s)}})}}}};var N=null;function H(){return N||(N=new re,N.addTarget({name:"molnos-internal",events:["*"]})),N}var Ze=null;function ne(){return Ze||void 0}function Se(t,e){let r={enabled:!1,requestsPerMinute:0};if(!e)return r;let n=e.services?.[t];return n||(e.global?e.global:r)}function xe(t,e){let r=t?.api?.port;if(!r)throw new Error('Missing "port" input when create API service!');let n=x(),s=t?.dataPath||n.molnos.dataPath,i=t?.api?.host||n.server.host,o=t?.identityApiUrl!==void 0?t.identityApiUrl:n.identity.apiUrl,a=t?.contextApiUrl!==void 0?t.contextApiUrl:n.context.apiUrl,c=t?.debug||!1,f;return e&&(f=Se(e,n.molnos.rateLimit)),{dataPath:s,api:{port:r,host:i},...o?{identityApiUrl:o}:{},...a?{contextApiUrl:a}:{},...f?{rateLimit:f}:{},debug:c}}var U=class{baseUrl;authToken;constructor(e,r){this.baseUrl=e.replace(/\/$/,""),this.authToken=r}async createCustomRole(e,r,n,s){let i=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:e,name:r,description:n,permissions:s})});if(!i.ok){let o=`Failed to create role: ${i.statusText}`;try{o=(await i.json()).error||o}catch{o=await i.text().catch(()=>i.statusText)||o}throw new Error(o)}}async updateRole(e,r){let n=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let s=await n.json();throw new Error(s.error||`Failed to update role: ${n.statusText}`)}}async deleteRole(e){let r=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete role: ${r.statusText}`)}}async addServiceAccount(e,r,n){let s=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:e,description:r,roles:n})});if(!s.ok){let o=`Failed to create service account: ${s.statusText}`;try{o=(await s.json()).error||o}catch{o=await s.text().catch(()=>s.statusText)||o}throw new Error(o)}let i=await s.json();return{id:i.id,apiKey:i.apiKey}}async deleteIdentity(e){let r=await fetch(`${this.baseUrl}/identity/service-accounts/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete service account: ${r.statusText}`)}}async getUserFromToken(e){try{let r=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return r.ok?await r.json():null}catch{return null}}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}};function Ce(t){return t?new U(t):null}var B=class{baseUrl;constructor(e){this.baseUrl=e.replace(/\/$/,"")}async listResourcesByType(e,r,n){let s=`${this.baseUrl}/contexts/${encodeURIComponent(e)}`;try{let i={"Content-Type":"application/json"};n&&(i.Authorization=`Bearer ${n}`);let o=await fetch(s,{method:"GET",headers:i});if(!o.ok)return[];let c=(await o.json()).context?.resources||{};switch(r){case"function":return c.functions||[];case"database":return c.databases||[];case"storage":return c.storage||[];case"site":return c.sites||[];default:return[]}}catch{return[]}}};function Ee(t){return t?new B(t):null}var ie=class t{static MAX_EVENT_CHAIN_DEPTH=10;functionsDir;functions=new Map;eventHandlers=new Map;eventChainDepth=0;debug;bindingService;constructor(e){this.functionsDir=e.functionsDir||k(process.cwd(),"functions-data"),this.debug=e.debug||!1,this.bindingService=new L}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions(),this.subscribeEventTriggeredFunctions()}getFunction(e){return this.functions.get(e)}getFunctions(){return Array.from(this.functions.values()).map(e=>({name:e.name,endpoint:e.endpoint,id:e.id,filePath:e.filePath,methods:e.methods,...e.bindings?{bindings:e.bindings}:{},...e.triggers&&e.triggers.length>0?{triggers:e.triggers}:{},...e.passAllHeaders!==void 0?{passAllHeaders:e.passAllHeaders}:{},...e.allowUnauthenticated!==void 0?{allowUnauthenticated:e.allowUnauthenticated}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}))}async ensureFunctionsDirExists(){q(this.functionsDir)||await Ye(this.functionsDir,{recursive:!0})}async loadExistingFunctions(){try{let e=k(this.functionsDir,"functions.json");if(q(e)){let r=await Pe(e,"utf8"),n=JSON.parse(r);for(let s of n)q(s.filePath)&&this.functions.set(s.id,s)}}catch{}}async saveFunctionsMetadata(){try{let e=k(this.functionsDir,"functions.json"),r=Array.from(this.functions.values());await se(e,JSON.stringify(r,null,2),"utf8")}catch{}}async deployFunction(e,r,n,s,i,o,a,c){if(!e||typeof e!="string")throw new v("Function name is required and must be a string");if(!r||typeof r!="string")throw new v("Function code is required and must be a string");if(n!==void 0){if(!Array.isArray(n))throw new v("Methods must be an array");let h=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let g of n)if(!h.includes(g.toUpperCase()))throw new R(`Invalid HTTP method: ${g}. Must be one of: ${h.join(", ")}`)}if(s&&s.length>0&&this.bindingService.validateBindings(s),i&&i.length>0){for(let h of i)if(h.type==="event"&&!h.eventName)throw new v("Event trigger must specify an eventName")}let f=te(c),l=k(this.functionsDir,`${f}.mjs`),u=this.wrapFunctionCode(r);await se(l,u,"utf8");let d=Date.now(),p={id:f,name:e,filePath:l,endpoint:`/functions/run/${f}`,...n&&n.length>0?{methods:n.map(h=>h.toUpperCase())}:{},...s?{bindings:s}:{},...i&&i.length>0?{triggers:i}:{},...o!==void 0?{passAllHeaders:o}:{},...a!==void 0?{allowUnauthenticated:a}:{},createdAt:d,updatedAt:d};return this.functions.set(f,p),await this.saveFunctionsMetadata(),this.subscribeToEvents(p),p}async updateFunction(e,r){let n=this.functions.get(e);if(!n)throw new O(`Function with ID ${e} not found`);let{code:s,methods:i,bindings:o,triggers:a,passAllHeaders:c,allowUnauthenticated:f}=r;if(s===void 0&&i===void 0&&o===void 0&&a===void 0&&c===void 0&&f===void 0)throw new v("At least one parameter (code, methods, bindings, triggers, passAllHeaders, or allowUnauthenticated) must be provided");if(s!==void 0&&(typeof s!="string"||!s))throw new v("Function code must be a non-empty string");if(i!==void 0){if(!Array.isArray(i))throw new v("Methods must be an array");let l=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let u of i)if(!l.includes(u.toUpperCase()))throw new R(`Invalid HTTP method: ${u}. Must be one of: ${l.join(", ")}`)}if(s!==void 0){let l=this.wrapFunctionCode(s);await se(n.filePath,l,"utf8")}if(i!==void 0&&(i.length>0?n.methods=i.map(l=>l.toUpperCase()):delete n.methods),o!==void 0&&(o.length>0&&this.bindingService.validateBindings(o),n.bindings=o.length>0?o:void 0),c!==void 0&&(c?n.passAllHeaders=!0:delete n.passAllHeaders),a!==void 0){for(let l of a)if(l.type==="event"&&!l.eventName)throw new v("Event trigger must specify an eventName");this.unsubscribeFromEvents(e),n.triggers=a.length>0?a:void 0,this.subscribeToEvents(n)}return f!==void 0&&(n.allowUnauthenticated=f),n.updatedAt=Date.now(),this.functions.set(e,n),await this.saveFunctionsMetadata(),n}async deleteFunction(e){let r=this.functions.get(e);if(!r)return!1;try{return this.unsubscribeFromEvents(e),q(r.filePath)&&await Ke(r.filePath),this.functions.delete(e),await this.saveFunctionsMetadata(),!0}catch(n){throw console.error(`Error deleting function ${e}:`,n.message),n}}wrapFunctionCode(e){let r=e;if(/export\s+default\s+\w+/.test(e))return`// FunctionsService generated module
12
12
  // Generated at: ${new Date().toISOString()}
13
13
 
14
14
  // User function code starts here
15
15
  ${r}
16
16
  // User function code ends here
17
- `;let n=t.match(/export\s*\{([^}]+)\}/);if(n){let s=n[1],o=s.match(/(\w+)\s+as\s+handler\b/)||s.match(/\bhandler\b/);if(o){let i=o[1]||"handler";r=t.replace(/export\s*\{[^}]+\}/,`export default ${i}`)}}else r=`${t}
17
+ `;let n=e.match(/export\s*\{([^}]+)\}/);if(n){let s=n[1],i=s.match(/(\w+)\s+as\s+handler\b/)||s.match(/\bhandler\b/);if(i){let o=i[1]||"handler";r=e.replace(/export\s*\{[^}]+\}/,`export default ${o}`)}}else r=`${e}
18
18
 
19
19
  export default handler;`;return`// FunctionsService generated module
20
20
  // Generated at: ${new Date().toISOString()}
@@ -22,4 +22,4 @@ export default handler;`;return`// FunctionsService generated module
22
22
  // User function code starts here
23
23
  ${r}
24
24
  // User function code ends here
25
- `}async executeFunction(t,r){try{let n=this.functions.get(t);if(!n)return r.json({error:"Not Found",message:"Function not found"},404);if(n.allowUnauthenticated!==!0&&!r.headers.authorization)return r.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(n.methods&&n.methods.length>0){let f=(r.req.method||"GET").toUpperCase();if(!n.methods.includes(f)){let m=n.methods.join(", "),p=r.json({error:"Method Not Allowed",message:`This function only accepts: ${m}`},405);return p.headers={...p.headers||{},allow:m},p}}let s=null;try{let f=r.req.method||"GET";["POST","PUT","PATCH"].includes(f)&&((r.headers["content-type"]||"").includes("application/json")?s=await I(r):s=r.body)}catch{}let o=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],i={},a=r.req.headers;for(let[f,m]of Object.entries(a))(n.passAllHeaders||!o.includes(f.toLowerCase()))&&(i[f]=m);let c=new URL(r.req.url||"","http://127.0.0.1").pathname,d=`/run/${t}`,l=c.startsWith(d)?c.substring(d.length):"/";l||(l="/");let u={};if(n.bindings&&n.bindings.length>0){let m=r.headers.authorization?.replace(/^Bearer\s+/i,"")||null,p=T(),x={databases:p.services.databases.url,storage:p.services.storage.url,observability:p.services.observability.url,sites:p.services.sites.url,functions:p.services.functions.url};u=new k(x,m).createBindings(n.bindings)}let h={request:{method:r.req.method||"GET",path:c,subpath:l,query:r.query,headers:i,body:s},functionId:t,functionName:n.name,bindings:u};try{let p=(await import(`${zt(n.filePath).href}?t=${Date.now()}`)).default;if(typeof p!="function")return r.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:x,restore:C}=this.createConsoleInterceptor(t,n.name);Object.assign(console,x);let g;try{g=await p(h.request,h)}finally{C()}if(g&&typeof g=="object"){if(g.statusCode!==void 0&&g.body!==void 0){let R=g.statusCode||200,S=g.headers||{};if(typeof g.body=="object"){let N=r.json(g.body,R);return Object.keys(S).length>0&&(N.headers={...N.headers||{},...S}),N}let E=r.text(g.body,R);return Object.keys(S).length>0&&(E.headers={...E.headers||{},...S}),E}return r.json(g)}return typeof g=="string"?r.text(g):typeof g=="number"||typeof g=="boolean"?r.json({result:g}):r.json({result:g===null?null:void 0})}catch(f){return console.error("Function execution error:",f),r.json({error:"Function Execution Error",message:this.debug?f.message:"Error executing function",stack:this.debug?f.stack:void 0},500)}}catch(n){return console.error("Error processing function execution:",n),r.json({error:"Internal Server Error",message:this.debug?n.message:"Failed to process function execution"},500)}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(r=>({id:r.id,name:r.name,endpoint:r.endpoint,createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()}))}}createConsoleInterceptor(t,r){let n={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),debug:console.debug.bind(console)},s=(o,i)=>{let a=i.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" ");st({functionId:t,functionName:r,level:o,message:a,timestamp:Date.now()})};return{interceptedConsole:{log:(...o)=>{n.log(...o),s("info",o)},error:(...o)=>{n.error(...o),s("error",o)},warn:(...o)=>{n.warn(...o),s("warn",o)},info:(...o)=>{n.info(...o),s("info",o)},debug:(...o)=>{n.debug(...o),s("debug",o)}},restore:()=>{console.log=n.log,console.error=n.error,console.warn=n.warn,console.info=n.info,console.debug=n.debug}}}};async function Gt(e){let t=e.dataPath||"data",r=F(t,"functions"),n=e.debug||!1,s=new K({functionsDir:r,debug:n});await s.start();let o=yt(e.identityApiUrl),i=bt(e.contextApiUrl),a=Z(),c=T(),d=c.services.observability.url;a.on("function.log",f=>{fetch(`${d}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:`functions.${f.functionId}`,level:f.level,message:f.message,metadata:{functionId:f.functionId,functionName:f.functionName,...f.metadata}})}).catch(m=>{n&&console.error("Failed to send log to observability service:",m)})});let l=new J({port:e.api.port||c.services.functions.port,host:e.api.host||c.services.functions.host,rateLimit:e.rateLimit||{enabled:!1,requestsPerMinute:0}});l.post("/deploy",async f=>ct(f,s,o)),l.get("/list",async f=>pt(f,s,o,i)),l.get("/stats",async f=>{try{let m=s.getStats();return f.json({success:!0,stats:m})}catch(m){return f.json({error:m.message},500)}}),l.get("/:functionId/config",async f=>{try{let m=f.params.functionId,p=s.getFunction(m);if(!p)return f.json({error:"Function not found"},404);let x="";try{let C=await wt(p.filePath,"utf8"),g="// User function code starts here",R="// User function code ends here",S=C.indexOf(g),E=C.indexOf(R);S!==-1&&E!==-1?(x=C.substring(S+g.length,E).trim().replace(/^\n+/,"").replace(/\n+$/,""),x=x.replace(/\n*export\s+default\s+handler;\s*$/,"")):x=C}catch(C){return f.json({error:"Failed to read function code",message:C.message},500)}return f.json({success:!0,function:{id:p.id,name:p.name,endpoint:p.endpoint,filePath:p.filePath,code:x,...p.methods?{methods:p.methods}:{},...p.bindings?{bindings:p.bindings}:{},...p.passAllHeaders!==void 0?{passAllHeaders:p.passAllHeaders}:{},...p.allowUnauthenticated!==void 0?{allowUnauthenticated:p.allowUnauthenticated}:{},createdAt:new Date(p.createdAt).toISOString(),updatedAt:new Date(p.updatedAt).toISOString()}})}catch(m){return f.json({error:m.message},500)}}),l.get("/:functionId",async f=>ht(f,s,o)),l.put("/:functionId",async f=>dt(f,s,o)),l.delete("/:functionId",async f=>ft(f,s,o));let u=async f=>ut(f,s,o);return l.get("/run/:functionId/*",u),l.post("/run/:functionId/*",u),l.put("/run/:functionId/*",u),l.patch("/run/:functionId/*",u),l.delete("/run/:functionId/*",u),l.get("/run/:functionId",u),l.post("/run/:functionId",u),l.put("/run/:functionId",u),l.patch("/run/:functionId",u),l.delete("/run/:functionId",u),l.start()}if(import.meta.url===`file://${process.argv[1]}`){let e=T(),r=process.argv.slice(2).find(o=>o.startsWith("--port=")),n=r?parseInt(r.split("=")[1],10):e.services.functions.port,s=gt({api:{port:n}},"functions");Gt(s)}export{K as FunctionsService,Gt as startServer};
25
+ `}async executeFunction(e,r){try{let n=this.functions.get(e);if(!n)return r.json({error:"Not Found",message:"Function not found"},404);if(n.triggers&&n.triggers.length>0&&!n.triggers.some(p=>p.type==="http"))return r.json({error:"Not Found",message:"Function not found"},404);if(n.allowUnauthenticated!==!0&&!r.headers.authorization)return r.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(n.methods&&n.methods.length>0){let p=(r.req.method||"GET").toUpperCase();if(!n.methods.includes(p)){let h=n.methods.join(", "),g=r.json({error:"Method Not Allowed",message:`This function only accepts: ${h}`},405);return g.headers={...g.headers||{},allow:h},g}}let s=null;try{let p=r.req.method||"GET";["POST","PUT","PATCH"].includes(p)&&((r.headers["content-type"]||"").includes("application/json")?s=await F(r):s=r.body)}catch{}let i=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],o={},a=r.req.headers;for(let[p,h]of Object.entries(a))(n.passAllHeaders||!i.includes(p.toLowerCase()))&&(o[p]=h);let c=new URL(r.req.url||"","http://127.0.0.1").pathname,f=`/run/${e}`,l=c.startsWith(f)?c.substring(f.length):"/";l||(l="/");let u={};if(n.bindings&&n.bindings.length>0){let h=r.headers.authorization?.replace(/^Bearer\s+/i,"")||null,g=x(),m={databases:g.services.databases.url,storage:g.services.storage.url,observability:g.services.observability.url,sites:g.services.sites.url,functions:g.services.functions.url};u=new j(m,h,H(),ne()).createBindings(n.bindings)}let d={request:{method:r.req.method||"GET",path:c,subpath:l,query:r.query,headers:o,body:s},functionId:e,functionName:n.name,bindings:u};try{let g=(await import(`${Te(n.filePath).href}?t=${Date.now()}`)).default;if(typeof g!="function")return r.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:m,restore:C}=this.createConsoleInterceptor(e,n.name);Object.assign(console,m);let y;try{y=await g(d.request,d)}finally{C()}if(y&&typeof y=="object"){if(y.statusCode!==void 0&&y.body!==void 0){let A=y.statusCode||200,E=y.headers||{};if(typeof y.body=="object"){let P=r.json(y.body,A);return Object.keys(E).length>0&&(P.headers={...P.headers||{},...E}),P}let T=r.text(y.body,A);return Object.keys(E).length>0&&(T.headers={...T.headers||{},...E}),T}return r.json(y)}return typeof y=="string"?r.text(y):typeof y=="number"||typeof y=="boolean"?r.json({result:y}):r.json({result:y===null?null:void 0})}catch(p){return console.error("Function execution error:",p),r.json({error:"Function Execution Error",message:this.debug?p.message:"Error executing function",stack:this.debug?p.stack:void 0},500)}}catch(n){return console.error("Error processing function execution:",n),r.json({error:"Internal Server Error",message:this.debug?n.message:"Failed to process function execution"},500)}}subscribeEventTriggeredFunctions(){for(let e of this.functions.values())this.subscribeToEvents(e)}subscribeToEvents(e){if(!e.triggers||e.triggers.length===0)return;this.unsubscribeFromEvents(e.id);let r=H();for(let n of e.triggers){if(n.type!=="event"||!n.eventName)continue;let s=n.eventName,i=async a=>{await this.executeFunctionFromEvent(e.id,s,a)},o=`${e.id}:${s}`;this.eventHandlers.set(o,i),r.on(s,i)}}unsubscribeFromEvents(e){let r=H(),n=`${e}:`;for(let[s,i]of this.eventHandlers.entries())if(s.startsWith(n)){let o=s.substring(n.length);r.off(o,i),this.eventHandlers.delete(s)}}async executeFunctionFromEvent(e,r,n){if(this.eventChainDepth>=t.MAX_EVENT_CHAIN_DEPTH){console.error(`Event chain depth limit (${t.MAX_EVENT_CHAIN_DEPTH}) exceeded. Dropping event "${r}" for function "${e}". This likely indicates an infinite loop.`);return}let s=this.functions.get(e);if(s){this.eventChainDepth++;try{let i={};if(s.bindings&&s.bindings.length>0){let p=x(),h={databases:p.services.databases.url,storage:p.services.storage.url,observability:p.services.observability.url,sites:p.services.sites.url,functions:p.services.functions.url};i=new j(h,null,H(),ne()).createBindings(s.bindings)}let o={eventName:r,data:n,timestamp:Date.now(),id:te()},a={functionId:e,functionName:s.name,bindings:i},l=(await import(`${Te(s.filePath).href}?t=${Date.now()}`)).default;if(typeof l!="function")return;let{interceptedConsole:u,restore:d}=this.createConsoleInterceptor(e,s.name);Object.assign(console,u);try{return await l(o,a)}finally{d()}}catch(i){console.error(`Event-triggered function execution error (${e}):`,i.message)}finally{this.eventChainDepth--}}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(r=>({id:r.id,name:r.name,endpoint:r.endpoint,createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()}))}}createConsoleInterceptor(e,r){let n={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),debug:console.debug.bind(console)},s=(i,o)=>{let a=o.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" ");we({functionId:e,functionName:r,level:i,message:a,timestamp:Date.now()})};return{interceptedConsole:{log:(...i)=>{n.log(...i),s("info",i)},error:(...i)=>{n.error(...i),s("error",i)},warn:(...i)=>{n.warn(...i),s("warn",i)},info:(...i)=>{n.info(...i),s("info",i)},debug:(...i)=>{n.debug(...i),s("debug",i)}},restore:()=>{console.log=n.log,console.error=n.error,console.warn=n.warn,console.info=n.info,console.debug=n.debug}}}};async function Qe(t){let e=t.dataPath||"data",r=k(e,"functions"),n=t.debug||!1,s=new ie({functionsDir:r,debug:n});await s.start();let i=Ce(t.identityApiUrl),o=Ee(t.contextApiUrl),a=Q(),c=x(),f=c.services.observability.url,l=c.internalServiceSecret;a.on("function.log",h=>{let g={"Content-Type":"application/json"};l&&(g["x-molnos-service-token"]=l),fetch(`${f}/events`,{method:"POST",headers:g,body:JSON.stringify({service:`functions.${h.functionId}`,level:h.level,message:h.message,metadata:{functionId:h.functionId,functionName:h.functionName,...h.metadata}})}).catch(m=>{n&&console.error("Failed to send log to observability service:",m)})});let u=new J({port:t.api.port||c.services.functions.port,host:t.api.host||c.services.functions.host,rateLimit:t.rateLimit||{enabled:!1,requestsPerMinute:0}});u.post("/deploy",async h=>he(h,s,i)),u.get("/list",async h=>be(h,s,i,o)),u.get("/stats",async h=>{try{let g=s.getStats();return h.json({success:!0,stats:g})}catch(g){return h.json({error:g.message},500)}}),u.get("/:functionId/config",async h=>{try{let g=h.params.functionId,m=s.getFunction(g);if(!m)return h.json({error:"Function not found"},404);let C="";try{let y=await Pe(m.filePath,"utf8"),A="// User function code starts here",E="// User function code ends here",T=y.indexOf(A),P=y.indexOf(E);T!==-1&&P!==-1?(C=y.substring(T+A.length,P).trim().replace(/^\n+/,"").replace(/\n+$/,""),C=C.replace(/\n*export\s+default\s+handler;\s*$/,"")):C=y}catch(y){return h.json({error:"Failed to read function code",message:y.message},500)}return h.json({success:!0,function:{id:m.id,name:m.name,endpoint:m.endpoint,filePath:m.filePath,code:C,...m.methods?{methods:m.methods}:{},...m.bindings?{bindings:m.bindings}:{},...m.triggers&&m.triggers.length>0?{triggers:m.triggers}:{},...m.passAllHeaders!==void 0?{passAllHeaders:m.passAllHeaders}:{},...m.allowUnauthenticated!==void 0?{allowUnauthenticated:m.allowUnauthenticated}:{},createdAt:new Date(m.createdAt).toISOString(),updatedAt:new Date(m.updatedAt).toISOString()}})}catch(g){return h.json({error:g.message},500)}}),u.get("/:functionId",async h=>ve(h,s,i)),u.put("/:functionId",async h=>me(h,s,i)),u.delete("/:functionId",async h=>ye(h,s,i));let d=async h=>pe(h,s,i);return u.get("/run/:functionId/*",d),u.post("/run/:functionId/*",d),u.put("/run/:functionId/*",d),u.patch("/run/:functionId/*",d),u.delete("/run/:functionId/*",d),u.get("/run/:functionId",d),u.post("/run/:functionId",d),u.put("/run/:functionId",d),u.patch("/run/:functionId",d),u.delete("/run/:functionId",d),u.start()}if(import.meta.url===`file://${process.argv[1]}`){let t=x(),r=process.argv.slice(2).find(i=>i.startsWith("--port=")),n=r?parseInt(r.split("=")[1],10):t.services.functions.port,s=xe({api:{port:n}},"functions");Qe(s)}export{ie as FunctionsService,Qe as startServer};