molnos 1.0.3 → 1.1.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,16 +1,25 @@
1
1
  // MolnOS Core - See LICENSE file for copyright and license details.
2
- import{createHash as yr}from"node:crypto";import{existsSync as ce}from"node:fs";var ue=(t,e,s)=>(r,n)=>{let o=-1;return i(0);async function i(c){if(c<=o)throw new Error("next() called multiple times");o=c;let a,u=!1,l;if(t[c]?(l=t[c][0][0],r.req.routeIndex=c):l=c===t.length&&n||void 0,l)try{a=await l(r,()=>i(c+1))}catch(d){if(d instanceof Error&&e)r.error=d,a=await e(d,r),u=!0;else throw d}else r.finalized===!1&&s&&(a=await s(r));return a&&(r.finalized===!1||u)&&(r.res=a),r}};var He=Symbol();var Ie=async(t,e=Object.create(null))=>{let{all:s=!1,dot:r=!1}=e,o=(t instanceof z?t.raw.headers:t.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?Ot(t,{all:s,dot:r}):{}};async function Ot(t,e){let s=await t.formData();return s?Tt(s,e):{}}function Tt(t,e){let s=Object.create(null);return t.forEach((r,n)=>{e.all||n.endsWith("[]")?Ft(s,n,r):s[n]=r}),e.dot&&Object.entries(s).forEach(([r,n])=>{r.includes(".")&&($t(s,r,n),delete s[r])}),s}var Ft=(t,e,s)=>{t[e]!==void 0?Array.isArray(t[e])?t[e].push(s):t[e]=[t[e],s]:e.endsWith("[]")?t[e]=[s]:t[e]=s},$t=(t,e,s)=>{let r=t,n=e.split(".");n.forEach((o,i)=>{i===n.length-1?r[o]=s:((!r[o]||typeof r[o]!="object"||Array.isArray(r[o])||r[o]instanceof File)&&(r[o]=Object.create(null)),r=r[o])})};var de=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},De=t=>{let{groups:e,path:s}=Ht(t),r=de(s);return It(r,e)},Ht=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(s,r)=>{let n=`@${r}`;return e.push([n,s]),n}),{groups:e,path:t}},It=(t,e)=>{for(let s=e.length-1;s>=0;s--){let[r]=e[s];for(let n=t.length-1;n>=0;n--)if(t[n].includes(r)){t[n]=t[n].replace(r,e[s][1]);break}}return t},G={},ke=(t,e)=>{if(t==="*")return"*";let s=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(s){let r=`${t}#${e}`;return G[r]||(s[2]?G[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,s[1],new RegExp(`^${s[2]}(?=/${e})`)]:[t,s[1],new RegExp(`^${s[2]}$`)]:G[r]=[t,s[1],!0]),G[r]}return null},V=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,s=>{try{return e(s)}catch{return s}})}},Dt=t=>V(t,decodeURI),he=t=>{let e=t.url,s=e.indexOf("/",e.indexOf(":")+4),r=s;for(;r<e.length;r++){let n=e.charCodeAt(r);if(n===37){let o=e.indexOf("?",r),i=e.slice(s,o===-1?void 0:o);return Dt(i.includes("%25")?i.replace(/%25/g,"%2525"):i)}else if(n===63)break}return e.slice(s,r)};var Me=t=>{let e=he(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},S=(t,e,...s)=>(s.length&&(e=S(e,...s)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),W=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),s=[],r="";return e.forEach(n=>{if(n!==""&&!/\:/.test(n))r+="/"+n;else if(/\:/.test(n))if(/\?/.test(n)){s.length===0&&r===""?s.push("/"):s.push(r);let o=n.replace("?","");r+="/"+o,s.push(r)}else r+="/"+n}),s.filter((n,o,i)=>i.indexOf(n)===o)},le=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?V(t,fe):t):t,Ue=(t,e,s)=>{let r;if(!s&&e&&!/[%+]/.test(e)){let i=t.indexOf("?",8);if(i===-1)return;for(t.startsWith(e,i+1)||(i=t.indexOf(`&${e}`,i+1));i!==-1;){let c=t.charCodeAt(i+e.length+1);if(c===61){let a=i+e.length+2,u=t.indexOf("&",a);return le(t.slice(a,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";i=t.indexOf(`&${e}`,i+1)}if(r=/[%+]/.test(t),!r)return}let n={};r??=/[%+]/.test(t);let o=t.indexOf("?",8);for(;o!==-1;){let i=t.indexOf("&",o+1),c=t.indexOf("=",o);c>i&&i!==-1&&(c=-1);let a=t.slice(o+1,c===-1?i===-1?void 0:i:c);if(r&&(a=le(a)),o=i,a==="")continue;let u;c===-1?u="":(u=t.slice(c+1,i===-1?void 0:i),r&&(u=le(u))),s?(n[a]&&Array.isArray(n[a])||(n[a]=[]),n[a].push(u)):n[a]??=u}return e?n[e]:n},qe=Ue,Le=(t,e)=>Ue(t,e,!0),fe=decodeURIComponent;var Ne=t=>V(t,fe),z=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(t,e="/",s=[[]]){this.raw=t,this.path=e,this.#e=s,this.#t={}}param(t){return t?this.#r(t):this.#o()}#r(t){let e=this.#e[0][this.routeIndex][1][t],s=this.#n(e);return s&&/\%/.test(s)?Ne(s):s}#o(){let t={},e=Object.keys(this.#e[0][this.routeIndex][1]);for(let s of e){let r=this.#n(this.#e[0][this.routeIndex][1][s]);r!==void 0&&(t[s]=/\%/.test(r)?Ne(r):r)}return t}#n(t){return this.#e[1]?this.#e[1][t]:t}query(t){return qe(this.url,t)}queries(t){return Le(this.url,t)}header(t){if(t)return this.raw.headers.get(t)??void 0;let e={};return this.raw.headers.forEach((s,r)=>{e[r]=s}),e}async parseBody(t){return this.bodyCache.parsedBody??=await Ie(this,t)}#s=t=>{let{bodyCache:e,raw:s}=this,r=e[t];if(r)return r;let n=Object.keys(e)[0];return n?e[n].then(o=>(n==="json"&&(o=JSON.stringify(o)),new Response(o)[t]())):e[t]=s[t]()};json(){return this.#s("text").then(t=>JSON.parse(t))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(t,e){this.#t[t]=e}valid(t){return this.#t[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[He](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,t]])=>t)}get routePath(){return this.#e[0].map(([[,t]])=>t)[this.routeIndex].path}};var Be={Stringify:1,BeforeStream:2,Stream:3},kt=(t,e)=>{let s=new String(t);return s.isEscaped=!0,s.callbacks=e,s};var pe=async(t,e,s,r,n)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let o=t.callbacks;if(!o?.length)return Promise.resolve(t);n?n[0]+=t:n=[t];let i=Promise.all(o.map(c=>c({phase:e,buffer:n,context:r}))).then(c=>Promise.all(c.filter(Boolean).map(a=>pe(a,e,!1,r,n))).then(()=>n[0]));return s?kt(await i,o):i};var Mt="text/plain; charset=UTF-8",me=(t,e)=>({"Content-Type":t,...e}),_e=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#s;#l;#c;#u;#a;#d;#h;constructor(t,e){this.#t=t,e&&(this.#n=e.executionCtx,this.env=e.env,this.#u=e.notFoundHandler,this.#h=e.path,this.#d=e.matchResult)}get req(){return this.#e??=new z(this.#t,this.#h,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=new Response(null,{headers:this.#a??=new Headers})}set res(t){if(this.#s&&t){t=new Response(t.body,t);for(let[e,s]of this.#s.headers.entries())if(e!=="content-type")if(e==="set-cookie"){let r=this.#s.headers.getSetCookie();t.headers.delete("set-cookie");for(let n of r)t.headers.append("set-cookie",n)}else t.headers.set(e,s)}this.#s=t,this.finalized=!0}render=(...t)=>(this.#c??=e=>this.html(e),this.#c(...t));setLayout=t=>this.#l=t;getLayout=()=>this.#l;setRenderer=t=>{this.#c=t};header=(t,e,s)=>{this.finalized&&(this.#s=new Response(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;e===void 0?r.delete(t):s?.append?r.append(t,e):r.set(t,e)};status=t=>{this.#o=t};set=(t,e)=>{this.#r??=new Map,this.#r.set(t,e)};get=t=>this.#r?this.#r.get(t):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(t,e,s){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof e=="object"&&"headers"in e){let o=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[i,c]of o)i.toLowerCase()==="set-cookie"?r.append(i,c):r.set(i,c)}if(s)for(let[o,i]of Object.entries(s))if(typeof i=="string")r.set(o,i);else{r.delete(o);for(let c of i)r.append(o,c)}let n=typeof e=="number"?e:e?.status??this.#o;return new Response(t,{status:n,headers:r})}newResponse=(...t)=>this.#i(...t);body=(t,e,s)=>this.#i(t,e,s);text=(t,e,s)=>!this.#a&&!this.#o&&!e&&!s&&!this.finalized?new Response(t):this.#i(t,e,me(Mt,s));json=(t,e,s)=>this.#i(JSON.stringify(t),e,me("application/json",s));html=(t,e,s)=>{let r=n=>this.#i(n,e,me("text/html; charset=UTF-8",s));return typeof t=="object"?pe(t,Be.Stringify,!1,{}).then(r):r(t)};redirect=(t,e)=>{let s=String(t);return this.header("Location",/[^\x00-\xFF]/.test(s)?encodeURI(s):s),this.newResponse(null,e??302)};notFound=()=>(this.#u??=()=>new Response,this.#u(this))};var g="ALL",ze="all",Ge=["get","post","put","delete","options","patch"],J="Can not add a route since the matcher is already built.",K=class extends Error{};var Ve="__COMPOSED_HANDLER";var Ut=t=>t.text("404 Not Found",404),We=(t,e)=>{if("getResponse"in t){let s=t.getResponse();return e.newResponse(s.body,s)}return console.error(t),e.text("Internal Server Error",500)},Je=class Ke{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(e={}){[...Ge,ze].forEach(o=>{this[o]=(i,...c)=>(typeof i=="string"?this.#t=i:this.#o(o,this.#t,i),c.forEach(a=>{this.#o(o,this.#t,a)}),this)}),this.on=(o,i,...c)=>{for(let a of[i].flat()){this.#t=a;for(let u of[o].flat())c.map(l=>{this.#o(u.toUpperCase(),this.#t,l)})}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(c=>{this.#o(g,this.#t,c)}),this);let{strict:r,...n}=e;Object.assign(this,n),this.getPath=r??!0?e.getPath??he:Me}#e(){let e=new Ke({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Ut;errorHandler=We;route(e,s){let r=this.basePath(e);return s.routes.map(n=>{let o;s.errorHandler===We?o=n.handler:(o=async(i,c)=>(await ue([],s.errorHandler)(i,()=>n.handler(i,c))).res,o[Ve]=n.handler),r.#o(n.method,n.path,o)}),this}basePath(e){let s=this.#e();return s._basePath=S(this._basePath,e),s}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,s,r){let n,o;r&&(typeof r=="function"?o=r:(o=r.optionHandler,r.replaceRequest===!1?n=a=>a:n=r.replaceRequest));let i=o?a=>{let u=o(a);return Array.isArray(u)?u:[u]}:a=>{let u;try{u=a.executionCtx}catch{}return[a.env,u]};n||=(()=>{let a=S(this._basePath,e),u=a==="/"?0:a.length;return l=>{let d=new URL(l.url);return d.pathname=d.pathname.slice(u)||"/",new Request(d,l)}})();let c=async(a,u)=>{let l=await s(n(a.req.raw),...i(a));if(l)return l;await u()};return this.#o(g,S(e,"*"),c),this}#o(e,s,r){e=e.toUpperCase(),s=S(this._basePath,s);let n={basePath:this._basePath,path:s,method:e,handler:r};this.router.add(e,s,[r,n]),this.routes.push(n)}#n(e,s){if(e instanceof Error)return this.errorHandler(e,s);throw e}#s(e,s,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#s(e,s,r,"GET")))();let o=this.getPath(e,{env:r}),i=this.router.match(n,o),c=new _e(e,{path:o,matchResult:i,env:r,executionCtx:s,notFoundHandler:this.#r});if(i[0].length===1){let u;try{u=i[0][0][0][0](c,async()=>{c.res=await this.#r(c)})}catch(l){return this.#n(l,c)}return u instanceof Promise?u.then(l=>l||(c.finalized?c.res:this.#r(c))).catch(l=>this.#n(l,c)):u??this.#r(c)}let a=ue(i[0],this.errorHandler,this.#r);return(async()=>{try{let u=await a(c);if(!u.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return u.res}catch(u){return this.#n(u,c)}})()}fetch=(e,...s)=>this.#s(e,s[1],s[0],e.method);request=(e,s,r,n)=>e instanceof Request?this.fetch(s?new Request(e,s):e,r,n):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${S("/",e)}`,s),r,n));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method))})}};var Q=[];function ge(t,e){let s=this.buildAllMatchers(),r=((n,o)=>{let i=s[n]||s[g],c=i[2][o];if(c)return c;let a=o.match(i[0]);if(!a)return[[],Q];let u=a.indexOf("",1);return[i[1][u],a]});return this.match=r,r(t,e)}var Y="[^/]+",k=".*",M="(?:|/.*)",j=Symbol(),qt=new Set(".\\+*[^]$()");function Lt(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===k||t===M?1:e===k||e===M?-1:t===Y?1:e===Y?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Qe=class ye{#t;#e;#r=Object.create(null);insert(e,s,r,n,o){if(e.length===0){if(this.#t!==void 0)throw j;if(o)return;this.#t=s;return}let[i,...c]=e,a=i==="*"?c.length===0?["","",k]:["","",Y]:i==="/*"?["","",M]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),u;if(a){let l=a[1],d=a[2]||Y;if(l&&a[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw j;if(u=this.#r[d],!u){if(Object.keys(this.#r).some(h=>h!==k&&h!==M))throw j;if(o)return;u=this.#r[d]=new ye,l!==""&&(u.#e=n.varIndex++)}!o&&l!==""&&r.push([l,u.#e])}else if(u=this.#r[i],!u){if(Object.keys(this.#r).some(l=>l.length>1&&l!==k&&l!==M))throw j;if(o)return;u=this.#r[i]=new ye}u.insert(c,s,r,n,o)}buildRegExpStr(){let s=Object.keys(this.#r).sort(Lt).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:qt.has(r)?`\\${r}`:r)+n.buildRegExpStr()});return typeof this.#t=="number"&&s.unshift(`#${this.#t}`),s.length===0?"":s.length===1?s[0]:"(?:"+s.join("|")+")"}};var Ye=class{#t={varIndex:0};#e=new Qe;insert(t,e,s){let r=[],n=[];for(let i=0;;){let c=!1;if(t=t.replace(/\{[^}]+\}/g,a=>{let u=`@\\${i}`;return n[i]=[u,a],i++,c=!0,u}),!c)break}let o=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[c]=n[i];for(let a=o.length-1;a>=0;a--)if(o[a].indexOf(c)!==-1){o[a]=o[a].replace(c,n[i][1]);break}}return this.#e.insert(o,e,r,this.#t,s),r}buildRegExp(){let t=this.#e.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,s=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,i)=>o!==void 0?(s[++e]=Number(o),"$()"):(i!==void 0&&(r[Number(i)]=++e),"")),[new RegExp(`^${t}`),s,r]}};var Nt=[/^$/,[],Object.create(null)],Xe=Object.create(null);function Ze(t){return Xe[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,s)=>s?`\\${s}`:"(?:|/.*)")}$`)}function Bt(){Xe=Object.create(null)}function _t(t){let e=new Ye,s=[];if(t.length===0)return Nt;let r=t.map(u=>[!/\*|\/:/.test(u[0]),...u]).sort(([u,l],[d,h])=>u?1:d?-1:l.length-h.length),n=Object.create(null);for(let u=0,l=-1,d=r.length;u<d;u++){let[h,f,b]=r[u];h?n[f]=[b.map(([y])=>[y,Object.create(null)]),Q]:l++;let p;try{p=e.insert(f,l,h)}catch(y){throw y===j?new K(f):y}h||(s[l]=b.map(([y,m])=>{let O=Object.create(null);for(m-=1;m>=0;m--){let[T,v]=p[m];O[T]=v}return[y,O]}))}let[o,i,c]=e.buildRegExp();for(let u=0,l=s.length;u<l;u++)for(let d=0,h=s[u].length;d<h;d++){let f=s[u][d]?.[1];if(!f)continue;let b=Object.keys(f);for(let p=0,y=b.length;p<y;p++)f[b[p]]=c[f[b[p]]]}let a=[];for(let u in i)a[u]=s[i[u]];return[o,a,n]}function F(t,e){if(t){for(let s of Object.keys(t).sort((r,n)=>n.length-r.length))if(Ze(s).test(e))return[...t[s]]}}var X=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[g]:Object.create(null)},this.#e={[g]:Object.create(null)}}add(t,e,s){let r=this.#t,n=this.#e;if(!r||!n)throw new Error(J);r[t]||[r,n].forEach(c=>{c[t]=Object.create(null),Object.keys(c[g]).forEach(a=>{c[t][a]=[...c[g][a]]})}),e==="/*"&&(e="*");let o=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let c=Ze(e);t===g?Object.keys(r).forEach(a=>{r[a][e]||=F(r[a],e)||F(r[g],e)||[]}):r[t][e]||=F(r[t],e)||F(r[g],e)||[],Object.keys(r).forEach(a=>{(t===g||t===a)&&Object.keys(r[a]).forEach(u=>{c.test(u)&&r[a][u].push([s,o])})}),Object.keys(n).forEach(a=>{(t===g||t===a)&&Object.keys(n[a]).forEach(u=>c.test(u)&&n[a][u].push([s,o]))});return}let i=W(e)||[e];for(let c=0,a=i.length;c<a;c++){let u=i[c];Object.keys(n).forEach(l=>{(t===g||t===l)&&(n[l][u]||=[...F(r[l],u)||F(r[g],u)||[]],n[l][u].push([s,o-a+c+1]))})}}match=ge;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(e=>{t[e]||=this.#r(e)}),this.#t=this.#e=void 0,Bt(),t}#r(t){let e=[],s=t===g;return[this.#t,this.#e].forEach(r=>{let n=r[t]?Object.keys(r[t]).map(o=>[o,r[t][o]]):[];n.length!==0?(s||=!0,e.push(...n)):t!==g&&e.push(...Object.keys(r[g]).map(o=>[o,r[g][o]]))}),s?_t(e):null}};var be=class{name="SmartRouter";#t=[];#e=[];constructor(t){this.#t=t.routers}add(t,e,s){if(!this.#e)throw new Error(J);this.#e.push([t,e,s])}match(t,e){if(!this.#e)throw new Error("Fatal error");let s=this.#t,r=this.#e,n=s.length,o=0,i;for(;o<n;o++){let c=s[o];try{for(let a=0,u=r.length;a<u;a++)c.add(...r[a]);i=c.match(t,e)}catch(a){if(a instanceof K)continue;throw a}this.match=c.match.bind(c),this.#t=[c],this.#e=void 0;break}if(o===n)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var U=Object.create(null),et=class tt{#t;#e;#r;#o=0;#n=U;constructor(e,s,r){if(this.#e=r||Object.create(null),this.#t=[],e&&s){let n=Object.create(null);n[e]={handler:s,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(e,s,r){this.#o=++this.#o;let n=this,o=De(s),i=[];for(let c=0,a=o.length;c<a;c++){let u=o[c],l=o[c+1],d=ke(u,l),h=Array.isArray(d)?d[0]:u;if(h in n.#e){n=n.#e[h],d&&i.push(d[1]);continue}n.#e[h]=new tt,d&&(n.#r.push(d),i.push(d[1])),n=n.#e[h]}return n.#t.push({[e]:{handler:r,possibleKeys:i.filter((c,a,u)=>u.indexOf(c)===a),score:this.#o}}),n}#s(e,s,r,n){let o=[];for(let i=0,c=e.#t.length;i<c;i++){let a=e.#t[i],u=a[s]||a[g],l={};if(u!==void 0&&(u.params=Object.create(null),o.push(u),r!==U||n&&n!==U))for(let d=0,h=u.possibleKeys.length;d<h;d++){let f=u.possibleKeys[d],b=l[u.score];u.params[f]=n?.[f]&&!b?n[f]:r[f]??n?.[f],l[u.score]=!0}}return o}search(e,s){let r=[];this.#n=U;let o=[this],i=de(s),c=[];for(let a=0,u=i.length;a<u;a++){let l=i[a],d=a===u-1,h=[];for(let f=0,b=o.length;f<b;f++){let p=o[f],y=p.#e[l];y&&(y.#n=p.#n,d?(y.#e["*"]&&r.push(...this.#s(y.#e["*"],e,p.#n)),r.push(...this.#s(y,e,p.#n))):h.push(y));for(let m=0,O=p.#r.length;m<O;m++){let T=p.#r[m],v=p.#n===U?{}:{...p.#n};if(T==="*"){let P=p.#e["*"];P&&(r.push(...this.#s(P,e,p.#n)),P.#n=v,h.push(P));continue}let[jt,$e,D]=T;if(!l&&!(D instanceof RegExp))continue;let R=p.#e[jt],At=i.slice(a).join("/");if(D instanceof RegExp){let P=D.exec(At);if(P){if(v[$e]=P[0],r.push(...this.#s(R,e,p.#n,v)),Object.keys(R.#e).length){R.#n=v;let Ct=P[0].match(/\//)?.length??0;(c[Ct]||=[]).push(R)}continue}}(D===!0||D.test(l))&&(v[$e]=l,d?(r.push(...this.#s(R,e,v,p.#n)),R.#e["*"]&&r.push(...this.#s(R.#e["*"],e,v,p.#n))):(R.#n=v,h.push(R)))}}o=h.concat(c.shift()??[])}return r.length>1&&r.sort((a,u)=>a.score-u.score),[r.map(({handler:a,params:u})=>[a,u])]}};var we=class{name="TrieRouter";#t;constructor(){this.#t=new et}add(t,e,s){let r=W(e);if(r){for(let n=0,o=r.length;n<o;n++)this.#t.insert(t,r[n],s);return}this.#t.insert(t,e,s)}match(t,e){return this.#t.search(t,e)}};var ve=class extends Je{constructor(t={}){super(t),this.router=t.router??new be({routers:[new X,new we]})}};import{join as _}from"node:path";import{mkdir as br,writeFile as Te,readFile as St,unlink as wr}from"node:fs/promises";import{pathToFileURL as vr}from"node:url";import{createServer as zt}from"http";import{Http2ServerRequest as Gt}from"http2";import{Http2ServerRequest as Ee}from"http2";import{Readable as rt}from"stream";import sr from"crypto";var A=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Vt=t=>t instanceof A?t:new A(t.message,{cause:t}),Wt=global.Request,q=class extends Wt{constructor(t,e){typeof t=="object"&&I in t&&(t=t[I]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Jt=t=>{let e=[],s=t.rawHeaders;for(let r=0;r<s.length;r+=2){let{[r]:n,[r+1]:o}=s;n.charCodeAt(0)!==58&&e.push([n,o])}return new Headers(e)},nt=Symbol("wrapBodyStream"),Kt=(t,e,s,r,n)=>{let o={method:t,headers:s,signal:n.signal};if(t==="TRACE"){o.method="GET";let i=new q(e,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(r.rawBody),i.close()}});else if(r[nt]){let i;o.body=new ReadableStream({async pull(c){try{i||=rt.toWeb(r).getReader();let{done:a,value:u}=await i.read();a?c.close():c.enqueue(u)}catch(a){c.error(a)}}})}else o.body=rt.toWeb(r);return new q(e,o)},I=Symbol("getRequestCache"),Qt=Symbol("requestCache"),Z=Symbol("incomingKey"),ee=Symbol("urlKey"),Yt=Symbol("headersKey"),H=Symbol("abortControllerKey"),Xt=Symbol("getAbortController"),te={get method(){return this[Z].method||"GET"},get url(){return this[ee]},get headers(){return this[Yt]||=Jt(this[Z])},[Xt](){return this[I](),this[H]},[I](){return this[H]||=new AbortController,this[Qt]||=Kt(this.method,this[ee],this.headers,this[Z],this[H])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(te,t,{get(){return this[I]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(te,t,{value:function(){return this[I]()[t]()}})});Object.setPrototypeOf(te,q.prototype);var Zt=(t,e)=>{let s=Object.create(te);s[Z]=t;let r=t.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(t instanceof Ee)throw new A("Absolute URL for :path is not allowed in HTTP/2");try{let c=new URL(r);s[ee]=c.href}catch(c){throw new A("Invalid absolute URL",{cause:c})}return s}let n=(t instanceof Ee?t.authority:t.headers.host)||e;if(!n)throw new A("Missing host header");let o;if(t instanceof Ee){if(o=t.scheme,!(o==="http"||o==="https"))throw new A("Unsupported scheme")}else o=t.socket&&t.socket.encrypted?"https":"http";let i=new URL(`${o}://${n}${r}`);if(i.hostname.length!==n.length&&i.hostname!==n.replace(/:\d+$/,""))throw new A("Invalid host header");return s[ee]=i.href,s},st=Symbol("responseCache"),$=Symbol("getResponseCache"),C=Symbol("cache"),Re=global.Response,L=class ot{#t;#e;[$](){return delete this[C],this[st]||=new Re(this.#t,this.#e)}constructor(e,s){let r;if(this.#t=e,s instanceof ot){let n=s[st];if(n){this.#e=n,this[$]();return}else this.#e=s.#e,r=new Headers(s.#e.headers)}else this.#e=s;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(r||=s?.headers||{"content-type":"text/plain; charset=UTF-8"},this[C]=[s?.status||200,e,r])}get headers(){let e=this[C];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[$]().headers}get status(){return this[C]?.[0]??this[$]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(L.prototype,t,{get(){return this[$]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(L.prototype,t,{value:function(){return this[$]()[t]()}})});Object.setPrototypeOf(L,Re);Object.setPrototypeOf(L.prototype,Re.prototype);async function er(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function it(t,e,s){let r=c=>{t.cancel(c).catch(()=>{})};return e.on("close",r),e.on("error",r),(s??t.read()).then(i,n),t.closed.finally(()=>{e.off("close",r),e.off("error",r)});function n(c){c&&e.destroy(c)}function o(){t.read().then(i,n)}function i({done:c,value:a}){try{if(c)e.end();else if(!e.write(a))e.once("drain",o);else return t.read().then(i,n)}catch(u){n(u)}}}function tr(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:it(t.getReader(),e)}var at=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let s=[];for(let[r,n]of t)r==="set-cookie"?s.push(n):e[r]=n;return s.length>0&&(e["set-cookie"]=s),e["content-type"]??="text/plain; charset=UTF-8",e},rr="x-hono-already-sent",nr=global.fetch;typeof global.crypto>"u"&&(global.crypto=sr);global.fetch=(t,e)=>(e={compress:!1,...e},nr(t,e));var Pe=Symbol("outgoingEnded"),or=()=>new Response(null,{status:400}),ct=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),xe=(t,e)=>{let s=t instanceof Error?t:new Error("unknown error",{cause:t});s.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${s.message}`),e.destroy(s))},ut=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},lt=async(t,e)=>{let[s,r,n]=t[C];n instanceof Headers&&(n=at(n)),typeof r=="string"?n["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?n["Content-Length"]=r.byteLength:r instanceof Blob&&(n["Content-Length"]=r.size),e.writeHead(s,n),typeof r=="string"||r instanceof Uint8Array?e.end(r):r instanceof Blob?e.end(new Uint8Array(await r.arrayBuffer())):(ut(e),await tr(r,e)?.catch(o=>xe(o,e))),e[Pe]?.()},ir=t=>typeof t.then=="function",ar=async(t,e,s={})=>{if(ir(t))if(s.errorHandler)try{t=await t}catch(n){let o=await s.errorHandler(n);if(!o)return;t=o}else t=await t.catch(ct);if(C in t)return lt(t,e);let r=at(t.headers);if(t.body){let n=t.body.getReader(),o=[],i=!1,c;if(r["transfer-encoding"]!=="chunked"){let a=2;for(let u=0;u<a;u++){c||=n.read();let l=await er(c).catch(d=>{console.error(d),i=!0});if(!l){if(u===1){await new Promise(d=>setTimeout(d)),a=3;continue}break}if(c=void 0,l.value&&o.push(l.value),l.done){i=!0;break}}i&&!("content-length"in r)&&(r["content-length"]=o.reduce((u,l)=>u+l.length,0))}e.writeHead(t.status,r),o.forEach(a=>{e.write(a)}),i?e.end():(o.length===0&&ut(e),await it(n,e,c))}else r[rr]||(e.writeHead(t.status,r),e.end());e[Pe]?.()},cr=(t,e={})=>{let s=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==q&&(Object.defineProperty(global,"Request",{value:q}),Object.defineProperty(global,"Response",{value:L})),async(r,n)=>{let o,i;try{i=Zt(r,e.hostname);let c=!s||r.method==="GET"||r.method==="HEAD";if(c||(r[nt]=!0,r.on("end",()=>{c=!0}),r instanceof Gt&&(n[Pe]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{r.destroy(),n.destroy()})})})),n.on("close",()=>{i[H]&&(r.errored?i[H].abort(r.errored.toString()):n.writableFinished||i[H].abort("Client connection prematurely closed.")),c||setTimeout(()=>{c||setTimeout(()=>{r.destroy()})})}),o=t(i,{incoming:r,outgoing:n}),C in o)return lt(o,n)}catch(c){if(o)return xe(c,n);if(e.errorHandler){if(o=await e.errorHandler(i?c:Vt(c)),!o)return}else i?o=ct(c):o=or()}try{return await ar(o,n,e)}catch(c){return xe(c,n)}}},ur=t=>{let e=t.fetch,s=cr(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||zt)(t.serverOptions||{},s)},dt=(t,e)=>{let s=ur(t);return s.listen(t?.port??3e3,t.hostname,()=>{let r=s.address();e&&e(r)}),s};import{readFileSync as lr,existsSync as dr}from"node:fs";function ht(){let t=process.env.MOLNOS_RUNTIME_CONFIG;if(!t||!dr(t))return{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}};try{let e=lr(t,"utf-8");return JSON.parse(e)}catch(e){return console.error("[loadRuntimeConfig] Failed to load runtime config:",e),{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}}}}var w=class extends Error{constructor(e){super(),this.name="ValidationError",this.message=e||"Invalid input",this.cause={statusCode:400}}};var re=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};var N=class extends Error{constructor(e){super(),this.name="InvalidMethodError",this.message=e||"Invalid HTTP method",this.cause={statusCode:400}}};var se=class extends Error{constructor(e){super(),this.name="ServiceRequestError",this.message=e||"Service request failed",this.cause={statusCode:502}}};var ne=class{generatePermissionsFromBindings(e){let s=[];for(let r of e){let n=r.service;for(let o of r.permissions){if(!o.resource){s.push(`${n}.*`);continue}let i=o.resource,c=o.actions||["*"];if(o.targets&&o.targets.length>0)for(let a of c)for(let u of o.targets)s.push(`${n}.${i}.${a}:${u}`);else for(let a of c)s.push(`${n}.${i}.${a}`)}}return[...new Set(s)]}validateBindings(e){let s=["databases","storage","observability","sites","functions"];for(let r of e){if(!s.includes(r.service))throw new w(`Invalid service: ${r.service}. Must be one of: ${s.join(", ")}`);if(!r.permissions||r.permissions.length===0)throw new w("Bindings must have at least one permission");for(let n of r.permissions)if(n.targets&&n.targets.length>0){if(!n.resource)throw new w("Action-level bindings (with targets) must specify resource");if(!n.actions||n.actions.length===0)throw new w("Action-level bindings (with targets) must specify actions")}}}};var Se=class{constructor(e,s,r){this.baseUrl=e;this.authToken=s;this.bindings=r}async request(e,s,r,n){let o=`${this.baseUrl}${s}`;if(n){let d=new URLSearchParams(n);o+=`?${d.toString()}`}let i={"Content-Type":"application/json"};this.authToken&&(i.Authorization=`Bearer ${this.authToken}`),this.bindings&&this.bindings.length>0&&(i["X-Function-Bindings"]=JSON.stringify(this.bindings));let c={method:e,headers:i};r&&(c.body=JSON.stringify(r));let a=await fetch(o,c),u=a.headers.get("content-type"),l;if(u?.includes("application/json")?l=await a.json():l=await a.text(),!a.ok)throw new se(`Service request failed (${a.status}): ${typeof l=="string"?l:JSON.stringify(l)}`);return l}},je=class extends Se{async get(e,s){return this.request("POST","/get",{tableName:e,key:s})}async write(e,s,r,n,o){return this.request("POST","/write",{tableName:e,key:s,value:r,expiration:n,dictionaryName:o})}async delete(e,s){return this.request("DELETE","/delete",void 0,{tableName:e,key:s})}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}`)}},oe=class{constructor(e,s){this.serviceBaseUrls=e;this.authToken=s}createBindings(e){let s={};for(let r of e){let n=this.serviceBaseUrls[r.service];n&&r.service==="databases"&&(s.databases=new je(n,this.authToken,e))}return s}};import{EventEmitter as hr}from"node:events";var Ae=class t{static instance;constructor(){}static getInstance(){return t.instance||(t.instance=new hr,t.instance.setMaxListeners(100)),t.instance}};function Ce(){return Ae.getInstance()}function ft(t){let e=Ce();try{e.emit("function.log",t)}catch(s){console.error("Failed to emit function log event:",s)}}var B=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),n=this.compileErrors(s,r),o=this.isSuccessful(s,n);return{errors:n,success:o}}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 n=t?.additionalProperties??!0,o=t?.required||[];r=this.checkForRequiredKeysErrors(o,e,r),r=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),r,n);for(let i in t){let c=o.includes(i)&&i!=="required",a=t[i],u=e[i],l=a.additionalProperties??!0;c&&(r=this.checkForRequiredKeysErrors(a.required||[],u,r)),this.isDefined(u)&&(this.handleValidation(i,u,a,s),r=this.checkForDisallowedProperties(Object.keys(u),Object.keys(a),r,l),this.handleNestedObject(u,a,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):[],n=this.findNonOverlappingElements(t,r),o=n.length>0?`Missing the required key: '${n.join(", ")}'!`:`Missing values for required keys: '${r.filter(i=>!e[i]).join(", ")}'!`;s.push({key:"",value:e,success:!1,error:o})}return s}checkForDisallowedProperties(t,e,s,r){if(!r){let n=this.findNonOverlappingElements(t,e);n.length>0&&s.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${n.join(", ")}'!`})}return s}handleValidation(t,e,s,r){this.updatePropertyPath(t);let n=this.validateProperty(this.propertyPath,s,e);r.push(...n);let o=(c,a)=>{c.forEach(u=>{let l=this.validateProperty(this.propertyPath,a.items,u);r.push(...l)}),this.updatePropertyPath()},i=c=>{let a=Object.keys(c),u=this.propertyPath;a.forEach(l=>{if(this.updatePropertyPath(l,u),this.isArray(c[l])&&s[l]?.items!=null)o(c[l],s[l]);else{let d=this.validateProperty(this.propertyPath,s[l],c[l]);r.push(...d)}})};this.isArray(e)&&s.items!=null?o(e,s):this.isObject(e)?i(e):this.updatePropertyPath()}handleNestedObject(t,e,s,r){if(this.isObject(t)){let n=this.getNestedObjects(t);for(let o of n){let i=e[o],c=t[o];i&&typeof c=="object"&&this.validate(i,c,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(n=>{let{success:o,error:i}=n;return{key:t,value:s,success:o,error:i??""}})}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 n of s)n.condition()&&!n.validator()&&r.push({success:!1,error:n.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(o=>typeof o==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 ie(t){try{return await t.req.json()}catch{return{}}}function E(t,e="An error occurred"){let s=t?.message||t||e,r=t?.cause?.statusCode||t?.statusCode||400;return{message:s,status:r}}function pt(t,e,s={}){let r=Array.isArray(e)?e:[e];if(!t||!t.roles||!Array.isArray(t.roles)){let i=new Error("Unauthorized: User or roles missing");throw i.cause={statusCode:403},i}let n=t.roles.flatMap(i=>i?.policies?.flatMap(c=>(c?.permissions||[]).flatMap(u=>typeof u=="string"?u:u&&typeof u=="object"&&u.actions?u.actions:[]))||[]);if(!r.every(i=>n.includes(i)||n.includes("*")?!0:n.some(c=>{if(c.endsWith(".*")){let a=c.slice(0,-2);return i.startsWith(`${a}.`)}return!1}))){let i=new Error("Unauthorized");throw i.cause={statusCode:403},i}return!0}function mt(t,e,s,r,n){let o=t.find(a=>a.service===e);if(!o){let a=new Error(`Function bindings do not include access to service: ${e}`);throw a.cause={statusCode:403},a}if(!o.permissions||o.permissions.length===0)return;for(let a of o.permissions)if(!(a.resource&&a.resource!==s)){if(!a.resource||!a.actions||a.actions.length===0)return;if(a.actions.includes(r)){if(a.targets&&a.targets.length>0){if(!n)return;if(!a.targets.includes(n))continue}return}}let i=n?`:${n}`:"",c=new Error(`Function bindings do not allow: ${e}.${s}.${r}${i}`);throw c.cause={statusCode:403},c}async function x(t,e,s,r,n,o,i){if(!e)return null;let c=t.get("user");if(!c){let u=t.req.header("authorization");if(!u){let d=new Error("Unauthorized: No authentication provided");throw d.cause={statusCode:401},d}let l=u.replace(/^Bearer\s+/i,"");if(c=await e.getUserFromToken(l),!c){let d=new Error("Unauthorized: Invalid token");throw d.cause={statusCode:401},d}}pt(c,s,{});let a=t.req.header("x-function-bindings");if(a)try{let u=JSON.parse(a);mt(u,r,n,o,i)}catch(u){if(u.cause?.statusCode===403)throw u;let l=new Error("Invalid function bindings header");throw l.cause={statusCode:400},l}return c}var gt={properties:{name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},required:["name","code"],additionalProperties:!1};var pr=new B;async function yt(t,e,s){try{let r=await ie(t),n=pr.test(gt,r);if(!n.success)return t.json({error:"Invalid input",details:n.errors},400);await x(t,s,"functions.function.create","functions","function","create");let{name:o,code:i,methods:c,bindings:a,passAllHeaders:u,allowUnauthenticated:l}=r,d=await e.deployFunction(o,i,c,a,u,l);return t.json({success:!0,function:d},201)}catch(r){let{message:n,status:o}=E(r,"Error deploying function");return t.json({error:n},o)}}async function Oe(t,e,s){try{let{functionId:r}=t.req.param();if(!r)return t.json({error:"functionId is required"},400);let n=e.getFunction(r);return n?(n.allowUnauthenticated!==!0&&await x(t,s,"functions.function.execute","functions","function","execute",r),await e.executeFunction(r,t)):t.json({error:"Not Found",message:"Function not found"},404)}catch(r){let{message:n,status:o}=E(r,"Error executing function");return t.text(n,o)}}var bt={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var gr=new B;async function wt(t,e,s){try{let{functionId:r}=t.req.param(),n=await ie(t);if(!r)return t.json({error:"functionId is required"},400);let o=gr.test(bt,n);if(!o.success)return t.json({error:"Invalid input",details:o.errors},400);await x(t,s,"functions.function.update","functions","function","update",r);let{code:i,methods:c,bindings:a,passAllHeaders:u,allowUnauthenticated:l}=n,d=await e.updateFunction(r,{code:i,methods:c,bindings:a,passAllHeaders:u,allowUnauthenticated:l});return d?t.json({success:!0,function:d},200):t.json({error:"Function not found"},404)}catch(r){let{message:n,status:o}=E(r,"Error updating function");return t.json({error:n},o)}}async function vt(t,e,s){try{let{functionId:r}=t.req.param();return r?(await x(t,s,"functions.function.delete","functions","function","delete",r),await e.deleteFunction(r)?t.json({success:!0,message:"Function deleted"},200):t.json({error:"Function not found"},404)):t.json({error:"functionId is required"},400)}catch(r){let{message:n,status:o}=E(r,"Error deleting function");return t.json({error:n},o)}}async function Et(t,e,s){try{let{functionId:r}=t.req.param();if(!r)return t.json({error:"functionId is required"},400);await x(t,s,"functions.function.get","functions","function","read",r);let n=e.getFunction(r);return n?t.json({success:!0,function:n},200):t.json({error:"Function not found"},404)}catch(r){let{message:n,status:o}=E(r,"Error getting function");return t.json({error:n},o)}}async function xt(t,e,s){try{await x(t,s,"functions.function.get","functions","function","read");let r=e.getFunctions();return t.json({success:!0,count:r.length,functions:r},200)}catch(r){let{message:n,status:o}=E(r,"Error listing functions");return t.json({error:n},o)}}var ae=class{baseUrl;authToken;constructor(e,s){this.baseUrl=e.replace(/\/$/,""),this.authToken=s}async createCustomRole(e,s,r,n){let o=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:e,name:s,description:r,permissions:n})});if(!o.ok){let i=`Failed to create role: ${o.statusText}`;try{i=(await o.json()).error||i}catch{i=await o.text().catch(()=>o.statusText)||i}throw new Error(i)}}async updateRole(e,s){let r=await fetch(`${this.baseUrl}/identity/roles/${e}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(s)});if(!r.ok){let n=await r.json();throw new Error(n.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 n=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:e,description:s,roles:r})});if(!n.ok){let i=`Failed to create service account: ${n.statusText}`;try{i=(await n.json()).error||i}catch{i=await n.text().catch(()=>n.statusText)||i}throw new Error(i)}let o=await n.json();return{id:o.id,apiKey:o.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}};var Fe=class{functionsDir;functions=new Map;debug;bindingService;constructor(e){this.functionsDir=e.functionsDir||_(process.cwd(),"functions-data"),this.debug=e.debug||!1,this.bindingService=new ne}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions()}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.passAllHeaders!==void 0?{passAllHeaders:e.passAllHeaders}:{},...e.allowUnauthenticated!==void 0?{allowUnauthenticated:e.allowUnauthenticated}:{},createdAt:e.createdAt,updatedAt:e.updatedAt}))}async ensureFunctionsDirExists(){ce(this.functionsDir)||(this.debug&&console.log(`Creating functions directory: ${this.functionsDir}`),await br(this.functionsDir,{recursive:!0}))}async loadExistingFunctions(){try{let e=_(this.functionsDir,"functions.json");if(ce(e)){let s=await St(e,"utf8"),r=JSON.parse(s);for(let n of r)ce(n.filePath)&&(this.functions.set(n.id,n),this.debug&&console.log(`Loaded function: ${n.name} (${n.id})`))}}catch(e){this.debug&&console.error("Error loading functions metadata:",e.message)}}async saveFunctionsMetadata(){try{let e=_(this.functionsDir,"functions.json"),s=Array.from(this.functions.values());await Te(e,JSON.stringify(s,null,2),"utf8")}catch(e){this.debug&&console.error("Error saving functions metadata:",e.message)}}async deployFunction(e,s,r,n,o,i){if(!e||typeof e!="string")throw new w("Function name is required and must be a string");if(!s||typeof s!="string")throw new w("Function code is required and must be a string");if(r!==void 0){if(!Array.isArray(r))throw new w("Methods must be an array");let h=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let f of r)if(!h.includes(f.toUpperCase()))throw new N(`Invalid HTTP method: ${f}. Must be one of: ${h.join(", ")}`)}n&&n.length>0&&this.bindingService.validateBindings(n);let c=yr("sha256").update(`${e}-${Date.now()}`).digest("hex").substring(0,12),a=_(this.functionsDir,`${c}.mjs`),u=this.wrapFunctionCode(s);await Te(a,u,"utf8");let l=Date.now(),d={id:c,name:e,filePath:a,endpoint:`/functions/run/${c}`,...r&&r.length>0?{methods:r.map(h=>h.toUpperCase())}:{},...n?{bindings:n}:{},...o!==void 0?{passAllHeaders:o}:{},...i!==void 0?{allowUnauthenticated:i}:{},createdAt:l,updatedAt:l};return this.functions.set(c,d),await this.saveFunctionsMetadata(),this.debug&&(console.log(`Function deployed: ${e} (${c})`),console.log(`Endpoint: ${d.endpoint}`),d.methods&&console.log(`Allowed methods: ${d.methods.join(", ")}`)),d}async updateFunction(e,s){let r=this.functions.get(e);if(!r)throw new re(`Function with ID ${e} not found`);let{code:n,methods:o,bindings:i,passAllHeaders:c,allowUnauthenticated:a}=s;if(n===void 0&&o===void 0&&i===void 0&&c===void 0&&a===void 0)throw new w("At least one parameter (code, methods, bindings, passAllHeaders, or allowUnauthenticated) must be provided");if(n!==void 0&&(typeof n!="string"||!n))throw new w("Function code must be a non-empty string");if(o!==void 0){if(!Array.isArray(o))throw new w("Methods must be an array");let u=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let l of o)if(!u.includes(l.toUpperCase()))throw new N(`Invalid HTTP method: ${l}. Must be one of: ${u.join(", ")}`)}if(n!==void 0){let u=this.wrapFunctionCode(n);await Te(r.filePath,u,"utf8")}return o!==void 0&&(o.length>0?r.methods=o.map(u=>u.toUpperCase()):delete r.methods),i!==void 0&&(i.length>0&&this.bindingService.validateBindings(i),r.bindings=i.length>0?i:void 0),c!==void 0&&(c?r.passAllHeaders=!0:delete r.passAllHeaders),a!==void 0&&(r.allowUnauthenticated=a),r.updatedAt=Date.now(),this.functions.set(e,r),await this.saveFunctionsMetadata(),this.debug&&(console.log(`Function updated: ${r.name} (${e})`),r.methods&&console.log(`Allowed methods: ${r.methods.join(", ")}`)),r}async deleteFunction(e){let s=this.functions.get(e);if(!s)return!1;try{return ce(s.filePath)&&await wr(s.filePath),this.functions.delete(e),await this.saveFunctionsMetadata(),this.debug&&console.log(`Function deleted: ${s.name} (${e})`),!0}catch(r){throw console.error(`Error deleting function ${e}:`,r.message),r}}wrapFunctionCode(e){let s=e;if(/export\s+default\s+\w+/.test(e))return`// FunctionsService generated module
2
+ var Z=class{requests=new Map;limit;windowMs;constructor(e=100,t=60){this.limit=e,this.windowMs=t*1e3,setInterval(()=>this.cleanup(),this.windowMs)}getLimit(){return this.limit}isAllowed(e){let t=Date.now(),r=e||"unknown",n=this.requests.get(r);return(!n||n.resetTime<t)&&(n={count:0,resetTime:t+this.windowMs},this.requests.set(r,n)),n.count++,n.count<=this.limit}getRemainingRequests(e){let t=Date.now(),r=e||"unknown",n=this.requests.get(r);return!n||n.resetTime<t?this.limit:Math.max(0,this.limit-n.count)}getResetTime(e){let t=Date.now(),r=e||"unknown",n=this.requests.get(r);return!n||n.resetTime<t?Math.floor((t+this.windowMs)/1e3):Math.floor(n.resetTime/1e3)}cleanup(){let e=Date.now();for(let[t,r]of this.requests.entries())r.resetTime<e&&this.requests.delete(t)}};import{URL as gt}from"url";var K=class{routes=[];globalMiddlewares=[];pathPatterns=new Map;use(e){return this.globalMiddlewares.push(e),this}get(e,...t){let r=t.pop();return this.register("GET",e,r,t)}post(e,...t){let r=t.pop();return this.register("POST",e,r,t)}put(e,...t){let r=t.pop();return this.register("PUT",e,r,t)}delete(e,...t){let r=t.pop();return this.register("DELETE",e,r,t)}patch(e,...t){let r=t.pop();return this.register("PATCH",e,r,t)}any(e,...t){let r=t.pop(),n=t;return this.register("GET",e,r,n),this.register("POST",e,r,n),this.register("PUT",e,r,n),this.register("DELETE",e,r,n),this.register("PATCH",e,r,n),this.register("OPTIONS",e,r,n),this}options(e,...t){let r=t.pop();return this.register("OPTIONS",e,r,t)}match(e,t){for(let r of this.routes){if(r.method!==e)continue;let n=this.pathPatterns.get(r.path);if(!n)continue;let s=n.pattern.exec(t);if(!s)continue;let i={};return n.paramNames.forEach((o,a)=>{i[o]=s[a+1]||""}),{route:r,params:i}}return null}async handle(e,t){let r=e.method||"GET",n=new gt(e.url||"/",`http://${e.headers.host}`),s=n.pathname,i=this.match(r,s);if(!i)return null;let{route:o,params:a}=i,c={};n.searchParams.forEach((l,u)=>{c[u]=l});let d={req:e,res:t,params:a,query:c,body:e.body||{},headers:e.headers,path:s,state:{},raw:()=>t,binary:(l,u="application/octet-stream",h=200)=>({statusCode:h,body:l,headers:{"Content-Type":u,"Content-Length":l.length.toString()},isRaw:!0}),text:(l,u=200)=>({statusCode:u,body:l,headers:{"Content-Type":"text/plain"}}),form:(l,u=200)=>({statusCode:u,body:l,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),json:(l,u=200)=>({statusCode:u,body:l,headers:{"Content-Type":"application/json"}}),html:(l,u=200)=>({statusCode:u,body:l,headers:{"Content-Type":"text/html"}}),redirect:(l,u=302)=>({statusCode:u,body:null,headers:{Location:l}}),status:function(l){return{raw:()=>t,binary:(u,h="application/octet-stream")=>({statusCode:l,body:u,headers:{"Content-Type":h,"Content-Length":u.length.toString()},isRaw:!0}),text:u=>({statusCode:l,body:u,headers:{"Content-Type":"text/plain"}}),json:u=>({statusCode:l,body:u,headers:{"Content-Type":"application/json"}}),html:u=>({statusCode:l,body:u,headers:{"Content-Type":"text/html"}}),form:u=>({statusCode:l,body:u,headers:{"Content-Type":"application/x-www-form-urlencoded"}}),redirect:(u,h=302)=>({statusCode:h,body:null,headers:{Location:u}}),status:u=>this.status(u)}}},f=[...this.globalMiddlewares,...o.middlewares];return this.executeMiddlewareChain(d,f,o.handler)}register(e,t,r,n=[]){return this.routes.push({method:e,path:t,handler:r,middlewares:n}),this.pathPatterns.set(t,this.createPathPattern(t)),this}createPathPattern(e){let t=[],r=e.replace(/\/:[^/]+/g,n=>{let s=n.slice(2);return t.push(s),"/([^/]+)"});return r.endsWith("/*")?(r=`${r.slice(0,-2)}(?:/(.*))?`,t.push("wildcard")):r=r.replace(/\/$/,"/?"),{pattern:new RegExp(`^${r}$`),paramNames:t}}async executeMiddlewareChain(e,t,r){let n=0,s=async()=>{if(n<t.length){let i=t[n++];return i(e,s)}return r(e)};return s()}};var R=()=>({port:Number(process.env.PORT)||3e3,host:process.env.HOST||"0.0.0.0",useHttps:!1,useHttp2:!1,sslCert:"",sslKey:"",sslCa:"",debug:yt(process.env.DEBUG)||!1,maxBodySize:1048576,requestTimeout:3e4,rateLimit:{enabled:!0,requestsPerMinute:100},allowedDomains:["*"]});function yt(e){return e==="true"||e===!0}var N=class extends Error{constructor(e){super(e),this.name="ValidationError",this.message=e||"Validation did not pass",this.cause={statusCode:400}}};import{existsSync as bt,readFileSync as wt}from"node:fs";var U=class{config={};options=[];validators=[];autoValidate=!0;constructor(e){let t=e?.configFilePath,r=e?.args||[],n=e?.config||{};this.options=e?.options||[],this.validators=e?.validators||[],e?.autoValidate!==void 0&&(this.autoValidate=e.autoValidate),this.config=this.createConfig(t,r,n)}deepMerge(e,t){let r={...e};for(let n in t)t[n]!==void 0&&(t[n]!==null&&typeof t[n]=="object"&&!Array.isArray(t[n])&&n in e&&e[n]!==null&&typeof e[n]=="object"&&!Array.isArray(e[n])?r[n]=this.deepMerge(e[n],t[n]):t[n]!==void 0&&(r[n]=t[n]));return r}setValueAtPath(e,t,r){let n=t.split("."),s=e;for(let 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(e,t){let r=t.split("."),n=e;for(let s of r){if(n==null)return;n=n[s]}return n}createConfig(e,t=[],r={}){let n={};for(let a of this.options)a.defaultValue!==void 0&&this.setValueAtPath(n,a.path,a.defaultValue);let s={};if(e&&bt(e))try{let a=wt(e,"utf8");s=JSON.parse(a),console.log(`Loaded configuration from ${e}`)}catch(a){console.error(`Error reading config file: ${a instanceof Error?a.message:String(a)}`)}let i=this.parseCliArgs(t),o=this.deepMerge({},n);return o=this.deepMerge(o,s),o=this.deepMerge(o,r),o=this.deepMerge(o,i),o}parseCliArgs(e){let t={},r=e[0]?.endsWith("node")||e[0]?.endsWith("node.exe")?2:0;for(;r<e.length;){let n=e[r++],s=this.options.find(i=>i.flag===n);if(s)if(s.isFlag)this.setValueAtPath(t,s.path,!0);else if(r<e.length&&!e[r].startsWith("-")){let i=e[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(t,s.path,i)}else console.error(`Missing value for option ${n}`)}return t}validate(){for(let e of this.validators){let t=this.getValueAtPath(this.config,e.path),r=e.validator(t,this.config);if(r===!1)throw new N(e.message);if(typeof r=="string")throw new N(r)}}get(){return this.autoValidate&&this.validate(),this.config}getValue(e,t){let r=this.getValueAtPath(this.config,e);return r!==void 0?r:t}setValue(e,t){if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=this.getValueAtPath(this.config,e)||{};if(typeof r=="object"&&!Array.isArray(r)){let n=this.deepMerge(r,t);this.setValueAtPath(this.config,e,n);return}}this.setValueAtPath(this.config,e,t)}getHelpText(){let e=`Available configuration options:
3
+
4
+ `;for(let t of this.options)e+=`${t.flag}${t.isFlag?"":" <value>"}
5
+ `,t.description&&(e+=` ${t.description}
6
+ `),t.defaultValue!==void 0&&(e+=` Default: ${JSON.stringify(t.defaultValue)}
7
+ `),e+=`
8
+ `;return e}};var V={int:e=>{let t=e.trim();if(!/^[+-]?\d+$/.test(t))throw new Error(`Cannot parse "${e}" as an integer`);let r=Number.parseInt(t,10);if(Number.isNaN(r))throw new Error(`Cannot parse "${e}" as an integer`);return r},float:e=>{let t=e.trim();if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(t)){if(t==="Infinity"||t==="-Infinity")return t==="Infinity"?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY;throw new Error(`Cannot parse "${e}" as a number`)}let r=Number.parseFloat(t);if(Number.isNaN(r))throw new Error(`Cannot parse "${e}" as a number`);return r},boolean:e=>{let t=e.trim().toLowerCase();if(["true","yes","1","y"].includes(t))return!0;if(["false","no","0","n"].includes(t))return!1;throw new Error(`Cannot parse "${e}" as a boolean`)},array:e=>e.split(",").map(t=>t.trim()),json:e=>{try{return JSON.parse(e)}catch{throw new Error(`Cannot parse "${e}" as JSON`)}}};var b=R(),Q=e=>({configFilePath:"mikroserve.config.json",args:process.argv,options:[{flag:"--port",path:"port",defaultValue:b.port},{flag:"--host",path:"host",defaultValue:b.host},{flag:"--https",path:"useHttps",defaultValue:b.useHttps,isFlag:!0},{flag:"--http2",path:"useHttp2",defaultValue:b.useHttp2,isFlag:!0},{flag:"--cert",path:"sslCert",defaultValue:b.sslCert},{flag:"--key",path:"sslKey",defaultValue:b.sslKey},{flag:"--ca",path:"sslCa",defaultValue:b.sslCa},{flag:"--ratelimit",path:"rateLimit.enabled",defaultValue:b.rateLimit.enabled,isFlag:!0},{flag:"--rps",path:"rateLimit.requestsPerMinute",defaultValue:b.rateLimit.requestsPerMinute},{flag:"--allowed",path:"allowedDomains",defaultValue:b.allowedDomains,parser:V.array},{flag:"--debug",path:"debug",defaultValue:b.debug,isFlag:!0},{flag:"--max-body-size",path:"maxBodySize",defaultValue:b.maxBodySize},{flag:"--request-timeout",path:"requestTimeout",defaultValue:b.requestTimeout}],config:e});function tt(e,t){let r=t.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!r)throw new Error("Invalid multipart/form-data: missing boundary");let n=r[1]||r[2],s=Buffer.from(`--${n}`),i=Buffer.from(`--${n}--`),o={},a={},c=vt(e,s);for(let d of c){if(d.length===0||d.equals(i.subarray(s.length)))continue;let f=St(d);if(!f)continue;let{name:l,filename:u,contentType:h,data:p}=f;if(u){let m={filename:u,contentType:h||"application/octet-stream",data:p,size:p.length};a[l]?Array.isArray(a[l])?a[l].push(m):a[l]=[a[l],m]:a[l]=m}else{let m=p.toString("utf8");o[l]?Array.isArray(o[l])?o[l].push(m):o[l]=[o[l],m]:o[l]=m}}return{fields:o,files:a}}function vt(e,t){let r=[],n=0;for(;n<e.length;){let s=e.indexOf(t,n);if(s===-1)break;n!==s&&r.push(e.subarray(n,s)),n=s+t.length,n<e.length&&e[n]===13&&e[n+1]===10&&(n+=2)}return r}function St(e){let t=Buffer.from(`\r
9
+ \r
10
+ `),r=e.indexOf(t);if(r===-1)return null;let n=e.subarray(0,r),s=e.subarray(r+4),o=n.toString("utf8").split(`\r
11
+ `),a="",c="",d,f;for(let u of o){let h=u.toLowerCase();if(h.startsWith("content-disposition:")){a=u.substring(20).trim();let p=a.match(/name="([^"]+)"/);p&&(c=p[1]);let m=a.match(/filename="([^"]+)"/);m&&(d=m[1])}else h.startsWith("content-type:")&&(f=u.substring(13).trim())}if(!c)return null;let l=s;return l.length>=2&&l[l.length-2]===13&&l[l.length-1]===10&&(l=l.subarray(0,l.length-2)),{disposition:a,name:c,filename:d,contentType:f,data:l}}import{readFileSync as x}from"fs";import B from"http";import Ct from"http2";import xt from"https";var z=class{config;rateLimiter;router;shutdownHandlers=[];constructor(e){let t=new U(Q(e||{})).get();t.debug&&console.log("Using configuration:",t),this.config=t,this.router=new K;let r=t.rateLimit.requestsPerMinute||R().rateLimit.requestsPerMinute;this.rateLimiter=new Z(r,60),t.rateLimit.enabled===!0&&this.use(this.rateLimitMiddleware.bind(this))}use(e){return this.router.use(e),this}get(e,...t){return this.router.get(e,...t),this}post(e,...t){return this.router.post(e,...t),this}put(e,...t){return this.router.put(e,...t),this}delete(e,...t){return this.router.delete(e,...t),this}patch(e,...t){return this.router.patch(e,...t),this}any(e,...t){return this.router.any(e,...t),this}options(e,...t){return this.router.options(e,...t),this}start(){let e=this.createServer(),{port:t,host:r}=this.config;return this.setupGracefulShutdown(e),e.listen(t,r,()=>{let n=e.address(),s=this.config.useHttps||this.config.useHttp2?"https":"http";console.log(`MikroServe running at ${s}://${n.address!=="::"?n.address:"localhost"}:${n.port}`)}),e}createServer(){let e=this.requestHandler.bind(this);if(this.config.useHttp2){if(!this.config.sslCert||!this.config.sslKey)throw new Error("SSL certificate and key paths are required when useHttp2 is true");try{let t={key:x(this.config.sslKey),cert:x(this.config.sslCert),...this.config.sslCa?{ca:x(this.config.sslCa)}:{}};return Ct.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 xt.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 B.createServer(e)}async rateLimitMiddleware(e,t){let r=e.req.socket.remoteAddress||"unknown";return e.res.setHeader("X-RateLimit-Limit",this.rateLimiter.getLimit().toString()),e.res.setHeader("X-RateLimit-Remaining",this.rateLimiter.getRemainingRequests(r).toString()),e.res.setHeader("X-RateLimit-Reset",this.rateLimiter.getResetTime(r).toString()),this.rateLimiter.isAllowed(r)?t():{statusCode:429,body:{error:"Too Many Requests",message:"Rate limit exceeded, please try again later"},headers:{"Content-Type":"application/json"}}}async requestHandler(e,t){let r=Date.now(),n=e.method||"UNKNOWN",s=e.url||"/unknown",i=this.config.debug;try{if(this.setCorsHeaders(t,e),this.setSecurityHeaders(t,this.config.useHttps),i&&console.log(`${n} ${s}`),e.method==="OPTIONS"){if(t instanceof B.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 i&&console.error("Body parsing error:",a.message),this.respond(t,{statusCode:400,body:{error:"Bad Request",message:a.message}})}let o=await this.router.handle(e,t);return o?o._handled?void 0:this.respond(t,o):this.respond(t,{statusCode:404,body:{error:"Not Found",message:"The requested endpoint does not exist"}})}catch(o){return console.error("Server error:",o),this.respond(t,{statusCode:500,body:{error:"Internal Server Error",message:i?o.message:"An unexpected error occurred"}})}finally{i&&this.logDuration(r,n,s)}}logDuration(e,t,r){let n=Date.now()-e;console.log(`${t} ${r} completed in ${n}ms`)}async parseBody(e){return new Promise((t,r)=>{let n=[],s=0,i=this.config.maxBodySize,o=!1,a=null,c=this.config.debug,d=e.headers["content-type"]||"";c&&console.log("Content-Type:",d),this.config.requestTimeout>0&&(a=setTimeout(()=>{o||(o=!0,c&&console.log("Request timeout exceeded"),r(new Error("Request timeout")))},this.config.requestTimeout));let f=()=>{a&&(clearTimeout(a),a=null)};e.on("data",l=>{if(!o){if(s+=l.length,c&&console.log(`Received chunk: ${l.length} bytes, total size: ${s}`),s>i){o=!0,f(),c&&console.log(`Body size exceeded limit: ${s} > ${i}`),r(new Error("Request body too large"));return}n.push(l)}}),e.on("end",()=>{if(!o){o=!0,f(),c&&console.log(`Request body complete: ${s} bytes`);try{if(n.length>0){let l=Buffer.concat(n);if(d.includes("application/json"))try{let u=l.toString("utf8");t(JSON.parse(u))}catch(u){r(new Error(`Invalid JSON in request body: ${u.message}`))}else if(d.includes("application/x-www-form-urlencoded")){let u=l.toString("utf8"),h={};new URLSearchParams(u).forEach((p,m)=>{h[m]=p}),t(h)}else if(d.includes("multipart/form-data"))try{let u=tt(l,d);t(u)}catch(u){r(new Error(`Invalid multipart form data: ${u.message}`))}else this.isBinaryContentType(d)?t(l):t(l.toString("utf8"))}else t({})}catch(l){r(new Error(`Invalid request body: ${l}`))}}}),e.on("error",l=>{o||(o=!0,f(),r(new Error(`Error reading request body: ${l.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(r=>e.includes(r))}setCorsHeaders(e,t){let r=t.headers.origin,{allowedDomains:n=["*"]}=this.config;!r||n.length===0||n.includes("*")?e.setHeader("Access-Control-Allow-Origin","*"):n.includes(r)&&(e.setHeader("Access-Control-Allow-Origin",r),e.setHeader("Vary","Origin")),e.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, PATCH, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),e.setHeader("Access-Control-Max-Age","86400")}setSecurityHeaders(e,t=!1){let r={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'self'; script-src 'self'; object-src 'none'","X-XSS-Protection":"1; mode=block"};if((t||this.config.useHttp2)&&(r["Strict-Transport-Security"]="max-age=31536000; includeSubDomains"),e instanceof B.ServerResponse)Object.entries(r).forEach(([n,s])=>{e.setHeader(n,s)});else{let n=e;Object.entries(r).forEach(([s,i])=>{n.setHeader(s,i)})}}respond(e,t){let r={...t.headers||{}};(s=>typeof s.writeHead=="function"&&typeof s.end=="function")(e)?(e.writeHead(t.statusCode,r),t.body===null||t.body===void 0?e.end():t.isRaw||typeof t.body=="string"?e.end(t.body):e.end(JSON.stringify(t.body))):(console.warn("Unexpected response object type without writeHead/end methods"),e.writeHead?.(t.statusCode,r),t.body===null||t.body===void 0?e.end?.():t.isRaw||typeof t.body=="string"?e.end?.(t.body):e.end?.(JSON.stringify(t.body)))}setupGracefulShutdown(e){let t=o=>{console.log("Shutting down MikroServe server..."),o&&console.error("Error:",o),this.cleanupShutdownHandlers(),e.close(()=>{console.log("Server closed successfully"),process.env.NODE_ENV!=="test"&&process.env.VITEST!=="true"&&setImmediate(()=>process.exit(o?1:0))})},r=()=>t(),n=()=>t(),s=o=>t(o),i=o=>t(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[e,t,r,n]=this.shutdownHandlers;process.removeListener("SIGINT",e),process.removeListener("SIGTERM",t),process.removeListener("uncaughtException",r),process.removeListener("unhandledRejection",n),this.shutdownHandlers=[]}}};import{createHash as Rt}from"node:crypto";import{existsSync as L}from"node:fs";import{join as j}from"node:path";import{mkdir as $t,writeFile as X,readFile as mt,unlink as Ot}from"node:fs/promises";import{pathToFileURL as Ht}from"node:url";var y=class extends Error{constructor(t){super(),this.name="ValidationError",this.message=t||"Invalid input",this.cause={statusCode:400}}};var $=class extends Error{constructor(t){super(),this.name="NotFoundError",this.message=t||"Resource not found",this.cause={statusCode:404}}};var A=class extends Error{constructor(t){super(),this.name="InvalidMethodError",this.message=t||"Invalid HTTP method",this.cause={statusCode:400}}};var O=class extends Error{constructor(t){super(),this.name="ServiceRequestError",this.message=t||"Service request failed",this.cause={statusCode:502}}};var H=class{generatePermissionsFromBindings(t){let r=[];for(let n of t){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 d of i.targets)r.push(`${s}.${o}.${c}:${d}`);else for(let c of a)r.push(`${s}.${o}.${c}`)}}return[...new Set(r)]}validateBindings(t){let r=["databases","storage","observability","sites","functions"];for(let n of t){if(!r.includes(n.service))throw new y(`Invalid service: ${n.service}. Must be one of: ${r.join(", ")}`);if(!n.permissions||n.permissions.length===0)throw new y("Bindings must have at least one permission");for(let s of n.permissions)if(s.targets&&s.targets.length>0){if(!s.resource)throw new y("Action-level bindings (with targets) must specify resource");if(!s.actions||s.actions.length===0)throw new y("Action-level bindings (with targets) must specify actions")}}}};var G=class{constructor(t,r,n){this.baseUrl=t;this.authToken=r;this.bindings=n}async request(t,r,n,s){let i=`${this.baseUrl}${r}`;if(s){let l=new URLSearchParams(s);i+=`?${l.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:t,headers:o};n&&(a.body=JSON.stringify(n));let c=await fetch(i,a),d=c.headers.get("content-type"),f;if(d?.includes("application/json")?f=await c.json():f=await c.text(),!c.ok)throw new O(`Service request failed (${c.status}): ${typeof f=="string"?f:JSON.stringify(f)}`);return f}},J=class extends G{async get(t,r){return this.request("POST","/get",{tableName:t,key:r})}async write(t,r,n,s,i){return this.request("POST","/write",{tableName:t,key:r,value:n,expiration:s,dictionaryName:i})}async delete(t,r){return this.request("DELETE","/delete",void 0,{tableName:t,key:r})}async listTables(){return this.request("GET","/tables")}async getTableSize(t){return this.request("GET","/table",void 0,{tableName:t})}async getTableInfo(t){return this.request("GET",`/tables/${t}`)}async createTable(t){return this.request("POST",`/tables/${t}`)}async deleteTable(t){return this.request("DELETE",`/tables/${t}`)}},M=class{constructor(t,r){this.serviceBaseUrls=t;this.authToken=r}createBindings(t){let r={};for(let n of t){let s=this.serviceBaseUrls[n.service];s&&n.service==="databases"&&(r.databases=new J(s,this.authToken,t))}return r}};import{EventEmitter as Et}from"node:events";var W=class e{static instance;constructor(){}static getInstance(){return e.instance||(e.instance=new Et,e.instance.setMaxListeners(100)),e.instance}};function _(){return W.getInstance()}function et(e){let t=_();try{t.emit("function.log",e)}catch(r){console.error("Failed to emit function log event:",r)}}async function E(e){return e.body||{}}var F=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:r,errors:n}=this.validate(e.properties,t),s=this.compileErrors(r,n),i=this.isSuccessful(r,s);return{errors:s,success:i}}compileErrors(e,t){let r=e.filter(n=>n.success===!1);return[...t,...r].flatMap(n=>n)}isSuccessful(e,t){return e.every(r=>r.success===!0)&&t.length===0}validate(e,t,r=[],n=[]){let s=e?.additionalProperties??!0,i=e?.required||[];n=this.checkForRequiredKeysErrors(i,t,n),n=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),n,s);for(let o in e){let a=i.includes(o)&&o!=="required",c=e[o],d=t[o],f=c.additionalProperties??!0;a&&(n=this.checkForRequiredKeysErrors(c.required||[],d,n)),this.isDefined(d)&&(this.handleValidation(o,d,c,r),n=this.checkForDisallowedProperties(Object.keys(d),Object.keys(c),n,f),this.handleNestedObject(d,c,r,n))}return{results:r,errors:n}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,r){if(!this.areRequiredKeysPresent(e,t)){let n=t?Object.keys(t):[],s=this.findNonOverlappingElements(e,n),i=s.length>0?`Missing the required key: '${s.join(", ")}'!`:`Missing values for required keys: '${n.filter(o=>!t[o]).join(", ")}'!`;r.push({key:"",value:t,success:!1,error:i})}return r}checkForDisallowedProperties(e,t,r,n){if(!n){let s=this.findNonOverlappingElements(e,t);s.length>0&&r.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${s.join(", ")}'!`})}return r}handleValidation(e,t,r,n){this.updatePropertyPath(e);let s=this.validateProperty(this.propertyPath,r,t);n.push(...s);let i=(a,c)=>{a.forEach(d=>{let f=this.validateProperty(this.propertyPath,c.items,d);n.push(...f)}),this.updatePropertyPath()},o=a=>{let c=Object.keys(a),d=this.propertyPath;c.forEach(f=>{if(this.updatePropertyPath(f,d),this.isArray(a[f])&&r[f]?.items!=null)i(a[f],r[f]);else{let l=this.validateProperty(this.propertyPath,r[f],a[f]);n.push(...l)}})};this.isArray(t)&&r.items!=null?i(t,r):this.isObject(t)?o(t):this.updatePropertyPath()}handleNestedObject(e,t,r,n){if(this.isObject(e)){let s=this.getNestedObjects(e);for(let i of s){let o=t[i],a=e[i];o&&typeof a=="object"&&this.validate(o,a,r,n)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(r=>!t.includes(r))}areRequiredKeysPresent(e,t=[]){return e.every(r=>Object.keys(t).includes(r)?this.isDefined(t[r]):!1)}validateProperty(e,t,r){return this.validateInput(t,r).map(s=>{let{success:i,error:o}=s;return{key:e,value:r,success:i,error:o??""}})}validateInput(e,t){if(e){let r=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],n=[];for(let s of r)s.condition()&&!s.validator()&&n.push({success:!1,error:s.error});return n}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(r=>{switch(r){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let r in e){let n=e[r];t.properties.required.push(r),Array.isArray(n)?t.properties[r]=this.generateArraySchema(n):typeof n=="object"&&n!==null?t.properties[r]=this.generateNestedObjectSchema(n):t.properties[r]=this.generatePropertySchema(n)}return t}generateArraySchema(e){let t={type:"array"},r=e.filter(n=>n);if(r.length>0){let n=r[0];r.every(i=>typeof i==typeof n)?typeof n=="object"&&!Array.isArray(n)?t.items=this.generateNestedObjectSchema(n):t.items=this.generatePropertySchema(n):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let r in e){let n=e[r];t.required.push(r),typeof n=="object"&&!Array.isArray(n)&&n!==null?t[r]=this.generateNestedObjectSchema(n):t[r]=this.generatePropertySchema(n)}return t}generatePropertySchema(e){let t=typeof e,r={type:t};return t==="string"&&(r.minLength=1),r}};function w(e,t="An error occurred"){let r=e?.message||e||t,n=e?.cause?.statusCode||e?.statusCode||400;return{message:r,status:n}}function rt(e,t,r={}){let n=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let o=new Error("Unauthorized: User or roles missing");throw o.cause={statusCode:403},o}let s=e.roles.flatMap(o=>o?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(d=>typeof d=="string"?d:d&&typeof d=="object"&&d.actions?d.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 nt(e,t,r,n,s){let i=e.find(c=>c.service===t);if(!i){let c=new Error(`Function bindings do not include access to service: ${t}`);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: ${t}.${r}.${n}${o}`);throw a.cause={statusCode:403},a}async function v(e,t,r,n,s,i,o){if(!t)return null;let a=e.state.user;if(!a){let d=e.headers.authorization;if(!d){let l=new Error("Unauthorized: No authentication provided");throw l.cause={statusCode:401},l}let f=d.replace(/^Bearer\s+/i,"");if(a=await t.getUserFromToken(f),!a){let l=new Error("Unauthorized: Invalid token");throw l.cause={statusCode:401},l}}rt(a,r,{});let c=e.headers["x-function-bindings"];if(c)try{let d=Array.isArray(c)?c[0]:c,f=JSON.parse(d);nt(f,n,s,i,o)}catch(d){if(d.cause?.statusCode===403)throw d;let f=new Error("Invalid function bindings header");throw f.cause={statusCode:400},f}return a}var st={properties:{name:{type:"string",minLength:1},code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},required:["name","code"],additionalProperties:!1};var Tt=new F;async function it(e,t,r){try{let n=await E(e),s=Tt.test(st,n);if(!s.success)return e.json({error:"Invalid input",details:s.errors},400);await v(e,r,"functions.function.create","functions","function","create");let{name:i,code:o,methods:a,bindings:c,passAllHeaders:d,allowUnauthenticated:f}=n,l=await t.deployFunction(i,o,a,c,d,f);return e.json({success:!0,function:l},201)}catch(n){let{message:s,status:i}=w(n,"Error deploying function");return e.json({error:s},i)}}async function ot(e,t,r){try{let n=e.params.functionId;if(!n)return e.json({error:"functionId is required"},400);let s=t.getFunction(n);return s?(s.allowUnauthenticated!==!0&&await v(e,r,"functions.function.execute","functions","function","execute",n),await t.executeFunction(n,e)):e.json({error:"Not Found",message:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error executing function");return e.json({error:s},i)}}var at={properties:{code:{type:"string",minLength:1},methods:{type:"array",items:{type:"string"}},bindings:{type:"array"},passAllHeaders:{type:"boolean"},allowUnauthenticated:{type:"boolean"}},additionalProperties:!1};var At=new F;async function ct(e,t,r){try{let n=e.params.functionId,s=await E(e);if(!n)return e.json({error:"functionId is required"},400);let i=At.test(at,s);if(!i.success)return e.json({error:"Invalid input",details:i.errors},400);await v(e,r,"functions.function.update","functions","function","update",n);let{code:o,methods:a,bindings:c,passAllHeaders:d,allowUnauthenticated:f}=s,l=await t.updateFunction(n,{code:o,methods:a,bindings:c,passAllHeaders:d,allowUnauthenticated:f});return l?e.json({success:!0,function:l},200):e.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error updating function");return e.json({error:s},i)}}async function ut(e,t,r){try{let n=e.params.functionId;return n?(await v(e,r,"functions.function.delete","functions","function","delete",n),await t.deleteFunction(n)?e.json({success:!0,message:"Function deleted"},200):e.json({error:"Function not found"},404)):e.json({error:"functionId is required"},400)}catch(n){let{message:s,status:i}=w(n,"Error deleting function");return e.json({error:s},i)}}async function dt(e,t,r){try{let n=e.params.functionId;if(!n)return e.json({error:"functionId is required"},400);await v(e,r,"functions.function.get","functions","function","read",n);let s=t.getFunction(n);return s?e.json({success:!0,function:s},200):e.json({error:"Function not found"},404)}catch(n){let{message:s,status:i}=w(n,"Error getting function");return e.json({error:s},i)}}async function lt(e,t,r){try{await v(e,r,"functions.function.get","functions","function","read");let n=t.getFunctions();return e.json({success:!0,count:n.length,functions:n},200)}catch(n){let{message:s,status:i}=w(n,"Error listing functions");return e.json({error:s},i)}}import{readFileSync as Ft,existsSync as jt}from"node:fs";function P(){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:""},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||!jt(e))return t;try{let r=Ft(e,"utf-8");return JSON.parse(r)}catch(r){return console.error("[loadRuntimeConfig] Failed to load runtime config:",r),t}}function ft(e,t){let r={enabled:!1,requestsPerMinute:0};if(!t)return r;let n=t.services?.[e];return n||(t.global?t.global:r)}function ht(e,t){let r=e?.api?.port;if(!r)throw new Error('Missing "port" input when create API service!');let n=P(),s=e?.dataPath||n.molnos.dataPath,i=e?.api?.host||n.server.host,o=e?.identityApiUrl!==void 0?e.identityApiUrl:n.identity.apiUrl,a=e?.debug||!1,c;return t&&(c=ft(t,n.molnos.rateLimit)),{dataPath:s,api:{port:r,host:i},...o?{identityApiUrl:o}:{},...c?{rateLimit:c}:{},debug:a}}var k=class{baseUrl;authToken;constructor(t,r){this.baseUrl=t.replace(/\/$/,""),this.authToken=r}async createCustomRole(t,r,n,s){let i=await fetch(`${this.baseUrl}/identity/roles`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({roleId:t,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(t,r){let n=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"PATCH",headers:this.getHeaders(),body:JSON.stringify(r)});if(!n.ok){let s=await n.json();throw new Error(s.error||`Failed to update role: ${n.statusText}`)}}async deleteRole(t){let r=await fetch(`${this.baseUrl}/identity/roles/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete role: ${r.statusText}`)}}async addServiceAccount(t,r,n){let s=await fetch(`${this.baseUrl}/identity/service-accounts`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({name:t,description:r,roles:n})});if(!s.ok){let 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(t){let r=await fetch(`${this.baseUrl}/identity/service-accounts/${t}`,{method:"DELETE",headers:this.getHeaders()});if(!r.ok){let n=await r.json();throw new Error(n.error||`Failed to delete service account: ${r.statusText}`)}}async getUserFromToken(t){try{let r=await fetch(`${this.baseUrl}/identity/whoami`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});return r.ok?await r.json():null}catch{return null}}getHeaders(){let t={"Content-Type":"application/json"};return this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),t}};function pt(e){return e?new k(e):null}var Y=class{functionsDir;functions=new Map;debug;bindingService;constructor(t){this.functionsDir=t.functionsDir||j(process.cwd(),"functions-data"),this.debug=t.debug||!1,this.bindingService=new H}async start(){await this.ensureFunctionsDirExists(),await this.loadExistingFunctions()}getFunction(t){return this.functions.get(t)}getFunctions(){return Array.from(this.functions.values()).map(t=>({name:t.name,endpoint:t.endpoint,id:t.id,filePath:t.filePath,methods:t.methods,...t.bindings?{bindings:t.bindings}:{},...t.passAllHeaders!==void 0?{passAllHeaders:t.passAllHeaders}:{},...t.allowUnauthenticated!==void 0?{allowUnauthenticated:t.allowUnauthenticated}:{},createdAt:t.createdAt,updatedAt:t.updatedAt}))}async ensureFunctionsDirExists(){L(this.functionsDir)||await $t(this.functionsDir,{recursive:!0})}async loadExistingFunctions(){try{let t=j(this.functionsDir,"functions.json");if(L(t)){let r=await mt(t,"utf8"),n=JSON.parse(r);for(let s of n)L(s.filePath)&&this.functions.set(s.id,s)}}catch{}}async saveFunctionsMetadata(){try{let t=j(this.functionsDir,"functions.json"),r=Array.from(this.functions.values());await X(t,JSON.stringify(r,null,2),"utf8")}catch{}}async deployFunction(t,r,n,s,i,o){if(!t||typeof t!="string")throw new y("Function name is required and must be a string");if(!r||typeof r!="string")throw new y("Function code is required and must be a string");if(n!==void 0){if(!Array.isArray(n))throw new y("Methods must be an array");let u=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let h of n)if(!u.includes(h.toUpperCase()))throw new A(`Invalid HTTP method: ${h}. Must be one of: ${u.join(", ")}`)}s&&s.length>0&&this.bindingService.validateBindings(s);let a=Rt("sha256").update(`${t}-${Date.now()}`).digest("hex").substring(0,12),c=j(this.functionsDir,`${a}.mjs`),d=this.wrapFunctionCode(r);await X(c,d,"utf8");let f=Date.now(),l={id:a,name:t,filePath:c,endpoint:`/functions/run/${a}`,...n&&n.length>0?{methods:n.map(u=>u.toUpperCase())}:{},...s?{bindings:s}:{},...i!==void 0?{passAllHeaders:i}:{},...o!==void 0?{allowUnauthenticated:o}:{},createdAt:f,updatedAt:f};return this.functions.set(a,l),await this.saveFunctionsMetadata(),l}async updateFunction(t,r){let n=this.functions.get(t);if(!n)throw new $(`Function with ID ${t} not found`);let{code:s,methods:i,bindings:o,passAllHeaders:a,allowUnauthenticated:c}=r;if(s===void 0&&i===void 0&&o===void 0&&a===void 0&&c===void 0)throw new y("At least one parameter (code, methods, bindings, passAllHeaders, or allowUnauthenticated) must be provided");if(s!==void 0&&(typeof s!="string"||!s))throw new y("Function code must be a non-empty string");if(i!==void 0){if(!Array.isArray(i))throw new y("Methods must be an array");let d=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let f of i)if(!d.includes(f.toUpperCase()))throw new A(`Invalid HTTP method: ${f}. Must be one of: ${d.join(", ")}`)}if(s!==void 0){let d=this.wrapFunctionCode(s);await X(n.filePath,d,"utf8")}return i!==void 0&&(i.length>0?n.methods=i.map(d=>d.toUpperCase()):delete n.methods),o!==void 0&&(o.length>0&&this.bindingService.validateBindings(o),n.bindings=o.length>0?o:void 0),a!==void 0&&(a?n.passAllHeaders=!0:delete n.passAllHeaders),c!==void 0&&(n.allowUnauthenticated=c),n.updatedAt=Date.now(),this.functions.set(t,n),await this.saveFunctionsMetadata(),n}async deleteFunction(t){let r=this.functions.get(t);if(!r)return!1;try{return L(r.filePath)&&await Ot(r.filePath),this.functions.delete(t),await this.saveFunctionsMetadata(),!0}catch(n){throw console.error(`Error deleting function ${t}:`,n.message),n}}wrapFunctionCode(t){let r=t;if(/export\s+default\s+\w+/.test(t))return`// FunctionsService generated module
3
12
  // Generated at: ${new Date().toISOString()}
4
13
 
5
14
  // User function code starts here
6
- ${s}
15
+ ${r}
7
16
  // User function code ends here
8
- `;let r=e.match(/export\s*\{([^}]+)\}/);if(r){let n=r[1],o=n.match(/(\w+)\s+as\s+handler\b/)||n.match(/\bhandler\b/);if(o){let i=o[1]||"handler";s=e.replace(/export\s*\{[^}]+\}/,`export default ${i}`)}}else s=`${e}
17
+ `;let n=t.match(/export\s*\{([^}]+)\}/);if(n){let s=n[1],i=s.match(/(\w+)\s+as\s+handler\b/)||s.match(/\bhandler\b/);if(i){let o=i[1]||"handler";r=t.replace(/export\s*\{[^}]+\}/,`export default ${o}`)}}else r=`${t}
9
18
 
10
19
  export default handler;`;return`// FunctionsService generated module
11
20
  // Generated at: ${new Date().toISOString()}
12
21
 
13
22
  // User function code starts here
14
- ${s}
23
+ ${r}
15
24
  // User function code ends here
16
- `}async executeFunction(e,s){try{let r=this.functions.get(e);if(!r)return s.json({error:"Not Found",message:"Function not found"},404);if(r.allowUnauthenticated!==!0&&!s.req.header("authorization"))return s.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(r.methods&&r.methods.length>0){let h=s.req.method.toUpperCase();if(!r.methods.includes(h))return s.json({error:"Method Not Allowed",message:`This function only accepts: ${r.methods.join(", ")}`},405,{Allow:r.methods.join(", ")})}this.debug&&console.log(`Executing function: ${r.name} (${e})`);let n=null;try{["POST","PUT","PATCH"].includes(s.req.method)&&((s.req.header("content-type")||"").includes("application/json")?n=await s.req.json():n=await s.req.text())}catch{}let o=["x-molnos-token","x-molnos-service-token","x-molnos-internal"],i={};s.req.raw.headers.forEach((h,f)=>{(r.passAllHeaders||!o.includes(f.toLowerCase()))&&(i[f]=h)});let c=s.req.path,a=`/run/${e}`,u=c.startsWith(a)?c.substring(a.length):"/";u||(u="/");let l={};if(r.bindings&&r.bindings.length>0){let f=s.req.header("authorization")?.replace(/^Bearer\s+/i,"")||null,b={databases:"http://localhost:3004",storage:"http://localhost:3001",observability:"http://localhost:3005",sites:"http://localhost:3003",functions:"http://localhost:3002"};l=new oe(b,f).createBindings(r.bindings)}let d={request:{method:s.req.method,path:s.req.path,subpath:u,query:s.req.query(),headers:i,body:n},functionId:e,functionName:r.name,bindings:l};try{let b=(await import(`${vr(r.filePath).href}?t=${Date.now()}`)).default;if(typeof b!="function")return s.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:p,restore:y}=this.createConsoleInterceptor(e,r.name);Object.assign(console,p);let m;try{m=await b(d.request,d)}finally{y()}if(m&&typeof m=="object"){if(m.statusCode!==void 0&&m.body!==void 0){let O=m.statusCode||200,T=m.headers||{},v=typeof m.body=="object"?JSON.stringify(m.body):m.body;return s.body(v,O,T)}return s.json(m)}return typeof m=="string"?s.text(m):typeof m=="number"||typeof m=="boolean"?s.json({result:m}):s.json({result:m===null?null:void 0})}catch(h){return console.error("Function execution error:",h),s.json({error:"Function Execution Error",message:this.debug?h.message:"Error executing function",stack:this.debug?h.stack:void 0},500)}}catch(r){return console.error("Error processing function execution:",r),s.json({error:"Internal Server Error",message:this.debug?r.message:"Failed to process function execution"},500)}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(s=>({id:s.id,name:s.name,endpoint:s.endpoint,createdAt:new Date(s.createdAt).toISOString(),updatedAt:new Date(s.updatedAt).toISOString()}))}}createConsoleInterceptor(e,s){let r={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)},n=(o,i)=>{let c=i.map(a=>typeof a=="object"?JSON.stringify(a):String(a)).join(" ");ft({functionId:e,functionName:s,level:o,message:c,timestamp:Date.now()})};return{interceptedConsole:{log:(...o)=>{r.log(...o),n("info",o)},error:(...o)=>{r.error(...o),n("error",o)},warn:(...o)=>{r.warn(...o),n("warn",o)},info:(...o)=>{r.info(...o),n("info",o)},debug:(...o)=>{r.debug(...o),n("debug",o)}},restore:()=>{console.log=r.log,console.error=r.error,console.warn=r.warn,console.info=r.info,console.debug=r.debug}}}};async function Er(t){let e=t.dataPath||"data",s=_(e,"functions"),r=new Fe({functionsDir:t.functions?.path||s,debug:t.functions?.debug||!1});await r.start();let n=t.identityApiUrl?new ae(t.identityApiUrl):null,o=Ce(),i=t.observability?.url||"http://localhost:3005";o.on("function.log",a=>{fetch(`${i}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:`functions.${a.functionId}`,level:a.level,message:a.message,metadata:{functionId:a.functionId,functionName:a.functionName,...a.metadata}})}).catch(u=>{t.functions?.debug&&console.error("Failed to send log to observability service:",u)})});let c=new ve;return c.post("/deploy",async a=>yt(a,r,n)),c.get("/list",async a=>xt(a,r,n)),c.get("/stats",async a=>{try{let u=r.getStats();return a.json({success:!0,stats:u})}catch(u){return a.json({error:u.message},500)}}),c.get("/:functionId/config",async a=>{try{let u=a.req.param("functionId"),l=r.getFunction(u);if(!l)return a.json({error:"Function not found"},404);let d="";try{let h=await St(l.filePath,"utf8"),f="// User function code starts here",b="// User function code ends here",p=h.indexOf(f),y=h.indexOf(b);p!==-1&&y!==-1?(d=h.substring(p+f.length,y).trim().replace(/^\n+/,"").replace(/\n+$/,""),d=d.replace(/\n*export\s+default\s+handler;\s*$/,"")):d=h}catch(h){return a.json({error:"Failed to read function code",message:h.message},500)}return a.json({success:!0,function:{id:l.id,name:l.name,endpoint:l.endpoint,filePath:l.filePath,code:d,...l.methods?{methods:l.methods}:{},...l.bindings?{bindings:l.bindings}:{},...l.passAllHeaders!==void 0?{passAllHeaders:l.passAllHeaders}:{},...l.allowUnauthenticated!==void 0?{allowUnauthenticated:l.allowUnauthenticated}:{},createdAt:new Date(l.createdAt).toISOString(),updatedAt:new Date(l.updatedAt).toISOString()}})}catch(u){return a.json({error:u.message},500)}}),c.get("/:functionId",async a=>Et(a,r,n)),c.put("/:functionId",async a=>wt(a,r,n)),c.delete("/:functionId",async a=>vt(a,r,n)),c.all("/run/:functionId/*",async a=>Oe(a,r,n)),c.all("/run/:functionId",async a=>Oe(a,r,n)),dt({fetch:c.fetch,port:t.server.port||3002,hostname:t.server.host||"localhost"}),console.log(`Functions server started on ${t.server.host||"localhost"}:${t.server.port||3002}`),c}var xr=process.argv.slice(2),Rt=xr.find(t=>t.startsWith("--port=")),Rr=Rt?parseInt(Rt.split("=")[1],10):3002,Pt=ht(),Pr={molnos:{dataPath:Pt.molnos.dataPath},functions:{debug:!0},server:{port:Rr,host:Pt.server.host},identityApiUrl:process.env.IDENTITY_API_URL||"http://localhost:3000"};Er(Pr);export{Fe as FunctionsService,Er as startServer};
25
+ `}async executeFunction(t,r){try{let n=this.functions.get(t);if(!n)return r.json({error:"Not Found",message:"Function not found"},404);if(n.allowUnauthenticated!==!0&&!r.headers.authorization)return r.json({error:"Unauthorized",message:"This function requires authentication. Provide a valid Bearer token."},401);if(n.methods&&n.methods.length>0){let h=(r.req.method||"GET").toUpperCase();if(!n.methods.includes(h)){let p=n.methods.join(", "),m=r.json({error:"Method Not Allowed",message:`This function only accepts: ${p}`},405);return m.headers={...m.headers||{},allow:p},m}}let s=null;try{let h=r.req.method||"GET";["POST","PUT","PATCH"].includes(h)&&((r.headers["content-type"]||"").includes("application/json")?s=await E(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,d=`/run/${t}`,f=c.startsWith(d)?c.substring(d.length):"/";f||(f="/");let l={};if(n.bindings&&n.bindings.length>0){let p=r.headers.authorization?.replace(/^Bearer\s+/i,"")||null,m=P(),S={databases:m.services.databases.url,storage:m.services.storage.url,observability:m.services.observability.url,sites:m.services.sites.url,functions:m.services.functions.url};l=new M(S,p).createBindings(n.bindings)}let u={request:{method:r.req.method||"GET",path:c,subpath:f,query:r.query,headers:o,body:s},functionId:t,functionName:n.name,bindings:l};try{let m=(await import(`${Ht(n.filePath).href}?t=${Date.now()}`)).default;if(typeof m!="function")return r.json({error:"Invalid Function",message:"The deployed code does not export a default function"},500);let{interceptedConsole:S,restore:T}=this.createConsoleInterceptor(t,n.name);Object.assign(console,S);let g;try{g=await m(u.request,u)}finally{T()}if(g&&typeof g=="object"){if(g.statusCode!==void 0&&g.body!==void 0){let I=g.statusCode||200,C=g.headers||{};if(typeof g.body=="object"){let q=r.json(g.body,I);return Object.keys(C).length>0&&(q.headers={...q.headers||{},...C}),q}let D=r.text(g.body,I);return Object.keys(C).length>0&&(D.headers={...D.headers||{},...C}),D}return r.json(g)}return typeof g=="string"?r.text(g):typeof g=="number"||typeof g=="boolean"?r.json({result:g}):r.json({result:g===null?null:void 0})}catch(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)}}getStats(){return{totalFunctions:this.functions.size,functions:this.getFunctions().map(r=>({id:r.id,name:r.name,endpoint:r.endpoint,createdAt:new Date(r.createdAt).toISOString(),updatedAt:new Date(r.updatedAt).toISOString()}))}}createConsoleInterceptor(t,r){let n={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),debug:console.debug.bind(console)},s=(i,o)=>{let a=o.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" ");et({functionId:t,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 Mt(e){let t=e.dataPath||"data",r=j(t,"functions"),n=e.debug||!1,s=new Y({functionsDir:r,debug:n});await s.start();let i=pt(e.identityApiUrl),o=_(),a=P(),c=a.services.observability.url;o.on("function.log",u=>{fetch(`${c}/events`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({service:`functions.${u.functionId}`,level:u.level,message:u.message,metadata:{functionId:u.functionId,functionName:u.functionName,...u.metadata}})}).catch(h=>{n&&console.error("Failed to send log to observability service:",h)})});let d=new z({port:e.api.port||a.services.functions.port,host:e.api.host||a.services.functions.host,rateLimit:e.rateLimit||{enabled:!1,requestsPerMinute:0}});d.post("/deploy",async u=>it(u,s,i)),d.get("/list",async u=>lt(u,s,i)),d.get("/stats",async u=>{try{let h=s.getStats();return u.json({success:!0,stats:h})}catch(h){return u.json({error:h.message},500)}}),d.get("/:functionId/config",async u=>{try{let h=u.params.functionId,p=s.getFunction(h);if(!p)return u.json({error:"Function not found"},404);let m="";try{let S=await mt(p.filePath,"utf8"),T="// User function code starts here",g="// User function code ends here",I=S.indexOf(T),C=S.indexOf(g);I!==-1&&C!==-1?(m=S.substring(I+T.length,C).trim().replace(/^\n+/,"").replace(/\n+$/,""),m=m.replace(/\n*export\s+default\s+handler;\s*$/,"")):m=S}catch(S){return u.json({error:"Failed to read function code",message:S.message},500)}return u.json({success:!0,function:{id:p.id,name:p.name,endpoint:p.endpoint,filePath:p.filePath,code:m,...p.methods?{methods:p.methods}:{},...p.bindings?{bindings:p.bindings}:{},...p.passAllHeaders!==void 0?{passAllHeaders:p.passAllHeaders}:{},...p.allowUnauthenticated!==void 0?{allowUnauthenticated:p.allowUnauthenticated}:{},createdAt:new Date(p.createdAt).toISOString(),updatedAt:new Date(p.updatedAt).toISOString()}})}catch(h){return u.json({error:h.message},500)}}),d.get("/:functionId",async u=>dt(u,s,i)),d.put("/:functionId",async u=>ct(u,s,i)),d.delete("/:functionId",async u=>ut(u,s,i));let f=async u=>ot(u,s,i);return d.get("/run/:functionId/*",f),d.post("/run/:functionId/*",f),d.put("/run/:functionId/*",f),d.patch("/run/:functionId/*",f),d.delete("/run/:functionId/*",f),d.get("/run/:functionId",f),d.post("/run/:functionId",f),d.put("/run/:functionId",f),d.patch("/run/:functionId",f),d.delete("/run/:functionId",f),d.start()}if(import.meta.url===`file://${process.argv[1]}`){let e=P(),r=process.argv.slice(2).find(i=>i.startsWith("--port=")),n=r?parseInt(r.split("=")[1],10):e.services.functions.port,s=ht({api:{port:n}},"functions");Mt(s)}export{Y as FunctionsService,Mt as startServer};