molnos 1.4.2 → 1.5.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,14 +1,14 @@
1
1
  // MolnOS Core - See LICENSE file for copyright and license details.
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:
2
+ import{existsSync as V}from"node:fs";import{join as M}from"node:path";import{mkdir as rt,writeFile as ie,readFile as je,unlink as nt}from"node:fs/promises";import{pathToFileURL as Re}from"node:url";var ae=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 Ae}from"url";var ce=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 Ae(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",h=200)=>({statusCode:h,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,h="application/octet-stream")=>({statusCode:u,body:d,headers:{"Content-Type":h,"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,h=302)=>({statusCode:h,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 H=()=>({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 z=class extends Error{constructor(t){super(t),this.name="ValidationError",this.message=t||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as $e,readFileSync as Oe}from"node:fs";var _=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&&$e(t))try{let a=Oe(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 z(t.message);if(typeof r=="string")throw new z(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
4
  `;for(let e of this.options)t+=`${e.flag}${e.isFlag?"":" <value>"}
5
5
  `,e.description&&(t+=` ${e.description}
6
6
  `),e.defaultValue!==void 0&&(t+=` Default: ${JSON.stringify(e.defaultValue)}
7
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
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=H(),ue=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 le(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=ke(t,s);for(let f of c){if(f.length===0||f.equals(i.subarray(s.length)))continue;let l=Me(f);if(!l)continue;let{name:u,filename:d,contentType:h,data:p}=l;if(d){let g={filename:d,contentType:h||"application/octet-stream",data:p,size:p.length};a[u]?Array.isArray(a[u])?a[u].push(g):a[u]=[a[u],g]:a[u]=g}else{let g=p.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 ke(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 Me(t){let e=Buffer.from(`\r
9
9
  \r
10
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
11
+ `),a="",c="",f,l;for(let d of o){let h=d.toLowerCase();if(h.startsWith("content-disposition:")){a=d.substring(20).trim();let p=a.match(/name="([^"]+)"/);p&&(c=p[1]);let g=a.match(/filename="([^"]+)"/);g&&(f=g[1])}else h.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 R}from"fs";import J from"http";import He from"http2";import Ne from"https";var W=class{config;rateLimiter;router;shutdownHandlers=[];constructor(t){let e=new _(ue(t||{})).get();e.debug&&console.log("Using configuration:",e),this.config=e,this.router=new ce;let r=e.rateLimit.requestsPerMinute||H().rateLimit.requestsPerMinute;this.rateLimiter=new ae(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:R(this.config.sslKey),cert:R(this.config.sslCert),...this.config.sslCa?{ca:R(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:R(this.config.sslKey),cert:R(this.config.sslCert),...this.config.sslCa?{ca:R(this.config.sslCa)}:{}};return Ne.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 J.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 J.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"),h={};new URLSearchParams(d).forEach((p,g)=>{h[g]=p}),e(h)}else if(f.includes("multipart/form-data"))try{let d=le(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 J.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 N=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};var F=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","builder"];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 X=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}},Y=class extends X{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)}},K=class{constructor(e){this.schemaRegistry=e}validate(e,r,n){return this.schemaRegistry.validate(e,r,n)}},$=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 Y(s,this.authToken,e);break}case"events":this.eventBus&&(r.events=new Z(this.eventBus));break;case"schemas":this.schemaRegistry&&(r.schemas=new K(this.schemaRegistry));break}return r}};var O=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 j(t){return t.body||{}}function S(t,e="An error occurred"){let r=t?.message||t||e,n=t?.cause?.statusCode||t?.statusCode||400;return{message:r,status:n}}function de(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.some(a=>De(a,o)))){let o=new Error("Unauthorized");throw o.cause={statusCode:403},o}return!0}function De(t,e){if(t==="*"||t===e)return!0;if(!t.includes("*"))return!1;let r=t.split("*").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${r}$`).test(e)}function fe(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)&&!(c.targets&&c.targets.length>0&&(!s||!c.targets.includes(s)&&!c.targets.includes("*"))))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 Le,existsSync as Ue}from"node:fs";function E(){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||!Ue(t))return e;try{let r=Le(t,"utf-8");return JSON.parse(r)}catch(r){return console.error("[loadRuntimeConfig] Failed to load runtime config:",r),e}}async function x(t,e,r,n,s,i,o){if(!e)return null;let a=t.headers["x-molnos-service-token"];if(a){let l=E();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}}de(c,r,{});let f=t.headers["x-function-bindings"];if(f)try{let l=Array.isArray(f)?f[0]:f,u=JSON.parse(l);fe(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 w={applications:{application:{create:"applications.application.create",read:"applications.application.read",list:"applications.application.list",update:"applications.application.update",delete:"applications.application.delete"}},builder:{artifact:{read:"builder.artifact.read",list:"builder.artifact.list",update:"builder.artifact.update"},revision:{create:"builder.revision.create",read:"builder.revision.read",list:"builder.revision.list",activate:"builder.revision.activate"},run:{plan:"builder.run.plan",import:"builder.run.import",generate:"builder.run.generate",evolve:"builder.run.evolve",apply:"builder.run.apply",evaluate:"builder.run.evaluate",read:"builder.run.read",list:"builder.run.list"}},contexts:{context:{create:"contexts.context.create",get:"contexts.context.get",update:"contexts.context.update",delete:"contexts.context.delete",deleteResources:"contexts.context.delete-resources"}},databases:{table:{create:"databases.table.create",get:"databases.table.get",update:"databases.table.update",delete:"databases.table.delete"}},functions:{function:{create:"functions.function.create",get:"functions.function.get",update:"functions.function.update",delete:"functions.function.delete",execute:"functions.function.execute"}},iac:{config:{create:"iac.config.create",get:"iac.config.get"}},identity:{identities:{get:"identity.identities.get"},user:{create:"identity.user.create",get:"identity.user.get",update:"identity.user.update",delete:"identity.user.delete"},role:{create:"identity.role.create",get:"identity.role.get",update:"identity.role.update",delete:"identity.role.delete"},serviceAccount:{create:"identity.service-account.create",get:"identity.service-account.get",update:"identity.service-account.update",delete:"identity.service-account.delete"}},management:{service:{create:"management.service.create",get:"management.service.get",update:"management.service.update",delete:"management.service.delete",start:"management.service.start",stop:"management.service.stop"},services:{get:"management.services.get"}},observability:{event:{create:"observability.event.create",read:"observability.event.read",delete:"observability.event.delete"},stats:{read:"observability.stats.read"},buffer:{write:"observability.buffer.write"},metrics:{read:"observability.metrics.read"}},schemas:{schema:{create:"schemas.schema.create",read:"schemas.schema.read",list:"schemas.schema.list",update:"schemas.schema.update",delete:"schemas.schema.delete"}},sites:{project:{create:"sites.project.create",list:"sites.project.list",delete:"sites.project.delete",download:"sites.project.download"}},storage:{bucket:{create:"storage.bucket.create",read:"storage.bucket.read",update:"storage.bucket.update",delete:"storage.bucket.delete",list:"storage.bucket.list"},object:{write:"storage.object.write",read:"storage.object.read",delete:"storage.object.delete",list:"storage.object.list"}}};function pe(t,e){if(typeof t=="string"){e.push(t);return}if(!(!t||typeof t!="object"))for(let r of Object.values(t))pe(r,e)}var he=[];pe(w,he);var qe=[...new Set(he)],pr=Object.freeze(qe);var ge={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 Ve=new O(!0);async function me(t,e,r){try{let n=await j(t),s=Ve.test(ge,n);if(!s.success)return t.json({error:"Invalid input",details:s.errors},400);await x(t,r,w.functions.function.create,"functions","function","create");let{id:i,name:o,code:a,methods:c,bindings:f,trigger:l,triggers:u,passAllHeaders:d,allowUnauthenticated:h}=n,p=u||(l?[l]:void 0),g=await e.deployFunction(o,a,c,f,p,d,h,i);return t.json({success:!0,function:g},201)}catch(n){let{message:s,status:i}=S(n,"Error deploying function");return t.json({error:s},i)}}async function ye(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 x(t,r,w.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}=S(n,"Error executing function");return t.json({error:s},i)}}var ve={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 _e=new O(!0);async function be(t,e,r){try{let n=t.params.functionId,s=await j(t);if(!n)return t.json({error:"functionId is required"},400);let i=_e.test(ve,s);if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);await x(t,r,w.functions.function.update,"functions","function","update",n);let{code:o,methods:a,bindings:c,trigger:f,triggers:l,passAllHeaders:u,allowUnauthenticated:d}=s,h=l||(f?[f]:void 0),p=await e.updateFunction(n,{code:o,methods:a,bindings:c,triggers:h,passAllHeaders:u,allowUnauthenticated:d});return p?t.json({success:!0,function:p},200):t.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=S(n,"Error updating function");return t.json({error:s},i)}}async function we(t,e,r){try{let n=t.params.functionId;return n?(await x(t,r,w.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}=S(n,"Error deleting function");return t.json({error:s},i)}}async function Se(t,e,r){try{let n=t.params.functionId;if(!n)return t.json({error:"functionId is required"},400);await x(t,r,w.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}=S(n,"Error getting function");return t.json({error:s},i)}}async function xe(t,e,r,n){try{await x(t,r,w.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}=S(s,"Error listing functions");return t.json({error:i},o)}}import{EventEmitter as Ge}from"node:events";var Q=class t{static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new Ge,t.instance.setMaxListeners(100)),t.instance}};function ee(){return Q.getInstance()}function Ee(t){let e=ee();try{e.emit("function.log",t)}catch(r){console.error("Failed to emit function log event:",r)}}import{getRandomValues as Je}from"node:crypto";var te=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);Je(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 We=8,Xe=40,Ye=/^[a-zA-Z0-9_-]{1,40}$/;function Ze(){return new te().create(We,"alphanumeric",!1,!0)}function Ke(t){return Ye.test(t)}function Qe(t){if(!Ke(t))throw new Error(`Invalid ID format: "${t}". IDs must be 1-${Xe} characters using only alphanumeric characters, underscores, and hyphens.`)}function re(t){return t?(Qe(t),t):Ze()}import{EventEmitter as et}from"events";var ne=class{emitter;targets={};options;constructor(t){this.emitter=new et,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 U=null;function k(){return U||(U=new ne,U.addTarget({name:"molnos-internal",events:["*"]})),U}var tt=null;function se(){return tt||void 0}function Ce(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 Pe(t,e){let r=t?.api?.port;if(!r)throw new Error('Missing "port" input when create API service!');let n=E(),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=Ce(e,n.molnos.rateLimit)),{dataPath:s,api:{port:r,host:i},...o?{identityApiUrl:o}:{},...a?{contextApiUrl:a}:{},...f?{rateLimit:f}:{},debug:c}}var q=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 Te(t){return t?new q(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 Ie(t){return t?new B(t):null}var oe=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||M(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(){V(this.functionsDir)||await rt(this.functionsDir,{recursive:!0})}async loadExistingFunctions(){try{let e=M(this.functionsDir,"functions.json");if(V(e)){let r=await je(e,"utf8"),n=JSON.parse(r);for(let s of n)V(s.filePath)&&this.functions.set(s.id,s)}}catch{}}async saveFunctionsMetadata(){try{let e=M(this.functionsDir,"functions.json"),r=Array.from(this.functions.values());await ie(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 p=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let g of n)if(!p.includes(g.toUpperCase()))throw new F(`Invalid HTTP method: ${g}. Must be one of: ${p.join(", ")}`)}if(s&&s.length>0&&this.bindingService.validateBindings(s),i&&i.length>0){for(let p of i)if(p.type==="event"&&!p.eventName)throw new v("Event trigger must specify an eventName")}let f=re(c),l=M(this.functionsDir,`${f}.mjs`),u=this.wrapFunctionCode(r);await ie(l,u,"utf8");let d=Date.now(),h={id:f,name:e,filePath:l,endpoint:`/functions/run/${f}`,...n&&n.length>0?{methods:n.map(p=>p.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,h),await this.saveFunctionsMetadata(),this.subscribeToEvents(h),h}async updateFunction(e,r){let n=this.functions.get(e);if(!n)throw new N(`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 F(`Invalid HTTP method: ${u}. Must be one of: ${l.join(", ")}`)}if(s!==void 0){let l=this.wrapFunctionCode(s);await ie(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),V(r.filePath)&&await nt(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
@@ -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(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};
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(h=>h.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 h=(r.req.method||"GET").toUpperCase();if(!n.methods.includes(h)){let p=n.methods.join(", "),g=r.json({error:"Method Not Allowed",message:`This function only accepts: ${p}`},405);return g.headers={...g.headers||{},allow:p},g}}let s=null;try{let h=r.req.method||"GET";["POST","PUT","PATCH"].includes(h)&&((r.headers["content-type"]||"").includes("application/json")?s=await j(r):s=r.body)}catch{}let i=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],o={},a=r.req.headers;for(let[h,p]of Object.entries(a))(n.passAllHeaders||!i.includes(h.toLowerCase()))&&(o[h]=p);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 p=r.headers.authorization?.replace(/^Bearer\s+/i,"")||null,g=E(),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 $(m,p,k(),se()).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(`${Re(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,P=y.headers||{};if(typeof y.body=="object"){let I=r.json(y.body,A);return Object.keys(P).length>0&&(I.headers={...I.headers||{},...P}),I}let T=r.text(y.body,A);return Object.keys(P).length>0&&(T.headers={...T.headers||{},...P}),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(h){return console.error("Function execution error:",h),r.json({error:"Function Execution Error",message:this.debug?h.message:"Error executing function",stack:this.debug?h.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=k();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=k(),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 h=E(),p={databases:h.services.databases.url,storage:h.services.storage.url,observability:h.services.observability.url,sites:h.services.sites.url,functions:h.services.functions.url};i=new $(p,null,k(),se()).createBindings(s.bindings)}let o={eventName:r,data:n,timestamp:Date.now(),id:re()},a={functionId:e,functionName:s.name,bindings:i},l=(await import(`${Re(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(" ");Ee({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 st(t){let e=t.dataPath||"data",r=M(e,"functions"),n=t.debug||!1,s=new oe({functionsDir:r,debug:n});await s.start();let i=Te(t.identityApiUrl),o=Ie(t.contextApiUrl),a=ee(),c=E(),f=c.services.observability.url,l=c.internalServiceSecret;a.on("function.log",p=>{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.${p.functionId}`,level:p.level,message:p.message,metadata:{functionId:p.functionId,functionName:p.functionName,...p.metadata}})}).catch(m=>{n&&console.error("Failed to send log to observability service:",m)})});let u=new W({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 p=>me(p,s,i)),u.get("/list",async p=>xe(p,s,i,o)),u.get("/stats",async p=>{try{let g=s.getStats();return p.json({success:!0,stats:g})}catch(g){return p.json({error:g.message},500)}}),u.get("/:functionId/config",async p=>{try{let g=p.params.functionId,m=s.getFunction(g);if(!m)return p.json({error:"Function not found"},404);let C="";try{let y=await je(m.filePath,"utf8"),A="// User function code starts here",P="// User function code ends here",T=y.indexOf(A),I=y.indexOf(P);T!==-1&&I!==-1?(C=y.substring(T+A.length,I).trim().replace(/^\n+/,"").replace(/\n+$/,""),C=C.replace(/\n*export\s+default\s+handler;\s*$/,"")):C=y}catch(y){return p.json({error:"Failed to read function code",message:y.message},500)}return p.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 p.json({error:g.message},500)}}),u.get("/:functionId",async p=>Se(p,s,i)),u.put("/:functionId",async p=>be(p,s,i)),u.delete("/:functionId",async p=>we(p,s,i));let d=async p=>ye(p,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=E(),r=process.argv.slice(2).find(i=>i.startsWith("--port=")),n=r?parseInt(r.split("=")[1],10):t.services.functions.port,s=Pe({api:{port:n}},"functions");st(s)}export{oe as FunctionsService,st as startServer};