molnos 1.2.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/VERSION +1 -1
- package/dist/databases.mjs +8 -8
- package/dist/functions.mjs +10 -10
- package/dist/molnos_core.mjs +306 -17
- package/dist/observability.mjs +5 -5
- package/dist/sites.mjs +3 -3
- package/dist/storage.mjs +1 -1
- package/package.json +2 -2
- package/sbom.json +1 -1
package/VERSION
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
1.
|
|
1
|
+
1.4.0
|
package/dist/databases.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// MolnOS Core - See LICENSE file for copyright and license details.
|
|
2
|
-
var D=class{requests=new Map;limit;windowMs;constructor(
|
|
2
|
+
var D=class{requests=new Map;limit;windowMs;constructor(e=100,t=60){this.limit=e,this.windowMs=t*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return(!r||r.resetTime<t)&&(r={count:0,resetTime:t+this.windowMs},this.requests.set(s,r)),r.count++,r.count<=this.limit}getRemainingRequests(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return!r||r.resetTime<t?this.limit:Math.max(0,this.limit-r.count)}getResetTime(e){let t=Date.now(),s=e||"unknown",r=this.requests.get(s);return!r||r.resetTime<t?Math.floor((t+this.windowMs)/1e3):Math.floor(r.resetTime/1e3)}cleanup(){let e=Date.now();for(let[t,s]of this.requests.entries())s.resetTime<e&&this.requests.delete(t)}};import{URL as he}from"url";var q=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(e){return this.globalMiddlewares.push(e),this}get(e,...t){let s=t.pop();return this.register("GET",e,s,t)}post(e,...t){let s=t.pop();return this.register("POST",e,s,t)}put(e,...t){let s=t.pop();return this.register("PUT",e,s,t)}delete(e,...t){let s=t.pop();return this.register("DELETE",e,s,t)}patch(e,...t){let s=t.pop();return this.register("PATCH",e,s,t)}any(e,...t){let s=t.pop(),r=t;return this.register("GET",e,s,r),this.register("POST",e,s,r),this.register("PUT",e,s,r),this.register("DELETE",e,s,r),this.register("PATCH",e,s,r),this.register("OPTIONS",e,s,r),this}options(e,...t){let s=t.pop();return this.register("OPTIONS",e,s,t)}match(e,t){for(let s of this.routes){if(s.method!==e)continue;let r=this.pathPatterns.get(s.path);if(!r)continue;let i=r.pattern.exec(t);if(!i)continue;let o={};return r.paramNames.forEach((n,a)=>{o[n]=i[a+1]||""}),{route:s,params:o}}return null}async handle(e,t){let s=e.method||"GET",r=new he(e.url||"/",`http://${e.headers.host}`),i=r.pathname,o=this.match(s,i);if(!o)return null;let{route:n,params:a}=o,c={};r.searchParams.forEach((u,d)=>{c[d]=u});let l={req:e,res:t,params:a,query:c,body:e.body||{},headers:e.headers,path:i,state:{},raw:()=>t,binary:(u,d="application/octet-stream",y=200)=>({statusCode:y,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:()=>t,binary:(d,y="application/octet-stream")=>({statusCode:u,body:d,headers:{"Content-Type":y,"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,y=302)=>({statusCode:y,body:null,headers:{Location:d}}),status:d=>this.status(d)}}},f=[...this.globalMiddlewares,...n.middlewares];return this.executeMiddlewareChain(l,f,n.handler)}register(e,t,s,r=[]){return this.routes.push({method:e,path:t,handler:s,middlewares:r}),this.pathPatterns.set(t,this.createPathPattern(t)),this}createPathPattern(e){let t=[],s=e.replace(/\/:[^/]+/g,r=>{let i=r.slice(2);return t.push(i),"/([^/]+)"});return s.endsWith("/*")?(s=`${s.slice(0,-2)}(?:/(.*))?`,t.push("wildcard")):s=s.replace(/\/$/,"/?"),{pattern:new RegExp(`^${s}$`),paramNames:t}}async executeMiddlewareChain(e,t,s){let r=0,i=async()=>{if(r<t.length){let o=t[r++];return o(e,i)}return s(e)};return i()}};var E=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:pe(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function pe(e){return e==="true"||e===!0}var $=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as me,readFileSync as ye}from"node:fs";var I=class{config={};options=[];validators=[];autoValidate=!0;constructor(e){let t=e?.configFilePath,s=e?.args||[],r=e?.config||{};this.options=e?.options||[],this.validators=e?.validators||[],e?.autoValidate!==void 0&&(this.autoValidate=e.autoValidate),this.config=this.createConfig(t,s,r)}deepMerge(e,t){let s={...e};for(let r in t)t[r]!==void 0&&(t[r]!==null&&typeof t[r]=="object"&&!Array.isArray(t[r])&&r in e&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])?s[r]=this.deepMerge(e[r],t[r]):t[r]!==void 0&&(s[r]=t[r]));return s}setValueAtPath(e,t,s){let r=t.split("."),i=e;for(let n=0;n<r.length-1;n++){let a=r[n];!(a in i)||i[a]===null?i[a]={}:typeof i[a]!="object"&&(i[a]={}),i=i[a]}let o=r[r.length-1];i[o]=s}getValueAtPath(e,t){let s=t.split("."),r=e;for(let i of s){if(r==null)return;r=r[i]}return r}createConfig(e,t=[],s={}){let r={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(r,a.path,a.defaultValue);let i={};if(e&&me(e))try{let a=ye(e,"utf8");i=JSON.parse(a),console.log(`Loaded configuration from ${e}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let o=this.parseCliArgs(t),n=this.deepMerge({},r);return n=this.deepMerge(n,i),n=this.deepMerge(n,s),n=this.deepMerge(n,o),n}parseCliArgs(e){let t={},s=e[0]?.endsWith("node")||e[0]?.endsWith("node.exe")?2:0;for(;s<e.length;){let r=e[s++],i=this.options.find(o=>o.flag===r);if(i)if(i.isFlag)this.setValueAtPath(t,i.path,!0);else if(s<e.length&&!e[s].startsWith("-")){let o=e[s++];if(i.parser)try{o=i.parser(o)}catch(n){console.error(`Error parsing value for ${i.flag}: ${n instanceof Error?n.message:String(n)}`);continue}if(i.validator){let n=i.validator(o);if(n!==!0&&typeof n=="string"){console.error(`Invalid value for ${i.flag}: ${n}`);continue}if(n===!1){console.error(`Invalid value for ${i.flag}`);continue}}this.setValueAtPath(t,i.path,o)}else console.error(`Missing value for option ${r}`)}return t}validate(){for(let e of this.validators){let t=this.getValueAtPath(this.config,e.path),s=e.validator(t,this.config);if(s===!1)throw new $(e.message);if(typeof s=="string")throw new $(s)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(e,t){let s=this.getValueAtPath(this.config,e);return s!==void 0?s:t}setValue(e,t){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let s=this.getValueAtPath(this.config,e)||{};if(typeof s=="object"&&!Array.isArray(s)){let r=this.deepMerge(s,t);this.setValueAtPath(this.config,e,r);return}}this.setValueAtPath(this.config,e,t)}getHelpText(){let e=`Available configuration options:
|
|
3
3
|
|
|
4
|
-
`;for(let
|
|
5
|
-
`,
|
|
6
|
-
`),
|
|
7
|
-
`),
|
|
8
|
-
`;return
|
|
4
|
+
`;for(let t of this.options)e+=`${t.flag}${t.isFlag?"":" <value>"}
|
|
5
|
+
`,t.description&&(e+=` ${t.description}
|
|
6
|
+
`),t.defaultValue!==void 0&&(e+=` Default: ${JSON.stringify(t.defaultValue)}
|
|
7
|
+
`),e+=`
|
|
8
|
+
`;return e}};var O={int:e=>{let t=e.trim();if(!/^[+-]?\d+$/.test(t))throw new Error(`Cannot parse "${e}" as an integer`);let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new Error(`Cannot parse "${e}" as an integer`);return s},float:e=>{let t=e.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)){if(t==="Infinity"||t==="-Infinity")return t==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${e}" as a number`)}let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error(`Cannot parse "${e}" as a number`);return s},boolean:e=>{let t=e.trim().toLowerCase();if(["true","yes","1","y"].includes(t))return!0;if(["false","no","0","n"].includes(t))return!1;throw new Error(`Cannot parse "${e}" as a boolean`)},array:e=>e.split(",").map(t=>t.trim()),json:e=>{try{return JSON.parse(e)}catch{throw new Error(`Cannot parse "${e}" as JSON`)}}};var g=E(),z=e=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:g.port},{flag:"--host",path:"host",defaultValue:g.host},{flag:"--https",path:"useHttps",defaultValue:g.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:g.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:g.sslCert},{flag:"--key",path:"sslKey",defaultValue:g.sslKey},{flag:"--ca",path:"sslCa",defaultValue:g.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:g.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:g.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:g.allowedDomains,parser:O.array},{flag:"--debug",path:"debug",defaultValue:g.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:g.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:g.requestTimeout}],config:e});function B(e,t){let s=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!s)throw new Error("Invalid multipart/form-data: missing boundary");let r=s[1]||s[2],i=Buffer.from(`--${r}`),o=Buffer.from(`--${r}--`),n={},a={},c=ge(e,i);for(let l of c){if(l.length===0||l.equals(o.subarray(i.length)))continue;let f=be(l);if(!f)continue;let{name:u,filename:d,contentType:y,data:w}=f;if(d){let b={filename:d,contentType:y||"application/octet-stream",data:w,size:w.length};a[u]?Array.isArray(a[u])?a[u].push(b):a[u]=[a[u],b]:a[u]=b}else{let b=w.toString("utf8");n[u]?Array.isArray(n[u])?n[u].push(b):n[u]=[n[u],b]:n[u]=b}}return{fields:n,files:a}}function ge(e,t){let s=[],r=0;for(;r<e.length;){let i=e.indexOf(t,r);if(i===-1)break;r!==i&&s.push(e.subarray(r,i)),r=i+t.length,r<e.length&&e[r]===13&&e[r+1]===10&&(r+=2)}return s}function be(e){let t=Buffer.from(`\r
|
|
9
9
|
\r
|
|
10
|
-
`),s=
|
|
11
|
-
`),a="",c="",l,f;for(let u of o){let y=u.toLowerCase();if(y.startsWith("content-disposition:")){a=u.substring(20).trim();let w=a.match(/name="([^"]+)"/);w&&(c=w[1]);let b=a.match(/filename="([^"]+)"/);b&&(l=b[1])}else y.startsWith("content-type:")&&(f=u.substring(13).trim())}if(!c)return null;let d=i;return d.length>=2&&d[d.length-2]===13&&d[d.length-1]===10&&(d=d.subarray(0,d.length-2)),{disposition:a,name:c,filename:l,contentType:f,data:d}}import{readFileSync as x}from"fs";import k from"http";import wt from"http2";import vt from"https";var L=class{config;rateLimiter;router;shutdownHandlers=[];constructor(t){let e=new I(z(t||{})).get();e.debug&&console.log("Using configuration:",e),this.config=e,this.router=new q;let s=e.rateLimit.requestsPerMinute||E().rateLimit.requestsPerMinute;this.rateLimiter=new D(s,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:s}=this.config;return this.setupGracefulShutdown(t),t.listen(e,s,()=>{let r=t.address(),i=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${i}://${r.address!=="::"?r.address:"localhost"}:${r.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:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return wt.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:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return vt.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 k.createServer(t)}async rateLimitMiddleware(t,e){let s=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(s).toString()),t.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(s).toString()),this.rateLimiter.isAllowed(s)?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 s=Date.now(),r=t.method||"UNKNOWN",i=t.url||"/unknown",n=this.config.debug;try{if(this.setCorsHeaders(e,t),this.setSecurityHeaders(e,this.config.useHttps),n&&console.log(`${r} ${i}`),t.method==="OPTIONS"){if(e instanceof k.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 n&&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:n?o.message:"An unexpected error occurred"}})}finally{n&&this.logDuration(s,r,i)}}logDuration(t,e,s){let r=Date.now()-t;console.log(`${e} ${s} completed in ${r}ms`)}async parseBody(t){return new Promise((e,s)=>{let r=[],i=0,n=this.config.maxBodySize,o=!1,a=null,c=this.config.debug,l=t.headers["content-type"]||"";c&&console.log("Content-Type:",l),this.config.requestTimeout>0&&(a=setTimeout(()=>{o||(o=!0,c&&console.log("Request timeout exceeded"),s(new Error("Request timeout")))},this.config.requestTimeout));let f=()=>{a&&(clearTimeout(a),a=null)};t.on("data",d=>{if(!o){if(i+=d.length,c&&console.log(`Received chunk: ${d.length} bytes, total size: ${i}`),i>n){o=!0,f(),c&&console.log(`Body size exceeded limit: ${i} > ${n}`),s(new Error("Request body too large"));return}r.push(d)}}),t.on("end",()=>{if(!o){o=!0,f(),c&&console.log(`Request body complete: ${i} bytes`);try{if(r.length>0){let d=Buffer.concat(r);if(l.includes("application/json"))try{let u=d.toString("utf8");e(JSON.parse(u))}catch(u){s(new Error(`Invalid JSON in request body: ${u.message}`))}else if(l.includes("application/x-www-form-urlencoded")){let u=d.toString("utf8"),y={};new URLSearchParams(u).forEach((w,b)=>{y[b]=w}),e(y)}else if(l.includes("multipart/form-data"))try{let u=B(d,l);e(u)}catch(u){s(new Error(`Invalid multipart form data: ${u.message}`))}else this.isBinaryContentType(l)?e(d):e(d.toString("utf8"))}else e({})}catch(d){s(new Error(`Invalid request body: ${d}`))}}}),t.on("error",d=>{o||(o=!0,f(),s(new Error(`Error reading request body: ${d.message}`)))}),t.on("close",()=>{f()})})}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(s=>t.includes(s))}setCorsHeaders(t,e){let s=e.headers.origin,{allowedDomains:r=["*"]}=this.config;!s||r.length===0||r.includes("*")?t.setHeader("Access-Control-Allow-Origin","*"):r.includes(s)&&(t.setHeader("Access-Control-Allow-Origin",s),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 s={"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)&&(s["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),t instanceof k.ServerResponse)Object.entries(s).forEach(([r,i])=>{t.setHeader(r,i)});else{let r=t;Object.entries(s).forEach(([i,n])=>{r.setHeader(i,n)})}}respond(t,e){let s={...e.headers||{}};(i=>typeof i.writeHead=="function"&&typeof i.end=="function")(t)?(t.writeHead(e.statusCode,s),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,s),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))})},s=()=>e(),r=()=>e(),i=o=>e(o),n=o=>e(o);this.shutdownHandlers=[s,r,i,n],process.on("SIGINT",s),process.on("SIGTERM",r),process.on("uncaughtException",i),process.on("unhandledRejection",n)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[t,e,s,r]=this.shutdownHandlers;process.removeListener("SIGINT",t),process.removeListener("SIGTERM",e),process.removeListener("uncaughtException",s),process.removeListener("unhandledRejection",r),this.shutdownHandlers=[]}}};function P(t){if(!t.deflate&&!t.inflate)throw new Error("Dictionary must provide either deflate or inflate mapping");if(t.deflate&&t.inflate)throw new Error("Dictionary should provide only one of deflate or inflate (not both). The inverse will be auto-generated.");return t.deflate?{deflate:t.deflate,inflate:F(t.deflate)}:{deflate:F(t.inflate),inflate:t.inflate}}function F(t){let e={};for(let[s,r]of Object.entries(t))e[r]=s;return e}function S(t,e){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>S(r,e));let s={};for(let[r,i]of Object.entries(t)){let n=e[r]||r;s[n]=S(i,e)}return s}function C(t){if(!t||typeof t!="string")throw new Error("Table name must be a non-empty string");if(t.length>255)throw new Error("Table name must not exceed 255 characters");if(t.includes("/")||t.includes("\\"))throw new Error("Table name must not contain path separators");if(t.includes(".."))throw new Error('Table name must not contain ".."');if(t.startsWith("."))throw new Error('Table name must not start with "."');if(t.includes("\0"))throw new Error("Table name must not contain null bytes");if(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(t.toUpperCase()))throw new Error(`Table name "${t}" is reserved by the filesystem`)}function R(t){if(t==null)throw new Error("Key must be defined");if(typeof t!="string")throw new Error("Key must be a string");if(t.length===0)throw new Error("Key must not be empty");if(t.length>1024)throw new Error("Key must not exceed 1024 characters");if(t.includes("\0"))throw new Error("Key must not contain null bytes")}function U(t){if(t===void 0)throw new Error("Value must not be undefined (use null instead)");let e=typeof t;if(e==="function")throw new Error("Value must be JSON-serializable: functions are not supported");if(e==="symbol")throw new Error("Value must be JSON-serializable: symbols are not supported");try{if(JSON.stringify(t)===void 0)throw new Error("Value must be JSON-serializable: value cannot be serialized")}catch(s){throw new Error(`Value must be JSON-serializable: ${s instanceof Error?s.message:String(s)}`)}}import{existsSync as H,mkdirSync as Ct,readdirSync as xt,openSync as St,closeSync as Tt}from"fs";import{readFile as Et,writeFile as Pt,rename as Rt,unlink as G,open as jt}from"fs/promises";import{join as V,dirname as At}from"path";var N=class{data=new Map;databaseDirectory;dictionaries=new Map;useFsync;constructor(t){this.databaseDirectory=t.databaseDirectory,this.useFsync=t.durableWrites??!1,t.dictionaries&&Object.entries(t.dictionaries).forEach(([e,s])=>{let r=P(s);this.dictionaries.set(e,r)}),H(this.databaseDirectory)||Ct(this.databaseDirectory,{recursive:!0})}async start(){try{let t=xt(this.databaseDirectory);for(let e of t)!e.endsWith(".tmp")&&!e.startsWith(".")&&await this.loadTable(e)}catch(t){throw console.error("Failed to start database:",t),t}}async write(t,e,s,r,i){if(C(t),R(e),U(s),i&&!this.dictionaries.has(i))throw new Error(`Dictionary "${i}" not found. Available dictionaries: ${Array.from(this.dictionaries.keys()).join(", ")||"none"}`);try{this.data.has(t)||this.data.set(t,new Map);let n=this.data.get(t),a=(n.get(e)?.version||0)+1,c={value:s,version:a,timestamp:Date.now(),expiration:r||null,dictionaryName:i||void 0};return n.set(e,c),await this.persistTable(t),!0}catch(n){return console.error(`Write failed for ${t}:${e}:`,n),!1}}async get(t,e){C(t),e!==void 0&&R(e);try{this.data.has(t)||await this.loadTable(t);let s=this.data.get(t);if(!s)return e?void 0:[];if(e!==void 0){let n=s.get(e);if(!n)return;if(this.isExpired(n)){s.delete(e),await this.persistTable(t);return}return n.value}let r=[],i=[];for(let[n,o]of s.entries())this.isExpired(o)?i.push(n):r.push([n,o.value]);if(i.length>0){for(let n of i)s.delete(n);await this.persistTable(t)}return r}catch(s){return console.error(`Read failed for ${t}:${e}:`,s),e?void 0:[]}}async delete(t,e){C(t),R(e);try{this.data.has(t)||await this.loadTable(t);let s=this.data.get(t);if(!s||!s.has(e))return!1;let r=s.get(e);return r?this.isExpired(r)?(s.delete(e),await this.persistTable(t),!1):(s.delete(e),await this.persistTable(t),!0):!1}catch(s){return console.error(`Delete failed for ${t}:${e}:`,s),!1}}async getTableSize(t){C(t);try{this.data.has(t)||await this.loadTable(t);let e=this.data.get(t);if(!e)return 0;let s=0,r=[];for(let[i,n]of e.entries())this.isExpired(n)?r.push(i):s++;if(r.length>0){for(let i of r)e.delete(i);await this.persistTable(t)}return s}catch(e){return console.error(`Get table size failed for ${t}:`,e),0}}isExpired(t){return t.expiration===null?!1:Date.now()>t.expiration}async cleanupExpired(t){C(t);try{this.data.has(t)||await this.loadTable(t);let e=this.data.get(t);if(!e)return 0;let s=[];for(let[r,i]of e.entries())this.isExpired(i)&&s.push(r);for(let r of s)e.delete(r);return s.length>0&&await this.persistTable(t),s.length}catch(e){return console.error(`Cleanup failed for ${t}:`,e),0}}async cleanupAllExpired(){let t=0;for(let e of this.data.keys())t+=await this.cleanupExpired(e);return t}async deleteTable(t){C(t);try{this.data.delete(t);let e=V(this.databaseDirectory,t);return H(e)&&await G(e),!0}catch(e){return console.error(`Delete table failed for ${t}:`,e),!1}}listTables(){return Array.from(this.data.keys())}async flush(){try{let t=Array.from(this.data.keys()).map(e=>this.persistTable(e));await Promise.all(t)}catch(t){throw console.error("Flush failed:",t),t}}async close(){await this.flush()}addDictionary(t,e){let s=P(e);this.dictionaries.set(t,s)}removeDictionary(t){return this.dictionaries.delete(t)}listDictionaries(){return Array.from(this.dictionaries.keys())}async loadTable(t){let e=V(this.databaseDirectory,t);if(!H(e)){this.data.set(t,new Map);return}try{let s=await Et(e);if(s.length===0){this.data.set(t,new Map);return}let r=this.deserializeTable(s);this.data.set(t,r)}catch(s){console.error(`Failed to load table ${t}:`,s),this.data.set(t,new Map)}}async persistTable(t){let e=this.data.get(t);if(!e)return;let s=this.serializeTable(e),r=V(this.databaseDirectory,t),i=`${r}.tmp.${Date.now()}.${Math.random().toString(36).substring(7)}`;try{if(await Pt(i,s),this.useFsync){let n=await jt(i,"r+");try{await n.sync()}finally{await n.close()}}if(await Rt(i,r),this.useFsync){let n=At(r),o=St(n,"r");try{Tt(o)}catch{}}}catch(n){try{await G(i)}catch{}throw n}}serializeTable(t){let e=Array.from(t.entries()).map(([s,r])=>{let i=r.dictionaryName?this.dictionaries.get(r.dictionaryName):void 0,n={d:i?S(r.value,i.deflate):r.value,v:r.version,t:r.timestamp,x:r.expiration};return r.dictionaryName&&(n.n=r.dictionaryName),[s,n]});return Buffer.from(JSON.stringify(e),"utf8")}deserializeTable(t){let s=JSON.parse(t.toString("utf8")).map(([r,i])=>{let n=i.n,o=n?this.dictionaries.get(n):void 0;return[r,{value:o?S(i.d,o.inflate):i.d,version:i.v,timestamp:i.t,expiration:i.x,dictionaryName:n||void 0}]});return new Map(s)}};import{join as ft}from"node:path";import{statSync as Ft}from"node:fs";var m=class{isSilent;propertyPath="";constructor(t=!1){this.isSilent=t}test(t,e){if(!e)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(t.properties,e),i=this.compileErrors(s,r),n=this.isSuccessful(s,i);return{errors:i,success:n}}compileErrors(t,e){let s=t.filter(r=>r.success===!1);return[...e,...s].flatMap(r=>r)}isSuccessful(t,e){return t.every(s=>s.success===!0)&&e.length===0}validate(t,e,s=[],r=[]){let i=t?.additionalProperties??!0,n=t?.required||[];r=this.checkForRequiredKeysErrors(n,e,r),r=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),r,i);for(let o in t){let a=n.includes(o)&&o!=="required",c=t[o],l=e[o],f=c.additionalProperties??!0;a&&(r=this.checkForRequiredKeysErrors(c.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(o,l,c,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(c),r,f),this.handleNestedObject(l,c,s,r))}return{results:s,errors:r}}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,s){if(!this.areRequiredKeysPresent(t,e)){let r=e?Object.keys(e):[],i=this.findNonOverlappingElements(t,r),n=i.length>0?`Missing the required key: '${i.join(", ")}'!`:`Missing values for required keys: '${r.filter(o=>!e[o]).join(", ")}'!`;s.push({key:"",value:e,success:!1,error:n})}return s}checkForDisallowedProperties(t,e,s,r){if(!r){let i=this.findNonOverlappingElements(t,e);i.length>0&&s.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${i.join(", ")}'!`})}return s}handleValidation(t,e,s,r){this.updatePropertyPath(t);let i=this.validateProperty(this.propertyPath,s,e);r.push(...i);let n=(a,c)=>{a.forEach(l=>{let f=this.validateProperty(this.propertyPath,c.items,l);r.push(...f)}),this.updatePropertyPath()},o=a=>{let c=Object.keys(a),l=this.propertyPath;c.forEach(f=>{if(this.updatePropertyPath(f,l),this.isArray(a[f])&&s[f]?.items!=null)n(a[f],s[f]);else{let d=this.validateProperty(this.propertyPath,s[f],a[f]);r.push(...d)}})};this.isArray(e)&&s.items!=null?n(e,s):this.isObject(e)?o(e):this.updatePropertyPath()}handleNestedObject(t,e,s,r){if(this.isObject(t)){let i=this.getNestedObjects(t);for(let n of i){let o=e[n],a=t[n];o&&typeof a=="object"&&this.validate(o,a,s,r)}}}getNestedObjects(t){return Object.keys(t).filter(e=>{if(this.isObject(t))return e})}findNonOverlappingElements(t,e){return t.filter(s=>!e.includes(s))}areRequiredKeysPresent(t,e=[]){return t.every(s=>Object.keys(e).includes(s)?this.isDefined(e[s]):!1)}validateProperty(t,e,s){return this.validateInput(e,s).map(i=>{let{success:n,error:o}=i;return{key:t,value:s,success:n,error:o??""}})}validateInput(t,e){if(t){let s=[{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"}],r=[];for(let i of s)i.condition()&&!i.validator()&&r.push({success:!1,error:i.error});return r}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(s=>{switch(s){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 s in t){let r=t[s];e.properties.required.push(s),Array.isArray(r)?e.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?e.properties[s]=this.generateNestedObjectSchema(r):e.properties[s]=this.generatePropertySchema(r)}return e}generateArraySchema(t){let e={type:"array"},s=t.filter(r=>r);if(s.length>0){let r=s[0];s.every(n=>typeof n==typeof r)?typeof r=="object"&&!Array.isArray(r)?e.items=this.generateNestedObjectSchema(r):e.items=this.generatePropertySchema(r):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 s in t){let r=t[s];e.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?e[s]=this.generateNestedObjectSchema(r):e[s]=this.generatePropertySchema(r)}return e}generatePropertySchema(t){let e=typeof t,s={type:e};return e==="string"&&(s.minLength=1),s}};async function j(t){return t.body||{}}function h(t,e="An error occurred"){let s=t?.message||t||e,r=t?.cause?.statusCode||t?.statusCode||400;return{message:s,status:r}}function W(t,e,s={}){let r=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 i=t.roles.flatMap(o=>o?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(o=>i.includes(o)||i.includes("*")?!0:i.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 J(t,e,s,r,i){let n=t.find(c=>c.service===e);if(!n){let c=new Error(`Function bindings do not include access to service: ${e}`);throw c.cause={statusCode:403},c}if(!n.permissions||n.permissions.length===0)return;for(let c of n.permissions)if(!(c.resource&&c.resource!==s)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(r)){if(c.targets&&c.targets.length>0){if(!i)return;if(!c.targets.includes(i))continue}return}}let o=i?`:${i}`:"",a=new Error(`Function bindings do not allow: ${e}.${s}.${r}${o}`);throw a.cause={statusCode:403},a}async function p(t,e,s,r,i,n,o){if(!e)return null;let a=t.state.user;if(!a){let l=t.headers.authorization;if(!l){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let f=l.replace(/^Bearer\s+/i,"");if(a=await e.getUserFromToken(f),!a){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}W(a,s,{});let c=t.headers["x-function-bindings"];if(c)try{let l=Array.isArray(c)?c[0]:c,f=JSON.parse(l);J(f,r,i,n,o)}catch(l){if(l.cause?.statusCode===403)throw l;let f=new Error("Invalid function bindings header");throw f.cause={statusCode:400},f}return a}var _={properties:{tableName:{type:"string",minLength:1},key:{type:"string"}},required:["tableName"],additionalProperties:!1};var $t=new m(!0);async function K(t,e,s){try{let r=await j(t),i=$t.test(_,r);if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);let{tableName:n,key:o}=r;if(!n)return t.json("tableName is required",400);await p(t,s,"databases.table.get","databases","table","read",n);let a=await e.get(n,o);return a===void 0?t.json(null,404):t.json(a,200)}catch(r){let{message:i,status:n}=h(r,"Error getting table data");return t.json({error:i},n)}}var X={properties:{tableName:{type:"string",minLength:1},key:{type:"string"},value:{},expiration:{type:"number"},dictionaryName:{type:"string"}},required:["tableName"],additionalProperties:!1};var Ot=new m(!0);async function Z(t,e,s){try{let r=await j(t),i=Ot.test(X,r);if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);let{tableName:n,key:o,value:a,expiration:c,dictionaryName:l}=r;if(!n||a===void 0)return t.json("tableName and value are required",400);await p(t,s,"databases.table.update","databases","table","write",n);let f=await e.write(n,o,a,c,l);return t.json(f,200)}catch(r){let{message:i,status:n}=h(r,"Error writing table data");return t.json({error:i},n)}}var Y={properties:{tableName:{type:"string",minLength:1},key:{type:"string",minLength:1}},required:["tableName","key"],additionalProperties:!1};var Lt=new m(!0);async function Q(t,e,s){try{let r=Lt.test(Y,t.query);if(!r.success)return t.json({error:"Invalid input",details:r.errors},400);let{tableName:i,key:n}=t.query;if(!i||!n)return t.json("tableName and key are required",400);await p(t,s,"databases.table.delete","databases","table","delete",i);let o=await e.delete(i,n);return t.json(o,200)}catch(r){let{message:i,status:n}=h(r,"Error deleting table item");return t.json({error:i},n)}}async function tt(t,e,s,r,i,n,o){try{await p(t,s,"databases.table.get","databases","table","read");let a=e.listTables(),c=t.query.context;if(c&&r){let f=t.headers.authorization?.replace(/^Bearer\s+/i,""),d=await r.listResourcesByType(c,"database",f);a=a.filter(u=>d.includes(u))}let l=await Promise.all(a.map(async f=>{let d=await e.getTableSize(f),u=n(i,f);return{name:f,items:d,size:o(u)}}));return t.json({tables:l},200)}catch(a){let{message:c,status:l}=h(a,"Error listing tables");return t.json({error:c},l)}}var v={properties:{tableName:{type:"string",minLength:1},context:{type:"string",minLength:1}},required:["tableName"],additionalProperties:!1};var Vt=new m(!0);async function et(t,e,s){try{let r=t.params.tableName;if(!r)return t.json({error:"tableName is required"},400);let i=Vt.test(v,{tableName:r});return i.success?(await p(t,s,"databases.table.create","databases","table","create",r),e.listTables().includes(r)?t.json({error:"Table already exists"},409):(await e.write(r,"__init__",null),await e.delete(r,"__init__"),t.json({success:!0,name:r,message:"Table created successfully"},201))):t.json({error:"Invalid input",details:i.errors},400)}catch(r){let{message:i,status:n}=h(r,"Error creating table");return t.json({error:i},n)}}var Nt=new m(!0);async function rt(t,e,s){try{let r=t.params.tableName;if(!r)return t.json({error:"tableName is required"},400);let i=Nt.test(v,{tableName:r});if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);if(await p(t,s,"databases.table.delete","databases","table","delete",r),!e.listTables().includes(r))return t.json({error:"Table not found"},404);let o=await e.deleteTable(r);return t.json({success:o,name:r,message:"Table deleted successfully"},200)}catch(r){let{message:i,status:n}=h(r,"Error deleting table");return t.json({error:i},n)}}var Dt=new m(!0);async function st(t,e,s,r,i,n){try{let o=t.params.tableName;if(!o)return t.json({error:"tableName is required"},400);let a=Dt.test(v,{tableName:o});if(!a.success)return t.json({error:"Invalid input",details:a.errors},400);if(await p(t,s,"databases.table.get","databases","table","read",o),!e.listTables().includes(o))return t.json({error:"Table not found"},404);let l=await e.getTableSize(o),f=i(r,o);return t.json({name:o,items:l,size:n(f)},200)}catch(o){let{message:a,status:c}=h(o,"Error getting table info");return t.json({error:a},c)}}async function it(t,e,s){try{if(!t.query.tableName)return t.json({error:"tableName is required"},400);let{tableName:r}=t.query;await p(t,s,"databases.table.get","databases","table","read",r);let i=await e.get(r),n=i?i.length:0;return t.json(n,200)}catch(r){let{message:i,status:n}=h(r,"Error getting table size");return t.json({error:i},n)}}var qt=new m(!0);async function ot(t,e,s){try{let r=t.params.tableName;if(!r)return t.json({error:"tableName is required"},400);let i=qt.test(v,{tableName:r});if(!i.success)return t.json({error:"Invalid input",details:i.errors},400);if(await p(t,s,"databases.table.get","databases","table","read",r),!e.listTables().includes(r))return t.json({error:"Table not found"},404);let o=await e.get(r),a=o?Object.entries(o).map(([c,l])=>Array.isArray(l)&&l.length===2?{key:l[0],value:l[1]}:{key:c,value:l}):[];return t.json({items:a},200)}catch(r){let{message:i,status:n}=h(r,"Error getting table items");return t.json({error:i},n)}}import{readFileSync as zt,existsSync as Bt}from"node:fs";function T(){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||!Bt(t))return e;try{let s=zt(t,"utf-8");return JSON.parse(s)}catch(s){return console.error("[loadRuntimeConfig] Failed to load runtime config:",s),e}}function nt(t,e){let s={enabled:!1,requestsPerMinute:0};if(!e)return s;let r=e.services?.[t];return r||(e.global?e.global:s)}function at(t,e){let s=t?.api?.port;if(!s)throw new Error('Missing "port" input when create API service!');let r=T(),i=t?.dataPath||r.molnos.dataPath,n=t?.api?.host||r.server.host,o=t?.identityApiUrl!==void 0?t.identityApiUrl:r.identity.apiUrl,a=t?.contextApiUrl!==void 0?t.contextApiUrl:r.context.apiUrl,c=t?.debug||!1,l;return e&&(l=nt(e,r.molnos.rateLimit)),{dataPath:i,api:{port:s,host:n},...o?{identityApiUrl:o}:{},...a?{contextApiUrl:a}:{},...l?{rateLimit:l}:{},debug:c}}var A=class{baseUrl;authToken;constructor(e,s){this.baseUrl=e.replace(/\/$/,""),this.authToken=s}async createCustomRole(e,s,r,i){let n=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:e,name:s,description:r,permissions:i})});if(!n.ok){let o=`Failed to create role: ${n.statusText}`;try{o=(await n.json()).error||o}catch{o=await n.text().catch(()=>n.statusText)||o}throw new Error(o)}}async updateRole(e,s){let r=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(s)});if(!r.ok){let i=await r.json();throw new Error(i.error||`Failed to update role: ${r.statusText}`)}}async deleteRole(e){let s=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete role: ${s.statusText}`)}}async addServiceAccount(e,s,r){let i=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:e,description:s,roles:r})});if(!i.ok){let o=`Failed to create service account: ${i.statusText}`;try{o=(await i.json()).error||o}catch{o=await i.text().catch(()=>i.statusText)||o}throw new Error(o)}let n=await i.json();return{id:n.id,apiKey:n.apiKey}}async deleteIdentity(e){let s=await fetch(`${this.baseUrl}/identity/service-accounts/${e}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete service account: ${s.statusText}`)}}async getUserFromToken(e){try{let s=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${e}`}});return s.ok?await s.json():null}catch{return null}}getHeaders(){let e={"Content-Type":"application/json"};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}};function lt(t){return t?new A(t):null}var M=class{baseUrl;constructor(e){this.baseUrl=e.replace(/\/$/,"")}async listResourcesByType(e,s,r){let i=`${this.baseUrl}/contexts/${encodeURIComponent(e)}`;try{let n={"Content-Type":"application/json"};r&&(n.Authorization=`Bearer ${r}`);let o=await fetch(i,{method:"GET",headers:n});if(!o.ok)return[];let c=(await o.json()).context?.resources||{};switch(s){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 ct(t){return t?new M(t):null}function dt(t){if(t===0)return"0 B";let e=["B","KB","MB","GB"],s=Math.floor(Math.log(t)/Math.log(1024));return`${(t/1024**s).toFixed(1)} ${e[s]}`}function ut(t,e){try{let s=ft(t,e);return Ft(s).size}catch{return 0}}async function Ut(t){let e=t.dataPath||"data",s=ft(e,"databases"),r=new N({databaseDirectory:s});await r.start();let i=lt(t.identityApiUrl),n=ct(t.contextApiUrl),o=T(),a=new L({port:t.api.port||o.services.databases.port,host:t.api.host||o.services.databases.host,rateLimit:t.rateLimit||o.molnos.rateLimit.global});return a.get("/table",async l=>it(l,r,i)),a.post("/get",async l=>K(l,r,i)),a.post("/write",async l=>Z(l,r,i)),a.delete("/delete",async l=>Q(l,r,i)),a.get("/tables",async l=>tt(l,r,i,n,s,ut,dt)),a.post("/tables/:tableName",async l=>et(l,r,i)),a.delete("/tables/:tableName",async l=>rt(l,r,i)),a.get("/tables/:tableName",async l=>st(l,r,i,s,ut,dt)),a.get("/tables/:tableName/items",async l=>ot(l,r,i)),a.start()}if(import.meta.url===`file://${process.argv[1]}`){let t=T(),s=process.argv.slice(2).find(n=>n.startsWith("--port=")),r=s?parseInt(s.split("=")[1],10):t.services.databases.port,i=at({api:{port:r}},"databases");Ut(i)}export{Ut as startServer};
|
|
10
|
+
`),s=e.indexOf(t);if(s===-1)return null;let r=e.subarray(0,s),i=e.subarray(s+4),n=r.toString("utf8").split(`\r
|
|
11
|
+
`),a="",c="",l,f;for(let d of n){let y=d.toLowerCase();if(y.startsWith("content-disposition:")){a=d.substring(20).trim();let w=a.match(/name="([^"]+)"/);w&&(c=w[1]);let b=a.match(/filename="([^"]+)"/);b&&(l=b[1])}else y.startsWith("content-type:")&&(f=d.substring(13).trim())}if(!c)return null;let u=i;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:l,contentType:f,data:u}}import{readFileSync as x}from"fs";import k from"http";import we from"http2";import ve from"https";var L=class{config;rateLimiter;router;shutdownHandlers=[];constructor(e){let t=new I(z(e||{})).get();t.debug&&console.log("Using configuration:",t),this.config=t,this.router=new q;let s=t.rateLimit.requestsPerMinute||E().rateLimit.requestsPerMinute;this.rateLimiter=new D(s,60),t.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(e){return this.router.use(e),this}get(e,...t){return this.router.get(e,...t),this}post(e,...t){return this.router.post(e,...t),this}put(e,...t){return this.router.put(e,...t),this}delete(e,...t){return this.router.delete(e,...t),this}patch(e,...t){return this.router.patch(e,...t),this}any(e,...t){return this.router.any(e,...t),this}options(e,...t){return this.router.options(e,...t),this}start(){let e=this.createServer(),{port:t,host:s}=this.config;return this.setupGracefulShutdown(e),e.listen(t,s,()=>{let r=e.address(),i=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${i}://${r.address!=="::"?r.address:"localhost"}:${r.port}`)}),e}createServer(){let e=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let t={key:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return we.createSecureServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}else if(this.config.useHttps){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttps is true");try{let t={key:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return ve.createServer(t,e)}catch(t){throw t.message.includes("key values mismatch")?new Error(`SSL certificate and key do not match: ${t.message}`):t}}return k.createServer(e)}async rateLimitMiddleware(e,t){let s=e.req.socket.remoteAddress||"unknown";return e.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),e.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(s).toString()),e.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(s).toString()),this.rateLimiter.isAllowed(s)?t():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(e,t){let s=Date.now(),r=e.method||"UNKNOWN",i=e.url||"/unknown",o=this.config.debug;try{if(this.setCorsHeaders(t,e),this.setSecurityHeaders(t,this.config.useHttps),o&&console.log(`${r} ${i}`),e.method==="OPTIONS"){if(t instanceof k.ServerResponse)t.statusCode=204,t.end();else{let a=t;a.writeHead(204),a.end()}return}try{e.body=await this.parseBody(e)}catch(a){return o&&console.error("Body parsing error:",a.message),this.respond(t,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let n=await this.router.handle(e,t);return n?n._handled?void 0:this.respond(t,n):this.respond(t,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(n){return console.error("Server error:",n),this.respond(t,{statusCode:500,body:{error:"Internal Server Error",message:o?n.message:"An unexpected error occurred"}})}finally{o&&this.logDuration(s,r,i)}}logDuration(e,t,s){let r=Date.now()-e;console.log(`${t} ${s} completed in ${r}ms`)}async parseBody(e){return new Promise((t,s)=>{let r=[],i=0,o=this.config.maxBodySize,n=!1,a=null,c=this.config.debug,l=e.headers["content-type"]||"";c&&console.log("Content-Type:",l),this.config.requestTimeout>0&&(a=setTimeout(()=>{n||(n=!0,c&&console.log("Request timeout exceeded"),s(new Error("Request timeout")))},this.config.requestTimeout));let f=()=>{a&&(clearTimeout(a),a=null)};e.on("data",u=>{if(!n){if(i+=u.length,c&&console.log(`Received chunk: ${u.length} bytes, total size: ${i}`),i>o){n=!0,f(),c&&console.log(`Body size exceeded limit: ${i} > ${o}`),s(new Error("Request body too large"));return}r.push(u)}}),e.on("end",()=>{if(!n){n=!0,f(),c&&console.log(`Request body complete: ${i} bytes`);try{if(r.length>0){let u=Buffer.concat(r);if(l.includes("application/json"))try{let d=u.toString("utf8");t(JSON.parse(d))}catch(d){s(new Error(`Invalid JSON in request body: ${d.message}`))}else if(l.includes("application/x-www-form-urlencoded")){let d=u.toString("utf8"),y={};new URLSearchParams(d).forEach((w,b)=>{y[b]=w}),t(y)}else if(l.includes("multipart/form-data"))try{let d=B(u,l);t(d)}catch(d){s(new Error(`Invalid multipart form data: ${d.message}`))}else this.isBinaryContentType(l)?t(u):t(u.toString("utf8"))}else t({})}catch(u){s(new Error(`Invalid request body: ${u}`))}}}),e.on("error",u=>{n||(n=!0,f(),s(new Error(`Error reading request body: ${u.message}`)))}),e.on("close",()=>{f()})})}isBinaryContentType(e){return["application/octet-stream","application/pdf","application/zip","application/gzip","application/x-tar","application/x-rar-compressed","application/x-7z-compressed","image/","video/","audio/","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument","application/msword","application/vnd.ms-powerpoint"].some(s=>e.includes(s))}setCorsHeaders(e,t){let s=t.headers.origin,{allowedDomains:r=["*"]}=this.config;!s||r.length===0||r.includes("*")?e.setHeader("Access-Control-Allow-Origin","*"):r.includes(s)&&(e.setHeader("Access-Control-Allow-Origin",s),e.setHeader("Vary","Origin")),e.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(e,t=!1){let s={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((t||this.config.useHttp2)&&(s["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),e instanceof k.ServerResponse)Object.entries(s).forEach(([r,i])=>{e.setHeader(r,i)});else{let r=e;Object.entries(s).forEach(([i,o])=>{r.setHeader(i,o)})}}respond(e,t){let s={...t.headers||{}};(i=>typeof i.writeHead=="function"&&typeof i.end=="function")(e)?(e.writeHead(t.statusCode,s),t.body===null||t.body===void 0?e.end():t.isRaw||typeof t.body=="string"?e.end(t.body):e.end(JSON.stringify(t.body))):(console.warn("Unexpected response object type without writeHead/end methods"),e.writeHead?.(t.statusCode,s),t.body===null||t.body===void 0?e.end?.():t.isRaw||typeof t.body=="string"?e.end?.(t.body):e.end?.(JSON.stringify(t.body)))}setupGracefulShutdown(e){let t=n=>{console.log("Shutting down MikroServe server..."),n&&console.error("Error:",n),this.cleanupShutdownHandlers(),e.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(n?1:0))})},s=()=>t(),r=()=>t(),i=n=>t(n),o=n=>t(n);this.shutdownHandlers=[s,r,i,o],process.on("SIGINT",s),process.on("SIGTERM",r),process.on("uncaughtException",i),process.on("unhandledRejection",o)}cleanupShutdownHandlers(){if(this.shutdownHandlers.length>0){let[e,t,s,r]=this.shutdownHandlers;process.removeListener("SIGINT",e),process.removeListener("SIGTERM",t),process.removeListener("uncaughtException",s),process.removeListener("unhandledRejection",r),this.shutdownHandlers=[]}}};function P(e){if(!e.deflate&&!e.inflate)throw new Error("Dictionary must provide either deflate or inflate mapping");if(e.deflate&&e.inflate)throw new Error("Dictionary should provide only one of deflate or inflate (not both). The inverse will be auto-generated.");return e.deflate?{deflate:e.deflate,inflate:F(e.deflate)}:{deflate:F(e.inflate),inflate:e.inflate}}function F(e){let t={};for(let[s,r]of Object.entries(e))t[r]=s;return t}function T(e,t){if(e==null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>T(r,t));let s={};for(let[r,i]of Object.entries(e)){let o=t[r]||r;s[o]=T(i,t)}return s}function C(e){if(!e||typeof e!="string")throw new Error("Table name must be a non-empty string");if(e.length>255)throw new Error("Table name must not exceed 255 characters");if(e.includes("/")||e.includes("\\"))throw new Error("Table name must not contain path separators");if(e.includes(".."))throw new Error('Table name must not contain ".."');if(e.startsWith("."))throw new Error('Table name must not start with "."');if(e.includes("\0"))throw new Error("Table name must not contain null bytes");if(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"].includes(e.toUpperCase()))throw new Error(`Table name "${e}" is reserved by the filesystem`)}function R(e){if(e==null)throw new Error("Key must be defined");if(typeof e!="string")throw new Error("Key must be a string");if(e.length===0)throw new Error("Key must not be empty");if(e.length>1024)throw new Error("Key must not exceed 1024 characters");if(e.includes("\0"))throw new Error("Key must not contain null bytes")}function U(e){if(e===void 0)throw new Error("Value must not be undefined (use null instead)");let t=typeof e;if(t==="function")throw new Error("Value must be JSON-serializable: functions are not supported");if(t==="symbol")throw new Error("Value must be JSON-serializable: symbols are not supported");try{if(JSON.stringify(e)===void 0)throw new Error("Value must be JSON-serializable: value cannot be serialized")}catch(s){throw new Error(`Value must be JSON-serializable: ${s instanceof Error?s.message:String(s)}`)}}import{existsSync as H,mkdirSync as Ce,readdirSync as Se,openSync as xe,closeSync as Te}from"fs";import{readFile as Ee,writeFile as Pe,rename as Re,unlink as G,open as je}from"fs/promises";import{join as V,dirname as Ae}from"path";var N=class{data=new Map;databaseDirectory;dictionaries=new Map;useFsync;constructor(e){this.databaseDirectory=e.databaseDirectory,this.useFsync=e.durableWrites??!1,e.dictionaries&&Object.entries(e.dictionaries).forEach(([t,s])=>{let r=P(s);this.dictionaries.set(t,r)}),H(this.databaseDirectory)||Ce(this.databaseDirectory,{recursive:!0})}async start(){try{let e=Se(this.databaseDirectory);for(let t of e)!t.endsWith(".tmp")&&!t.startsWith(".")&&await this.loadTable(t)}catch(e){throw console.error("Failed to start database:",e),e}}async write(e,t,s,r,i){if(C(e),R(t),U(s),i&&!this.dictionaries.has(i))throw new Error(`Dictionary "${i}" not found. Available dictionaries: ${Array.from(this.dictionaries.keys()).join(", ")||"none"}`);try{this.data.has(e)||this.data.set(e,new Map);let o=this.data.get(e),a=(o.get(t)?.version||0)+1,c={value:s,version:a,timestamp:Date.now(),expiration:r||null,dictionaryName:i||void 0};return o.set(t,c),await this.persistTable(e),!0}catch(o){return console.error(`Write failed for ${e}:${t}:`,o),!1}}async get(e,t){C(e),t!==void 0&&R(t);try{this.data.has(e)||await this.loadTable(e);let s=this.data.get(e);if(!s)return t?void 0:[];if(t!==void 0){let o=s.get(t);if(!o)return;if(this.isExpired(o)){s.delete(t),await this.persistTable(e);return}return o.value}let r=[],i=[];for(let[o,n]of s.entries())this.isExpired(n)?i.push(o):r.push([o,n.value]);if(i.length>0){for(let o of i)s.delete(o);await this.persistTable(e)}return r}catch(s){return console.error(`Read failed for ${e}:${t}:`,s),t?void 0:[]}}async delete(e,t){C(e),R(t);try{this.data.has(e)||await this.loadTable(e);let s=this.data.get(e);if(!s||!s.has(t))return!1;let r=s.get(t);return r?this.isExpired(r)?(s.delete(t),await this.persistTable(e),!1):(s.delete(t),await this.persistTable(e),!0):!1}catch(s){return console.error(`Delete failed for ${e}:${t}:`,s),!1}}async getTableSize(e){C(e);try{this.data.has(e)||await this.loadTable(e);let t=this.data.get(e);if(!t)return 0;let s=0,r=[];for(let[i,o]of t.entries())this.isExpired(o)?r.push(i):s++;if(r.length>0){for(let i of r)t.delete(i);await this.persistTable(e)}return s}catch(t){return console.error(`Get table size failed for ${e}:`,t),0}}isExpired(e){return e.expiration===null?!1:Date.now()>e.expiration}async cleanupExpired(e){C(e);try{this.data.has(e)||await this.loadTable(e);let t=this.data.get(e);if(!t)return 0;let s=[];for(let[r,i]of t.entries())this.isExpired(i)&&s.push(r);for(let r of s)t.delete(r);return s.length>0&&await this.persistTable(e),s.length}catch(t){return console.error(`Cleanup failed for ${e}:`,t),0}}async cleanupAllExpired(){let e=0;for(let t of this.data.keys())e+=await this.cleanupExpired(t);return e}async deleteTable(e){C(e);try{this.data.delete(e);let t=V(this.databaseDirectory,e);return H(t)&&await G(t),!0}catch(t){return console.error(`Delete table failed for ${e}:`,t),!1}}listTables(){return Array.from(this.data.keys())}async flush(){try{let e=Array.from(this.data.keys()).map(t=>this.persistTable(t));await Promise.all(e)}catch(e){throw console.error("Flush failed:",e),e}}async close(){await this.flush()}addDictionary(e,t){let s=P(t);this.dictionaries.set(e,s)}removeDictionary(e){return this.dictionaries.delete(e)}listDictionaries(){return Array.from(this.dictionaries.keys())}async loadTable(e){let t=V(this.databaseDirectory,e);if(!H(t)){this.data.set(e,new Map);return}try{let s=await Ee(t);if(s.length===0){this.data.set(e,new Map);return}let r=this.deserializeTable(s);this.data.set(e,r)}catch(s){console.error(`Failed to load table ${e}:`,s),this.data.set(e,new Map)}}async persistTable(e){let t=this.data.get(e);if(!t)return;let s=this.serializeTable(t),r=V(this.databaseDirectory,e),i=`${r}.tmp.${Date.now()}.${Math.random().toString(36).substring(7)}`;try{if(await Pe(i,s),this.useFsync){let o=await je(i,"r+");try{await o.sync()}finally{await o.close()}}if(await Re(i,r),this.useFsync){let o=Ae(r),n=xe(o,"r");try{Te(n)}catch{}}}catch(o){try{await G(i)}catch{}throw o}}serializeTable(e){let t=Array.from(e.entries()).map(([s,r])=>{let i=r.dictionaryName?this.dictionaries.get(r.dictionaryName):void 0,o={d:i?T(r.value,i.deflate):r.value,v:r.version,t:r.timestamp,x:r.expiration};return r.dictionaryName&&(o.n=r.dictionaryName),[s,o]});return Buffer.from(JSON.stringify(t),"utf8")}deserializeTable(e){let s=JSON.parse(e.toString("utf8")).map(([r,i])=>{let o=i.n,n=o?this.dictionaries.get(o):void 0;return[r,{value:n?T(i.d,n.inflate):i.d,version:i.v,timestamp:i.t,expiration:i.x,dictionaryName:o||void 0}]});return new Map(s)}};import{join as fe}from"node:path";import{statSync as Fe}from"node:fs";var m=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(e.properties,t),i=this.compileErrors(s,r),o=this.isSuccessful(s,i);return{errors:i,success:o}}compileErrors(e,t){let s=e.filter(r=>r.success===!1);return[...t,...s].flatMap(r=>r)}isSuccessful(e,t){return e.every(s=>s.success===!0)&&t.length===0}validate(e,t,s=[],r=[]){let i=e?.additionalProperties??!0,o=e?.required||[];r=this.checkForRequiredKeysErrors(o,t,r),r=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),r,i);for(let n in e){let a=o.includes(n)&&n!=="required",c=e[n],l=t[n],f=c.additionalProperties??!0;a&&(r=this.checkForRequiredKeysErrors(c.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(n,l,c,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(c),r,f),this.handleNestedObject(l,c,s,r))}return{results:s,errors:r}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,s){if(!this.areRequiredKeysPresent(e,t)){let r=t?Object.keys(t):[],i=this.findNonOverlappingElements(e,r),o=i.length>0?`Missing the required key: '${i.join(", ")}'!`:`Missing values for required keys: '${r.filter(n=>!t[n]).join(", ")}'!`;s.push({key:"",value:t,success:!1,error:o})}return s}checkForDisallowedProperties(e,t,s,r){if(!r){let i=this.findNonOverlappingElements(e,t);i.length>0&&s.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${i.join(", ")}'!`})}return s}handleValidation(e,t,s,r){this.updatePropertyPath(e);let i=this.validateProperty(this.propertyPath,s,t);r.push(...i);let o=(a,c)=>{a.forEach(l=>{let f=this.validateProperty(this.propertyPath,c.items,l);r.push(...f)}),this.updatePropertyPath()},n=a=>{let c=Object.keys(a),l=this.propertyPath;c.forEach(f=>{if(this.updatePropertyPath(f,l),this.isArray(a[f])&&s[f]?.items!=null)o(a[f],s[f]);else{let u=this.validateProperty(this.propertyPath,s[f],a[f]);r.push(...u)}})};this.isArray(t)&&s.items!=null?o(t,s):this.isObject(t)?n(t):this.updatePropertyPath()}handleNestedObject(e,t,s,r){if(this.isObject(e)){let i=this.getNestedObjects(e);for(let o of i){let n=t[o],a=e[o];n&&typeof a=="object"&&this.validate(n,a,s,r)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(s=>!t.includes(s))}areRequiredKeysPresent(e,t=[]){return e.every(s=>Object.keys(t).includes(s)?this.isDefined(t[s]):!1)}validateProperty(e,t,s){return this.validateInput(t,s).map(i=>{let{success:o,error:n}=i;return{key:e,value:s,success:o,error:n??""}})}validateInput(e,t){if(e){let s=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],r=[];for(let i of s)i.condition()&&!i.validator()&&r.push({success:!1,error:i.error});return r}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(s=>{switch(s){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let s in e){let r=e[s];t.properties.required.push(s),Array.isArray(r)?t.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?t.properties[s]=this.generateNestedObjectSchema(r):t.properties[s]=this.generatePropertySchema(r)}return t}generateArraySchema(e){let t={type:"array"},s=e.filter(r=>r);if(s.length>0){let r=s[0];s.every(o=>typeof o==typeof r)?typeof r=="object"&&!Array.isArray(r)?t.items=this.generateNestedObjectSchema(r):t.items=this.generatePropertySchema(r):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let s in e){let r=e[s];t.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?t[s]=this.generateNestedObjectSchema(r):t[s]=this.generatePropertySchema(r)}return t}generatePropertySchema(e){let t=typeof e,s={type:t};return t==="string"&&(s.minLength=1),s}};async function j(e){return e.body||{}}function h(e,t="An error occurred"){let s=e?.message||e||t,r=e?.cause?.statusCode||e?.statusCode||400;return{message:s,status:r}}function W(e,t,s={}){let r=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let n=new Error("Unauthorized: User or roles missing");throw n.cause={statusCode:403},n}let i=e.roles.flatMap(n=>n?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(n=>i.includes(n)||i.includes("*")?!0:i.some(a=>{if(a.endsWith(".*")){let c=a.slice(0,-2);return n.startsWith(`${c}.`)}return!1}))){let n=new Error("Unauthorized");throw n.cause={statusCode:403},n}return!0}function J(e,t,s,r,i){let o=e.find(c=>c.service===t);if(!o){let c=new Error(`Function bindings do not include access to service: ${t}`);throw c.cause={statusCode:403},c}if(!o.permissions||o.permissions.length===0)return;for(let c of o.permissions)if(!(c.resource&&c.resource!==s)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(r)){if(c.targets&&c.targets.length>0){if(!i)return;if(!c.targets.includes(i))continue}return}}let n=i?`:${i}`:"",a=new Error(`Function bindings do not allow: ${t}.${s}.${r}${n}`);throw a.cause={statusCode:403},a}import{readFileSync as Me,existsSync as $e}from"node:fs";function S(){let e=process.env.MOLNOS_RUNTIME_CONFIG,t={molnos:{dataPath:"data",rateLimit:{global:{enabled:!1,requestsPerMinute:0}},signedUrlSecret:"molnos-default-signed-url-secret"},server:{host:"127.0.0.1",port:3e3},identity:{apiUrl:"http://127.0.0.1:3000"},context:{apiUrl:"http://127.0.0.1:3000"},services:{storage:{host:"127.0.0.1",port:3001,url:"http://127.0.0.1:3001"},functions:{host:"127.0.0.1",port:3002,url:"http://127.0.0.1:3002"},sites:{host:"127.0.0.1",port:3003,url:"http://127.0.0.1:3003"},databases:{host:"127.0.0.1",port:3004,url:"http://127.0.0.1:3004"},observability:{host:"127.0.0.1",port:3005,url:"http://127.0.0.1:3005"}}};if(!e||!$e(e))return t;try{let s=Me(e,"utf-8");return JSON.parse(s)}catch(s){return console.error("[loadRuntimeConfig] Failed to load runtime config:",s),t}}async function p(e,t,s,r,i,o,n){if(!t)return null;let a=e.headers["x-molnos-service-token"];if(a){let f=S();if(f.internalServiceSecret&&a===f.internalServiceSecret)return null}let c=e.state.user;if(!c){let f=e.headers.authorization;if(!f){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let u=f.replace(/^Bearer\s+/i,"");if(c=await t.getUserFromToken(u),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}W(c,s,{});let l=e.headers["x-function-bindings"];if(l)try{let f=Array.isArray(l)?l[0]:l,u=JSON.parse(f);J(u,r,i,o,n)}catch(f){if(f.cause?.statusCode===403)throw f;let u=new Error("Invalid function bindings header");throw u.cause={statusCode:400},u}return c}var _={properties:{tableName:{type:"string",minLength:1},key:{type:"string"}},required:["tableName"],additionalProperties:!1};var Oe=new m(!0);async function K(e,t,s){try{let r=await j(e),i=Oe.test(_,r);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);let{tableName:o,key:n}=r;if(!o)return e.json("tableName is required",400);await p(e,s,"databases.table.get","databases","table","read",o);let a=await t.get(o,n);return a===void 0?e.json(null,404):e.json(a,200)}catch(r){let{message:i,status:o}=h(r,"Error getting table data");return e.json({error:i},o)}}var X={properties:{tableName:{type:"string",minLength:1},key:{type:"string"},value:{},expiration:{type:"number"},dictionaryName:{type:"string"}},required:["tableName"],additionalProperties:!1};var Le=new m(!0);async function Z(e,t,s){try{let r=await j(e),i=Le.test(X,r);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);let{tableName:o,key:n,value:a,expiration:c,dictionaryName:l}=r;if(!o||a===void 0)return e.json("tableName and value are required",400);await p(e,s,"databases.table.update","databases","table","write",o);let f=await t.write(o,n,a,c,l);return e.json(f,200)}catch(r){let{message:i,status:o}=h(r,"Error writing table data");return e.json({error:i},o)}}var Y={properties:{tableName:{type:"string",minLength:1},key:{type:"string",minLength:1}},required:["tableName","key"],additionalProperties:!1};var Ve=new m(!0);async function Q(e,t,s){try{let r=Ve.test(Y,e.query);if(!r.success)return e.json({error:"Invalid input",details:r.errors},400);let{tableName:i,key:o}=e.query;if(!i||!o)return e.json("tableName and key are required",400);await p(e,s,"databases.table.delete","databases","table","delete",i);let n=await t.delete(i,o);return e.json(n,200)}catch(r){let{message:i,status:o}=h(r,"Error deleting table item");return e.json({error:i},o)}}async function ee(e,t,s,r,i,o,n){try{await p(e,s,"databases.table.get","databases","table","read");let a=t.listTables(),c=e.query.context;if(c&&r){let f=e.headers.authorization?.replace(/^Bearer\s+/i,""),u=await r.listResourcesByType(c,"database",f);a=a.filter(d=>u.includes(d))}let l=await Promise.all(a.map(async f=>{let u=await t.getTableSize(f),d=o(i,f);return{name:f,items:u,size:n(d)}}));return e.json({tables:l},200)}catch(a){let{message:c,status:l}=h(a,"Error listing tables");return e.json({error:c},l)}}var v={properties:{tableName:{type:"string",minLength:1},context:{type:"string",minLength:1}},required:["tableName"],additionalProperties:!1};var De=new m(!0);async function te(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=De.test(v,{tableName:r});return i.success?(await p(e,s,"databases.table.create","databases","table","create",r),t.listTables().includes(r)?e.json({error:"Table already exists"},409):(await t.write(r,"__init__",null),await t.delete(r,"__init__"),e.json({success:!0,name:r,message:"Table created successfully"},201))):e.json({error:"Invalid input",details:i.errors},400)}catch(r){let{message:i,status:o}=h(r,"Error creating table");return e.json({error:i},o)}}var qe=new m(!0);async function re(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=qe.test(v,{tableName:r});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await p(e,s,"databases.table.delete","databases","table","delete",r),!t.listTables().includes(r))return e.json({error:"Table not found"},404);let n=await t.deleteTable(r);return e.json({success:n,name:r,message:"Table deleted successfully"},200)}catch(r){let{message:i,status:o}=h(r,"Error deleting table");return e.json({error:i},o)}}var ze=new m(!0);async function se(e,t,s,r,i,o){try{let n=e.params.tableName;if(!n)return e.json({error:"tableName is required"},400);let a=ze.test(v,{tableName:n});if(!a.success)return e.json({error:"Invalid input",details:a.errors},400);if(await p(e,s,"databases.table.get","databases","table","read",n),!t.listTables().includes(n))return e.json({error:"Table not found"},404);let l=await t.getTableSize(n),f=i(r,n);return e.json({name:n,items:l,size:o(f)},200)}catch(n){let{message:a,status:c}=h(n,"Error getting table info");return e.json({error:a},c)}}async function ie(e,t,s){try{if(!e.query.tableName)return e.json({error:"tableName is required"},400);let{tableName:r}=e.query;await p(e,s,"databases.table.get","databases","table","read",r);let i=await t.get(r),o=i?i.length:0;return e.json(o,200)}catch(r){let{message:i,status:o}=h(r,"Error getting table size");return e.json({error:i},o)}}var Be=new m(!0);async function ne(e,t,s){try{let r=e.params.tableName;if(!r)return e.json({error:"tableName is required"},400);let i=Be.test(v,{tableName:r});if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);if(await p(e,s,"databases.table.get","databases","table","read",r),!t.listTables().includes(r))return e.json({error:"Table not found"},404);let n=await t.get(r),a=n?Object.entries(n).map(([c,l])=>Array.isArray(l)&&l.length===2?{key:l[0],value:l[1]}:{key:c,value:l}):[];return e.json({items:a},200)}catch(r){let{message:i,status:o}=h(r,"Error getting table items");return e.json({error:i},o)}}function oe(e,t){let s={enabled:!1,requestsPerMinute:0};if(!t)return s;let r=t.services?.[e];return r||(t.global?t.global:s)}function ae(e,t){let s=e?.api?.port;if(!s)throw new Error('Missing "port" input when create API service!');let r=S(),i=e?.dataPath||r.molnos.dataPath,o=e?.api?.host||r.server.host,n=e?.identityApiUrl!==void 0?e.identityApiUrl:r.identity.apiUrl,a=e?.contextApiUrl!==void 0?e.contextApiUrl:r.context.apiUrl,c=e?.debug||!1,l;return t&&(l=oe(t,r.molnos.rateLimit)),{dataPath:i,api:{port:s,host:o},...n?{identityApiUrl:n}:{},...a?{contextApiUrl:a}:{},...l?{rateLimit:l}:{},debug:c}}var A=class{baseUrl;authToken;constructor(t,s){this.baseUrl=t.replace(/\/$/,""),this.authToken=s}async createCustomRole(t,s,r,i){let o=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:t,name:s,description:r,permissions:i})});if(!o.ok){let n=`Failed to create role: ${o.statusText}`;try{n=(await o.json()).error||n}catch{n=await o.text().catch(()=>o.statusText)||n}throw new Error(n)}}async updateRole(t,s){let r=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(s)});if(!r.ok){let i=await r.json();throw new Error(i.error||`Failed to update role: ${r.statusText}`)}}async deleteRole(t){let s=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete role: ${s.statusText}`)}}async addServiceAccount(t,s,r){let i=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:t,description:s,roles:r})});if(!i.ok){let n=`Failed to create service account: ${i.statusText}`;try{n=(await i.json()).error||n}catch{n=await i.text().catch(()=>i.statusText)||n}throw new Error(n)}let o=await i.json();return{id:o.id,apiKey:o.apiKey}}async deleteIdentity(t){let s=await fetch(`${this.baseUrl}/identity/service-accounts/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!s.ok){let r=await s.json();throw new Error(r.error||`Failed to delete service account: ${s.statusText}`)}}async getUserFromToken(t){try{let s=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return s.ok?await s.json():null}catch{return null}}getHeaders(){let t={"Content-Type":"application/json"};return this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),t}};function le(e){return e?new A(e):null}var M=class{baseUrl;constructor(t){this.baseUrl=t.replace(/\/$/,"")}async listResourcesByType(t,s,r){let i=`${this.baseUrl}/contexts/${encodeURIComponent(t)}`;try{let o={"Content-Type":"application/json"};r&&(o.Authorization=`Bearer ${r}`);let n=await fetch(i,{method:"GET",headers:o});if(!n.ok)return[];let c=(await n.json()).context?.resources||{};switch(s){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 ce(e){return e?new M(e):null}function ue(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**s).toFixed(1)} ${t[s]}`}function de(e,t){try{let s=fe(e,t);return Fe(s).size}catch{return 0}}async function Ue(e){let t=e.dataPath||"data",s=fe(t,"databases"),r=new N({databaseDirectory:s});await r.start();let i=le(e.identityApiUrl),o=ce(e.contextApiUrl),n=S(),a=new L({port:e.api.port||n.services.databases.port,host:e.api.host||n.services.databases.host,rateLimit:e.rateLimit||n.molnos.rateLimit.global});return a.get("/table",async l=>ie(l,r,i)),a.post("/get",async l=>K(l,r,i)),a.post("/write",async l=>Z(l,r,i)),a.delete("/delete",async l=>Q(l,r,i)),a.get("/tables",async l=>ee(l,r,i,o,s,de,ue)),a.post("/tables/:tableName",async l=>te(l,r,i)),a.delete("/tables/:tableName",async l=>re(l,r,i)),a.get("/tables/:tableName",async l=>se(l,r,i,s,de,ue)),a.get("/tables/:tableName/items",async l=>ne(l,r,i)),a.start()}if(import.meta.url===`file://${process.argv[1]}`){let e=S(),s=process.argv.slice(2).find(o=>o.startsWith("--port=")),r=s?parseInt(s.split("=")[1],10):e.services.databases.port,i=ae({api:{port:r}},"databases");Ue(i)}export{Ue as startServer};
|