molnos 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +89 -0
- package/README.md +66 -0
- package/dist/bin.mjs +5 -0
- package/dist/databases.mjs +2 -0
- package/dist/functions.mjs +16 -0
- package/dist/molnos_core.mjs +152 -0
- package/dist/observability.mjs +5 -0
- package/dist/sites.mjs +2 -0
- package/dist/storage.mjs +2 -0
- package/package.json +80 -0
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// MolnOS Core - See LICENSE file for copyright and license details.
|
|
2
|
+
import{createHash as tr}from"node:crypto";var re=(e,t,s)=>(r,n)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,l=!1,h;if(e[a]?(h=e[a][0][0],r.req.routeIndex=a):h=a===e.length&&n||void 0,h)try{c=await h(r,()=>i(a+1))}catch(u){if(u instanceof Error&&t)r.error=u,c=await t(u,r),l=!0;else throw u}else r.finalized===!1&&s&&(c=await s(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}};var we=Symbol();var Ee=async(e,t=Object.create(null))=>{let{all:s=!1,dot:r=!1}=t,o=(e instanceof U?e.raw.headers:e.headers).get("Content-Type");return o?.startsWith("multipart/form-data")||o?.startsWith("application/x-www-form-urlencoded")?pt(e,{all:s,dot:r}):{}};async function pt(e,t){let s=await e.formData();return s?mt(s,t):{}}function mt(e,t){let s=Object.create(null);return e.forEach((r,n)=>{t.all||n.endsWith("[]")?yt(s,n,r):s[n]=r}),t.dot&&Object.entries(s).forEach(([r,n])=>{r.includes(".")&&(gt(s,r,n),delete s[r])}),s}var yt=(e,t,s)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(s):e[t]=[e[t],s]:t.endsWith("[]")?e[t]=[s]:e[t]=s},gt=(e,t,s)=>{let r=e,n=t.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 ne=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Re=e=>{let{groups:t,path:s}=vt(e),r=ne(s);return bt(r,t)},vt=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(s,r)=>{let n=`@${r}`;return t.push([n,s]),n}),{groups:t,path:e}},bt=(e,t)=>{for(let s=t.length-1;s>=0;s--){let[r]=t[s];for(let n=e.length-1;n>=0;n--)if(e[n].includes(r)){e[n]=e[n].replace(r,t[s][1]);break}}return e},z={},Pe=(e,t)=>{if(e==="*")return"*";let s=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(s){let r=`${e}#${t}`;return z[r]||(s[2]?z[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,s[1],new RegExp(`^${s[2]}(?=/${t})`)]:[e,s[1],new RegExp(`^${s[2]}$`)]:z[r]=[e,s[1],!0]),z[r]}return null},W=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,s=>{try{return t(s)}catch{return s}})}},wt=e=>W(e,decodeURI),oe=e=>{let t=e.url,s=t.indexOf("/",t.indexOf(":")+4),r=s;for(;r<t.length;r++){let n=t.charCodeAt(r);if(n===37){let o=t.indexOf("?",r),i=t.slice(s,o===-1?void 0:o);return wt(i.includes("%25")?i.replace(/%25/g,"%2525"):i)}else if(n===63)break}return t.slice(s,r)};var xe=e=>{let t=oe(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},O=(e,t,...s)=>(s.length&&(t=O(t,...s)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),V=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),s=[],r="";return t.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)},se=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?W(e,ie):e):e,Se=(e,t,s)=>{let r;if(!s&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return se(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(r=/[%+]/.test(e),!r)return}let n={};r??=/[%+]/.test(e);let o=e.indexOf("?",8);for(;o!==-1;){let i=e.indexOf("&",o+1),a=e.indexOf("=",o);a>i&&i!==-1&&(a=-1);let c=e.slice(o+1,a===-1?i===-1?void 0:i:a);if(r&&(c=se(c)),o=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),r&&(l=se(l))),s?(n[c]&&Array.isArray(n[c])||(n[c]=[]),n[c].push(l)):n[c]??=l}return t?n[t]:n},Oe=Se,je=(e,t)=>Se(e,t,!0),ie=decodeURIComponent;var Ce=e=>W(e,ie),U=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",s=[[]]){this.raw=e,this.path=t,this.#e=s,this.#t={}}param(e){return e?this.#r(e):this.#o()}#r(e){let t=this.#e[0][this.routeIndex][1][e],s=this.#n(t);return s&&/\%/.test(s)?Ce(s):s}#o(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let s of t){let r=this.#n(this.#e[0][this.routeIndex][1][s]);r!==void 0&&(e[s]=/\%/.test(r)?Ce(r):r)}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Oe(this.url,e)}queries(e){return je(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((s,r)=>{t[r]=s}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Ee(this,e)}#s=e=>{let{bodyCache:t,raw:s}=this,r=t[e];if(r)return r;let n=Object.keys(t)[0];return n?t[n].then(o=>(n==="json"&&(o=JSON.stringify(o)),new Response(o)[e]())):t[e]=s[e]()};json(){return this.#s("text").then(e=>JSON.parse(e))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[we](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Ae={Stringify:1,BeforeStream:2,Stream:3},Et=(e,t)=>{let s=new String(e);return s.isEscaped=!0,s.callbacks=t,s};var ae=async(e,t,s,r,n)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);n?n[0]+=e:n=[e];let i=Promise.all(o.map(a=>a({phase:t,buffer:n,context:r}))).then(a=>Promise.all(a.filter(Boolean).map(c=>ae(c,t,!1,r,n))).then(()=>n[0]));return s?Et(await i,o):i};var Rt="text/plain; charset=UTF-8",ce=(e,t)=>({"Content-Type":e,...t}),Le=class{#t;#e;env={};#r;finalized=!1;error;#o;#n;#s;#h;#c;#l;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new U(this.#t,this.#f,this.#u),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(e){if(this.#s&&e){e=new Response(e.body,e);for(let[t,s]of this.#s.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#s.headers.getSetCookie();e.headers.delete("set-cookie");for(let n of r)e.headers.append("set-cookie",n)}else e.headers.set(t,s)}this.#s=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#h=e;getLayout=()=>this.#h;setRenderer=e=>{this.#c=e};header=(e,t,s)=>{this.finalized&&(this.#s=new Response(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#a??=new Headers;t===void 0?r.delete(e):s?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#o=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,s){let r=this.#s?new Headers(this.#s.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let o=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of o)i.toLowerCase()==="set-cookie"?r.append(i,a):r.set(i,a)}if(s)for(let[o,i]of Object.entries(s))if(typeof i=="string")r.set(o,i);else{r.delete(o);for(let a of i)r.append(o,a)}let n=typeof t=="number"?t:t?.status??this.#o;return new Response(e,{status:n,headers:r})}newResponse=(...e)=>this.#i(...e);body=(e,t,s)=>this.#i(e,t,s);text=(e,t,s)=>!this.#a&&!this.#o&&!t&&!s&&!this.finalized?new Response(e):this.#i(e,t,ce(Rt,s));json=(e,t,s)=>this.#i(JSON.stringify(e),t,ce("application/json",s));html=(e,t,s)=>{let r=n=>this.#i(n,t,ce("text/html; charset=UTF-8",s));return typeof e=="object"?ae(e,Ae.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let s=String(e);return this.header("Location",/[^\x00-\xFF]/.test(s)?encodeURI(s):s),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))};var d="ALL",Te="all",He=["get","post","put","delete","options","patch"],G="Can not add a route since the matcher is already built.",K=class extends Error{};var Ie="__COMPOSED_HANDLER";var Pt=e=>e.text("404 Not Found",404),ke=(e,t)=>{if("getResponse"in e){let s=e.getResponse();return t.newResponse(s.body,s)}return console.error(e),t.text("Internal Server Error",500)},De=class qe{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...He,Te].forEach(o=>{this[o]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#o(o,this.#t,i),a.forEach(c=>{this.#o(o,this.#t,c)}),this)}),this.on=(o,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[o].flat())a.map(h=>{this.#o(l.toUpperCase(),this.#t,h)})}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(a=>{this.#o(d,this.#t,a)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??oe:xe}#e(){let t=new qe({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Pt;errorHandler=ke;route(t,s){let r=this.basePath(t);return s.routes.map(n=>{let o;s.errorHandler===ke?o=n.handler:(o=async(i,a)=>(await re([],s.errorHandler)(i,()=>n.handler(i,a))).res,o[Ie]=n.handler),r.#o(n.method,n.path,o)}),this}basePath(t){let s=this.#e();return s._basePath=O(this._basePath,t),s}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,s,r){let n,o;r&&(typeof r=="function"?o=r:(o=r.optionHandler,r.replaceRequest===!1?n=c=>c:n=r.replaceRequest));let i=o?c=>{let l=o(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};n||=(()=>{let c=O(this._basePath,t),l=c==="/"?0:c.length;return h=>{let u=new URL(h.url);return u.pathname=u.pathname.slice(l)||"/",new Request(u,h)}})();let a=async(c,l)=>{let h=await s(n(c.req.raw),...i(c));if(h)return h;await l()};return this.#o(d,O(t,"*"),a),this}#o(t,s,r){t=t.toUpperCase(),s=O(this._basePath,s);let n={basePath:this._basePath,path:s,method:t,handler:r};this.router.add(t,s,[r,n]),this.routes.push(n)}#n(t,s){if(t instanceof Error)return this.errorHandler(t,s);throw t}#s(t,s,r,n){if(n==="HEAD")return(async()=>new Response(null,await this.#s(t,s,r,"GET")))();let o=this.getPath(t,{env:r}),i=this.router.match(n,o),a=new Le(t,{path:o,matchResult:i,env:r,executionCtx:s,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(h){return this.#n(h,a)}return l instanceof Promise?l.then(h=>h||(a.finalized?a.res:this.#r(a))).catch(h=>this.#n(h,a)):l??this.#r(a)}let c=re(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,a)}})()}fetch=(t,...s)=>this.#s(t,s[1],s[0],t.method);request=(t,s,r,n)=>t instanceof Request?this.fetch(s?new Request(t,s):t,r,n):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${O("/",t)}`,s),r,n));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#s(t.request,t,void 0,t.request.method))})}};var Q=[];function le(e,t){let s=this.buildAllMatchers(),r=((n,o)=>{let i=s[n]||s[d],a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],Q];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=r,r(e,t)}var J="[^/]+",D=".*",q="(?:|/.*)",j=Symbol(),xt=new Set(".\\+*[^]$()");function St(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===D||e===q?1:t===D||t===q?-1:e===J?1:t===J?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Me=class he{#t;#e;#r=Object.create(null);insert(t,s,r,n,o){if(t.length===0){if(this.#t!==void 0)throw j;if(o)return;this.#t=s;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",D]:["","",J]:i==="/*"?["","",q]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let h=c[1],u=c[2]||J;if(h&&c[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw j;if(l=this.#r[u],!l){if(Object.keys(this.#r).some(f=>f!==D&&f!==q))throw j;if(o)return;l=this.#r[u]=new he,h!==""&&(l.#e=n.varIndex++)}!o&&h!==""&&r.push([h,l.#e])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(h=>h.length>1&&h!==D&&h!==q))throw j;if(o)return;l=this.#r[i]=new he}l.insert(a,s,r,n,o)}buildRegExpStr(){let s=Object.keys(this.#r).sort(St).map(r=>{let n=this.#r[r];return(typeof n.#e=="number"?`(${r})@${n.#e}`:xt.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 Fe=class{#t={varIndex:0};#e=new Me;insert(e,t,s){let r=[],n=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let o=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,n[i][1]);break}}return this.#e.insert(o,t,r,this.#t,s),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,s=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,i)=>o!==void 0?(s[++t]=Number(o),"$()"):(i!==void 0&&(r[Number(i)]=++t),"")),[new RegExp(`^${e}`),s,r]}};var Ot=[/^$/,[],Object.create(null)],$e=Object.create(null);function _e(e){return $e[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,s)=>s?`\\${s}`:"(?:|/.*)")}$`)}function jt(){$e=Object.create(null)}function Ct(e){let t=new Fe,s=[];if(e.length===0)return Ot;let r=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,h],[u,f])=>l?1:u?-1:h.length-f.length),n=Object.create(null);for(let l=0,h=-1,u=r.length;l<u;l++){let[f,m,g]=r[l];f?n[m]=[g.map(([y])=>[y,Object.create(null)]),Q]:h++;let p;try{p=t.insert(m,h,f)}catch(y){throw y===j?new K(m):y}f||(s[h]=g.map(([y,b])=>{let v=Object.create(null);for(b-=1;b>=0;b--){let[B,w]=p[b];v[B]=w}return[y,v]}))}let[o,i,a]=t.buildRegExp();for(let l=0,h=s.length;l<h;l++)for(let u=0,f=s[l].length;u<f;u++){let m=s[l][u]?.[1];if(!m)continue;let g=Object.keys(m);for(let p=0,y=g.length;p<y;p++)m[g[p]]=a[m[g[p]]]}let c=[];for(let l in i)c[l]=s[i[l]];return[o,c,n]}function L(e,t){if(e){for(let s of Object.keys(e).sort((r,n)=>n.length-r.length))if(_e(s).test(t))return[...e[s]]}}var X=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[d]:Object.create(null)},this.#e={[d]:Object.create(null)}}add(e,t,s){let r=this.#t,n=this.#e;if(!r||!n)throw new Error(G);r[e]||[r,n].forEach(a=>{a[e]=Object.create(null),Object.keys(a[d]).forEach(c=>{a[e][c]=[...a[d][c]]})}),t==="/*"&&(t="*");let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=_e(t);e===d?Object.keys(r).forEach(c=>{r[c][t]||=L(r[c],t)||L(r[d],t)||[]}):r[e][t]||=L(r[e],t)||L(r[d],t)||[],Object.keys(r).forEach(c=>{(e===d||e===c)&&Object.keys(r[c]).forEach(l=>{a.test(l)&&r[c][l].push([s,o])})}),Object.keys(n).forEach(c=>{(e===d||e===c)&&Object.keys(n[c]).forEach(l=>a.test(l)&&n[c][l].push([s,o]))});return}let i=V(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(n).forEach(h=>{(e===d||e===h)&&(n[h][l]||=[...L(r[h],l)||L(r[d],l)||[]],n[h][l].push([s,o-c+a+1]))})}}match=le;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,jt(),e}#r(e){let t=[],s=e===d;return[this.#t,this.#e].forEach(r=>{let n=r[e]?Object.keys(r[e]).map(o=>[o,r[e][o]]):[];n.length!==0?(s||=!0,t.push(...n)):e!==d&&t.push(...Object.keys(r[d]).map(o=>[o,r[d][o]]))}),s?Ct(t):null}};var ue=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,s){if(!this.#e)throw new Error(G);this.#e.push([e,t,s])}match(e,t){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 a=s[o];try{for(let c=0,l=r.length;c<l;c++)a.add(...r[c]);i=a.match(e,t)}catch(c){if(c instanceof K)continue;throw c}this.match=a.match.bind(a),this.#t=[a],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 M=Object.create(null),Ne=class Be{#t;#e;#r;#o=0;#n=M;constructor(t,s,r){if(this.#e=r||Object.create(null),this.#t=[],t&&s){let n=Object.create(null);n[t]={handler:s,possibleKeys:[],score:0},this.#t=[n]}this.#r=[]}insert(t,s,r){this.#o=++this.#o;let n=this,o=Re(s),i=[];for(let a=0,c=o.length;a<c;a++){let l=o[a],h=o[a+1],u=Pe(l,h),f=Array.isArray(u)?u[0]:l;if(f in n.#e){n=n.#e[f],u&&i.push(u[1]);continue}n.#e[f]=new Be,u&&(n.#r.push(u),i.push(u[1])),n=n.#e[f]}return n.#t.push({[t]:{handler:r,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#o}}),n}#s(t,s,r,n){let o=[];for(let i=0,a=t.#t.length;i<a;i++){let c=t.#t[i],l=c[s]||c[d],h={};if(l!==void 0&&(l.params=Object.create(null),o.push(l),r!==M||n&&n!==M))for(let u=0,f=l.possibleKeys.length;u<f;u++){let m=l.possibleKeys[u],g=h[l.score];l.params[m]=n?.[m]&&!g?n[m]:r[m]??n?.[m],h[l.score]=!0}}return o}search(t,s){let r=[];this.#n=M;let o=[this],i=ne(s),a=[];for(let c=0,l=i.length;c<l;c++){let h=i[c],u=c===l-1,f=[];for(let m=0,g=o.length;m<g;m++){let p=o[m],y=p.#e[h];y&&(y.#n=p.#n,u?(y.#e["*"]&&r.push(...this.#s(y.#e["*"],t,p.#n)),r.push(...this.#s(y,t,p.#n))):f.push(y));for(let b=0,v=p.#r.length;b<v;b++){let B=p.#r[b],w=p.#n===M?{}:{...p.#n};if(B==="*"){let x=p.#e["*"];x&&(r.push(...this.#s(x,t,p.#n)),x.#n=w,f.push(x));continue}let[ut,be,k]=B;if(!h&&!(k instanceof RegExp))continue;let P=p.#e[ut],ft=i.slice(c).join("/");if(k instanceof RegExp){let x=k.exec(ft);if(x){if(w[be]=x[0],r.push(...this.#s(P,t,p.#n,w)),Object.keys(P.#e).length){P.#n=w;let dt=x[0].match(/\//)?.length??0;(a[dt]||=[]).push(P)}continue}}(k===!0||k.test(h))&&(w[be]=h,u?(r.push(...this.#s(P,t,w,p.#n)),P.#e["*"]&&r.push(...this.#s(P.#e["*"],t,w,p.#n))):(P.#n=w,f.push(P)))}}o=f.concat(a.shift()??[])}return r.length>1&&r.sort((c,l)=>c.score-l.score),[r.map(({handler:c,params:l})=>[c,l])]}};var fe=class{name="TrieRouter";#t;constructor(){this.#t=new Ne}add(e,t,s){let r=V(t);if(r){for(let n=0,o=r.length;n<o;n++)this.#t.insert(e,r[n],s);return}this.#t.insert(e,t,s)}match(e,t){return this.#t.search(e,t)}};var de=class extends De{constructor(e={}){super(e),this.router=e.router??new ue({routers:[new X,new fe]})}};import{join as N}from"node:path";import{promises as S}from"node:fs";import{createServer as At}from"http";import{Http2ServerRequest as Lt}from"http2";import{Http2ServerRequest as pe}from"http2";import{Readable as Ue}from"stream";import Bt from"crypto";var C=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Tt=e=>e instanceof C?e:new C(e.message,{cause:e}),Ht=global.Request,F=class extends Ht{constructor(e,t){typeof e=="object"&&I in e&&(e=e[I]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},It=e=>{let t=[],s=e.rawHeaders;for(let r=0;r<s.length;r+=2){let{[r]:n,[r+1]:o}=s;n.charCodeAt(0)!==58&&t.push([n,o])}return new Headers(t)},We=Symbol("wrapBodyStream"),kt=(e,t,s,r,n)=>{let o={method:e,headers:s,signal:n.signal};if(e==="TRACE"){o.method="GET";let i=new F(t,o);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(i){i.enqueue(r.rawBody),i.close()}});else if(r[We]){let i;o.body=new ReadableStream({async pull(a){try{i||=Ue.toWeb(r).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else o.body=Ue.toWeb(r);return new F(t,o)},I=Symbol("getRequestCache"),Dt=Symbol("requestCache"),Y=Symbol("incomingKey"),Z=Symbol("urlKey"),qt=Symbol("headersKey"),H=Symbol("abortControllerKey"),Mt=Symbol("getAbortController"),ee={get method(){return this[Y].method||"GET"},get url(){return this[Z]},get headers(){return this[qt]||=It(this[Y])},[Mt](){return this[I](),this[H]},[I](){return this[H]||=new AbortController,this[Dt]||=kt(this.method,this[Z],this.headers,this[Y],this[H])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(ee,e,{get(){return this[I]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(ee,e,{value:function(){return this[I]()[e]()}})});Object.setPrototypeOf(ee,F.prototype);var Ft=(e,t)=>{let s=Object.create(ee);s[Y]=e;let r=e.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(e instanceof pe)throw new C("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(r);s[Z]=a.href}catch(a){throw new C("Invalid absolute URL",{cause:a})}return s}let n=(e instanceof pe?e.authority:e.headers.host)||t;if(!n)throw new C("Missing host header");let o;if(e instanceof pe){if(o=e.scheme,!(o==="http"||o==="https"))throw new C("Unsupported scheme")}else o=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${o}://${n}${r}`);if(i.hostname.length!==n.length&&i.hostname!==n.replace(/:\d+$/,""))throw new C("Invalid host header");return s[Z]=i.href,s},ze=Symbol("responseCache"),T=Symbol("getResponseCache"),A=Symbol("cache"),ye=global.Response,$=class Ve{#t;#e;[T](){return delete this[A],this[ze]||=new ye(this.#t,this.#e)}constructor(t,s){let r;if(this.#t=t,s instanceof Ve){let n=s[ze];if(n){this.#e=n,this[T]();return}else this.#e=s.#e,r=new Headers(s.#e.headers)}else this.#e=s;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(r||=s?.headers||{"content-type":"text/plain; charset=UTF-8"},this[A]=[s?.status||200,t,r])}get headers(){let t=this[A];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2])),t[2]):this[T]().headers}get status(){return this[A]?.[0]??this[T]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty($.prototype,e,{get(){return this[T]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty($.prototype,e,{value:function(){return this[T]()[e]()}})});Object.setPrototypeOf($,ye);Object.setPrototypeOf($.prototype,ye.prototype);async function $t(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Ge(e,t,s){let r=a=>{e.cancel(a).catch(()=>{})};return t.on("close",r),t.on("error",r),(s??e.read()).then(i,n),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function n(a){a&&t.destroy(a)}function o(){e.read().then(i,n)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",o);else return e.read().then(i,n)}catch(l){n(l)}}}function _t(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Ge(e.getReader(),t)}var Ke=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[r,n]of e)r==="set-cookie"?s.push(n):t[r]=n;return s.length>0&&(t["set-cookie"]=s),t["content-type"]??="text/plain; charset=UTF-8",t},Nt="x-hono-already-sent",Ut=global.fetch;typeof global.crypto>"u"&&(global.crypto=Bt);global.fetch=(e,t)=>(t={compress:!1,...t},Ut(e,t));var ge=Symbol("outgoingEnded"),zt=()=>new Response(null,{status:400}),Qe=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),me=(e,t)=>{let s=e instanceof Error?e:new Error("unknown error",{cause:e});s.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${s.message}`),t.destroy(s))},Je=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Xe=async(e,t)=>{let[s,r,n]=e[A];n instanceof Headers&&(n=Ke(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),t.writeHead(s,n),typeof r=="string"||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(Je(t),await _t(r,t)?.catch(o=>me(o,t))),t[ge]?.()},Wt=e=>typeof e.then=="function",Vt=async(e,t,s={})=>{if(Wt(e))if(s.errorHandler)try{e=await e}catch(n){let o=await s.errorHandler(n);if(!o)return;e=o}else e=await e.catch(Qe);if(A in e)return Xe(e,t);let r=Ke(e.headers);if(e.body){let n=e.body.getReader(),o=[],i=!1,a;if(r["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=n.read();let h=await $t(a).catch(u=>{console.error(u),i=!0});if(!h){if(l===1){await new Promise(u=>setTimeout(u)),c=3;continue}break}if(a=void 0,h.value&&o.push(h.value),h.done){i=!0;break}}i&&!("content-length"in r)&&(r["content-length"]=o.reduce((l,h)=>l+h.length,0))}t.writeHead(e.status,r),o.forEach(c=>{t.write(c)}),i?t.end():(o.length===0&&Je(t),await Ge(n,t,a))}else r[Nt]||(t.writeHead(e.status,r),t.end());t[ge]?.()},Gt=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==F&&(Object.defineProperty(global,"Request",{value:F}),Object.defineProperty(global,"Response",{value:$})),async(r,n)=>{let o,i;try{i=Ft(r,t.hostname);let a=!s||r.method==="GET"||r.method==="HEAD";if(a||(r[We]=!0,r.on("end",()=>{a=!0}),r instanceof Lt&&(n[ge]=()=>{a||setTimeout(()=>{a||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.")),a||setTimeout(()=>{a||setTimeout(()=>{r.destroy()})})}),o=e(i,{incoming:r,outgoing:n}),A in o)return Xe(o,n)}catch(a){if(o)return me(a,n);if(t.errorHandler){if(o=await t.errorHandler(i?a:Tt(a)),!o)return}else i?o=Qe(a):o=zt()}try{return await Vt(o,n,t)}catch(a){return me(a,n)}}},Kt=e=>{let t=e.fetch,s=Gt(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||At)(e.serverOptions||{},s)},Ye=(e,t)=>{let s=Kt(e);return s.listen(e?.port??3e3,e.hostname,()=>{let r=s.address();t&&t(r)}),s};import{readFileSync as Qt,existsSync as Jt}from"node:fs";function Ze(){let e=process.env.MOLNOS_RUNTIME_CONFIG;if(!e||!Jt(e))return{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}};try{let t=Qt(e,"utf-8");return JSON.parse(t)}catch(t){return console.error("[loadRuntimeConfig] Failed to load runtime config:",t),{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}}}}var _=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(e.properties,t),n=this.compileErrors(s,r),o=this.isSuccessful(s,n);return{errors:n,success:o}}compileErrors(e,t){let s=e.filter(r=>r.success===!1);return[...t,...s].flatMap(r=>r)}isSuccessful(e,t){return e.every(s=>s.success===!0)&&t.length===0}validate(e,t,s=[],r=[]){let n=e?.additionalProperties??!0,o=e?.required||[];r=this.checkForRequiredKeysErrors(o,t,r),r=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),r,n);for(let i in e){let a=o.includes(i)&&i!=="required",c=e[i],l=t[i],h=c.additionalProperties??!0;a&&(r=this.checkForRequiredKeysErrors(c.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(i,l,c,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(c),r,h),this.handleNestedObject(l,c,s,r))}return{results:s,errors:r}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,s){if(!this.areRequiredKeysPresent(e,t)){let r=t?Object.keys(t):[],n=this.findNonOverlappingElements(e,r),o=n.length>0?`Missing the required key: '${n.join(", ")}'!`:`Missing values for required keys: '${r.filter(i=>!t[i]).join(", ")}'!`;s.push({key:"",value:t,success:!1,error:o})}return s}checkForDisallowedProperties(e,t,s,r){if(!r){let n=this.findNonOverlappingElements(e,t);n.length>0&&s.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${n.join(", ")}'!`})}return s}handleValidation(e,t,s,r){this.updatePropertyPath(e);let n=this.validateProperty(this.propertyPath,s,t);r.push(...n);let o=(a,c)=>{a.forEach(l=>{let h=this.validateProperty(this.propertyPath,c.items,l);r.push(...h)}),this.updatePropertyPath()},i=a=>{let c=Object.keys(a),l=this.propertyPath;c.forEach(h=>{if(this.updatePropertyPath(h,l),this.isArray(a[h])&&s[h]?.items!=null)o(a[h],s[h]);else{let u=this.validateProperty(this.propertyPath,s[h],a[h]);r.push(...u)}})};this.isArray(t)&&s.items!=null?o(t,s):this.isObject(t)?i(t):this.updatePropertyPath()}handleNestedObject(e,t,s,r){if(this.isObject(e)){let n=this.getNestedObjects(e);for(let o of n){let i=t[o],a=e[o];i&&typeof a=="object"&&this.validate(i,a,s,r)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(s=>!t.includes(s))}areRequiredKeysPresent(e,t=[]){return e.every(s=>Object.keys(t).includes(s)?this.isDefined(t[s]):!1)}validateProperty(e,t,s){return this.validateInput(t,s).map(n=>{let{success:o,error:i}=n;return{key:e,value:s,success:o,error:i??""}})}validateInput(e,t){if(e){let s=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],r=[];for(let n of s)n.condition()&&!n.validator()&&r.push({success:!1,error:n.error});return r}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(s=>{switch(s){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let s in e){let r=e[s];t.properties.required.push(s),Array.isArray(r)?t.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?t.properties[s]=this.generateNestedObjectSchema(r):t.properties[s]=this.generatePropertySchema(r)}return t}generateArraySchema(e){let t={type:"array"},s=e.filter(r=>r);if(s.length>0){let r=s[0];s.every(o=>typeof o==typeof r)?typeof r=="object"&&!Array.isArray(r)?t.items=this.generateNestedObjectSchema(r):t.items=this.generatePropertySchema(r):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let s in e){let r=e[s];t.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?t[s]=this.generateNestedObjectSchema(r):t[s]=this.generatePropertySchema(r)}return t}generatePropertySchema(e){let t=typeof e,s={type:t};return t==="string"&&(s.minLength=1),s}};async function te(e){try{return await e.req.json()}catch{return{}}}function E(e,t="An error occurred"){let s=e?.message||e||t,r=e?.cause?.statusCode||e?.statusCode||400;return{message:s,status:r}}function et(e,t,s={}){let r=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let i=new Error("Unauthorized: User or roles missing");throw i.cause={statusCode:403},i}let n=e.roles.flatMap(i=>i?.policies?.flatMap(a=>(a?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(i=>n.includes(i)||n.includes("*")?!0:n.some(a=>{if(a.endsWith(".*")){let c=a.slice(0,-2);return i.startsWith(`${c}.`)}return!1}))){let i=new Error("Unauthorized");throw i.cause={statusCode:403},i}return!0}function tt(e,t,s,r,n){let o=e.find(c=>c.service===t);if(!o){let c=new Error(`Function bindings do not include access to service: ${t}`);throw c.cause={statusCode:403},c}if(!o.permissions||o.permissions.length===0)return;for(let c of o.permissions)if(!(c.resource&&c.resource!==s)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(r)){if(c.targets&&c.targets.length>0){if(!n)return;if(!c.targets.includes(n))continue}return}}let i=n?`:${n}`:"",a=new Error(`Function bindings do not allow: ${t}.${s}.${r}${i}`);throw a.cause={statusCode:403},a}async function R(e,t,s,r,n,o,i){if(!t)return null;let a=e.get("user");if(!a){let l=e.req.header("authorization");if(!l){let u=new Error("Unauthorized: No authentication provided");throw u.cause={statusCode:401},u}let h=l.replace(/^Bearer\s+/i,"");if(a=await t.getUserFromToken(h),!a){let u=new Error("Unauthorized: Invalid token");throw u.cause={statusCode:401},u}}et(a,s,{});let c=e.req.header("x-function-bindings");if(c)try{let l=JSON.parse(c);tt(l,r,n,o,i)}catch(l){if(l.cause?.statusCode===403)throw l;let h=new Error("Invalid function bindings header");throw h.cause={statusCode:400},h}return a}var rt={properties:{service:{type:"string",minLength:1},level:{type:"string",enum:["info","warn","error","debug"]},message:{type:"string",minLength:1},metadata:{type:"object"}},required:["service","level","message"],additionalProperties:!1};var Yt=new _;async function st(e,t,s){try{let r=await te(e),n=Yt.test(rt,r);if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);await R(e,s,"observability.event.create","observability","event","create");let{service:o,level:i,message:a,metadata:c}=r;if(!o)return e.json({error:"service is required"},400);if(!i)return e.json({error:"level is required"},400);if(!["info","warn","error","debug"].includes(i))return e.json({error:"level must be one of: info, warn, error, debug"},400);if(!a)return e.json({error:"message is required"},400);let l=await t.log({service:o,level:i,message:a,metadata:c});return e.json({success:!0,event:l},201)}catch(r){let{message:n,status:o}=E(r,"Error logging event");return e.json({error:n},o)}}async function nt(e,t,s){try{await R(e,s,"observability.event.read","observability","event","read");let r=e.req.query("startTime"),n=r?parseInt(r,10):void 0,o=e.req.query("endTime"),i=o?parseInt(o,10):void 0,a=e.req.query("service")||void 0,c=e.req.query("level")||void 0,l=e.req.query("search")||void 0,h=e.req.query("limit"),u=h?parseInt(h,10):1e3,f=e.req.query("offset"),m=f?parseInt(f,10):0,g=await t.query({startTime:n,endTime:i,service:a,level:c,search:l,limit:u,offset:m});return e.json({success:!0,count:g.length,events:g},200)}catch(r){let{message:n,status:o}=E(r,"Error querying events");return e.json({error:n},o)}}async function ot(e,t,s){try{await R(e,s,"observability.stats.read","observability","stats","read");let r=await t.getStats();return e.json({success:!0,stats:r},200)}catch(r){let{message:n,status:o}=E(r,"Error getting statistics");return e.json({error:n},o)}}var it={properties:{olderThanDays:{type:"number",minimum:1}},required:["olderThanDays"],additionalProperties:!1};var er=new _;async function at(e,t,s){try{let r=await te(e),n=er.test(it,r);if(!n.success)return e.json({error:"Invalid input",details:n.errors},400);await R(e,s,"observability.event.delete","observability","event","delete");let{olderThanDays:o}=r;if(!o)return e.json({error:"olderThanDays is required"},400);let i=await t.deleteOldLogs(o);return e.json({success:!0,deletedCount:i},200)}catch(r){let{message:n,status:o}=E(r,"Error cleaning up logs");return e.json({error:n},o)}}async function ct(e,t,s){try{return await R(e,s,"observability.buffer.write","observability","buffer","write"),await t.flush(),e.json({success:!0},200)}catch(r){let{message:n,status:o}=E(r,"Error flushing buffer");return e.json({error:n},o)}}var ve=class{logDir;currentLogFile;writeBuffer=[];bufferSize;flushInterval=null;constructor(t){this.logDir=t.path||"observability-data",this.bufferSize=t.bufferSize||100,this.currentLogFile=this.getLogFileName()}async start(){await S.mkdir(this.logDir,{recursive:!0}),this.flushInterval=setInterval(()=>{this.writeBuffer.length>0&&this.flush().catch(t=>console.error("Failed to flush log buffer:",t))},5e3)}async stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),await this.flush()}getLogFileName(){let t=new Date().toISOString().split("T")[0];return N(this.logDir,`logs-${t}.ndjson`)}async log(t){let s={id:this.generateId(),timestamp:Date.now(),service:t.service,level:t.level,message:t.message,metadata:t.metadata};return this.writeBuffer.push(s),this.writeBuffer.length>=this.bufferSize&&await this.flush(),s}async flush(){if(this.writeBuffer.length===0)return;let t=this.getLogFileName(),s=[...this.writeBuffer];this.writeBuffer=[],t!==this.currentLogFile&&(this.currentLogFile=t);let r=`${s.map(n=>JSON.stringify(n)).join(`
|
|
3
|
+
`)}
|
|
4
|
+
`;await S.appendFile(this.currentLogFile,r,"utf8")}generateId(){return tr("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").substring(0,16)}async query(t={}){let{startTime:s,endTime:r,service:n,level:o,search:i,limit:a=1e3,offset:c=0}=t,l=await this.getLogFilesInRange(s,r),h=i?.toLowerCase(),u=[],f=0;for(let m of l){let g=N(this.logDir,m);try{let y=(await S.readFile(g,"utf8")).trim().split(`
|
|
5
|
+
`);for(let b of y)if(b)try{let v=JSON.parse(b);if(s&&v.timestamp<s||r&&v.timestamp>r||n&&!v.service.startsWith(n)||o&&v.level!==o||h&&!v.message?.toLowerCase().includes(h)&&!v.service?.toLowerCase().includes(h))continue;if(f<c){f++;continue}if(u.push(v),u.length>=a)return u}catch{}}catch{}}return u}async getLogFilesInRange(t,s){try{let n=(await S.readdir(this.logDir)).filter(i=>i.startsWith("logs-")&&i.endsWith(".ndjson"));return!t&&!s?n.sort().reverse():n.filter(i=>{let a=i.replace("logs-","").replace(".ndjson",""),c=new Date(a).getTime();return!(t&&c<t-864e5||s&&c>s+864e5)}).sort().reverse()}catch{return[]}}async getStats(){try{let s=(await S.readdir(this.logDir)).filter(n=>n.startsWith("logs-")&&n.endsWith(".ndjson")),r=await Promise.all(s.map(async n=>{let o=N(this.logDir,n),i=await S.stat(o);return{name:n,size:i.size,date:n.replace("logs-","").replace(".ndjson","")}}));return{totalLogFiles:s.length,logFiles:r.sort((n,o)=>o.date.localeCompare(n.date))}}catch{return{totalLogFiles:0,logFiles:[]}}}async deleteOldLogs(t){let s=Date.now()-t*864e5,n=(await S.readdir(this.logDir)).filter(i=>i.startsWith("logs-")&&i.endsWith(".ndjson")),o=0;for(let i of n){let a=i.replace("logs-","").replace(".ndjson","");if(new Date(a).getTime()<s){let l=N(this.logDir,i);await S.unlink(l),o++}}return o}};async function rr(e){let t=e.dataPath||"data",s=N(t,"observability"),r=new ve({path:e.observability?.path||s,bufferSize:e.observability?.bufferSize||100});await r.start();let n=e.identityService||null,o=new de;return o.post("/events",async i=>st(i,r,n)),o.get("/events",async i=>nt(i,r,n)),o.get("/stats",async i=>ot(i,r,n)),o.delete("/events/cleanup",async i=>at(i,r,n)),o.post("/flush",async i=>ct(i,r,n)),Ye({fetch:o.fetch,port:e.server.port||3005,hostname:e.server.host||"localhost"}),console.log(`Observability server started on ${e.server.host||"localhost"}:${e.server.port||3005}`),{server:o,observability:r}}var sr=process.argv.slice(2),lt=sr.find(e=>e.startsWith("--port=")),nr=lt?parseInt(lt.split("=")[1],10):3005,ht=Ze(),or={molnos:{dataPath:ht.molnos.dataPath},observability:{},server:{port:nr,host:ht.server.host}};rr(or);export{rr as startServer};
|
package/dist/sites.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// MolnOS Core - See LICENSE file for copyright and license details.
|
|
2
|
+
import{dirname as fr,join as E}from"node:path";import{existsSync as dr,rmSync as ae}from"node:fs";import{isAbsolute as pr,normalize as mr}from"node:path";var ie=(e,t,s)=>(r,o)=>{let n=-1;return a(0);async function a(i){if(i<=n)throw new Error("next() called multiple times");n=i;let c,l=!1,h;if(e[i]?(h=e[i][0][0],r.req.routeIndex=i):h=i===e.length&&o||void 0,h)try{c=await h(r,()=>a(i+1))}catch(u){if(u instanceof Error&&t)r.error=u,c=await t(u,r),l=!0;else throw u}else r.finalized===!1&&s&&(c=await s(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}};var Oe=Symbol();var Ae=async(e,t=Object.create(null))=>{let{all:s=!1,dot:r=!1}=t,n=(e instanceof z?e.raw.headers:e.headers).get("Content-Type");return n?.startsWith("multipart/form-data")||n?.startsWith("application/x-www-form-urlencoded")?St(e,{all:s,dot:r}):{}};async function St(e,t){let s=await e.formData();return s?Ct(s,t):{}}function Ct(e,t){let s=Object.create(null);return e.forEach((r,o)=>{t.all||o.endsWith("[]")?Ot(s,o,r):s[o]=r}),t.dot&&Object.entries(s).forEach(([r,o])=>{r.includes(".")&&(At(s,r,o),delete s[r])}),s}var Ot=(e,t,s)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(s):e[t]=[e[t],s]:t.endsWith("[]")?e[t]=[s]:e[t]=s},At=(e,t,s)=>{let r=e,o=t.split(".");o.forEach((n,a)=>{a===o.length-1?r[n]=s:((!r[n]||typeof r[n]!="object"||Array.isArray(r[n])||r[n]instanceof File)&&(r[n]=Object.create(null)),r=r[n])})};var le=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Ie=e=>{let{groups:t,path:s}=It(e),r=le(s);return Tt(r,t)},It=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(s,r)=>{let o=`@${r}`;return t.push([o,s]),o}),{groups:t,path:e}},Tt=(e,t)=>{for(let s=t.length-1;s>=0;s--){let[r]=t[s];for(let o=e.length-1;o>=0;o--)if(e[o].includes(r)){e[o]=e[o].replace(r,t[s][1]);break}}return e},V={},Te=(e,t)=>{if(e==="*")return"*";let s=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(s){let r=`${e}#${t}`;return V[r]||(s[2]?V[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,s[1],new RegExp(`^${s[2]}(?=/${t})`)]:[e,s[1],new RegExp(`^${s[2]}$`)]:V[r]=[e,s[1],!0]),V[r]}return null},W=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,s=>{try{return t(s)}catch{return s}})}},Ht=e=>W(e,decodeURI),he=e=>{let t=e.url,s=t.indexOf("/",t.indexOf(":")+4),r=s;for(;r<t.length;r++){let o=t.charCodeAt(r);if(o===37){let n=t.indexOf("?",r),a=t.slice(s,n===-1?void 0:n);return Ht(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(o===63)break}return t.slice(s,r)};var He=e=>{let t=he(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},j=(e,t,...s)=>(s.length&&(t=j(t,...s)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),G=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),s=[],r="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))r+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){s.length===0&&r===""?s.push("/"):s.push(r);let n=o.replace("?","");r+="/"+n,s.push(r)}else r+="/"+o}),s.filter((o,n,a)=>a.indexOf(o)===n)},ce=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?W(e,ue):e):e,Me=(e,t,s)=>{let r;if(!s&&t&&!/[%+]/.test(t)){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let i=e.charCodeAt(a+t.length+1);if(i===61){let c=a+t.length+2,l=e.indexOf("&",c);return ce(e.slice(c,l===-1?void 0:l))}else if(i==38||isNaN(i))return"";a=e.indexOf(`&${t}`,a+1)}if(r=/[%+]/.test(e),!r)return}let o={};r??=/[%+]/.test(e);let n=e.indexOf("?",8);for(;n!==-1;){let a=e.indexOf("&",n+1),i=e.indexOf("=",n);i>a&&a!==-1&&(i=-1);let c=e.slice(n+1,i===-1?a===-1?void 0:a:i);if(r&&(c=ce(c)),n=a,c==="")continue;let l;i===-1?l="":(l=e.slice(i+1,a===-1?void 0:a),r&&(l=ce(l))),s?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},ke=Me,$e=(e,t)=>Me(e,t,!0),ue=decodeURIComponent;var _e=e=>W(e,ue),z=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",s=[[]]){this.raw=e,this.path=t,this.#e=s,this.#t={}}param(e){return e?this.#r(e):this.#n()}#r(e){let t=this.#e[0][this.routeIndex][1][e],s=this.#o(t);return s&&/\%/.test(s)?_e(s):s}#n(){let e={},t=Object.keys(this.#e[0][this.routeIndex][1]);for(let s of t){let r=this.#o(this.#e[0][this.routeIndex][1][s]);r!==void 0&&(e[s]=/\%/.test(r)?_e(r):r)}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return ke(this.url,e)}queries(e){return $e(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((s,r)=>{t[r]=s}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Ae(this,e)}#s=e=>{let{bodyCache:t,raw:s}=this,r=t[e];if(r)return r;let o=Object.keys(t)[0];return o?t[o].then(n=>(o==="json"&&(n=JSON.stringify(n)),new Response(n)[e]())):t[e]=s[e]()};json(){return this.#s("text").then(e=>JSON.parse(e))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(e,t){this.#t[e]=t}valid(e){return this.#t[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Oe](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var Le={Stringify:1,BeforeStream:2,Stream:3},Mt=(e,t)=>{let s=new String(e);return s.isEscaped=!0,s.callbacks=t,s};var fe=async(e,t,s,r,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let n=e.callbacks;if(!n?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let a=Promise.all(n.map(i=>i({phase:t,buffer:o,context:r}))).then(i=>Promise.all(i.filter(Boolean).map(c=>fe(c,t,!1,r,o))).then(()=>o[0]));return s?Mt(await a,n):a};var kt="text/plain; charset=UTF-8",de=(e,t)=>({"Content-Type":e,...t}),De=class{#t;#e;env={};#r;finalized=!1;error;#n;#o;#s;#h;#c;#l;#i;#u;#f;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new z(this.#t,this.#f,this.#u),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=new Response(null,{headers:this.#i??=new Headers})}set res(e){if(this.#s&&e){e=new Response(e.body,e);for(let[t,s]of this.#s.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#s.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of r)e.headers.append("set-cookie",o)}else e.headers.set(t,s)}this.#s=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#h=e;getLayout=()=>this.#h;setRenderer=e=>{this.#c=e};header=(e,t,s)=>{this.finalized&&(this.#s=new Response(this.#s.body,this.#s));let r=this.#s?this.#s.headers:this.#i??=new Headers;t===void 0?r.delete(e):s?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#n=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#a(e,t,s){let r=this.#s?new Headers(this.#s.headers):this.#i??new Headers;if(typeof t=="object"&&"headers"in t){let n=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[a,i]of n)a.toLowerCase()==="set-cookie"?r.append(a,i):r.set(a,i)}if(s)for(let[n,a]of Object.entries(s))if(typeof a=="string")r.set(n,a);else{r.delete(n);for(let i of a)r.append(n,i)}let o=typeof t=="number"?t:t?.status??this.#n;return new Response(e,{status:o,headers:r})}newResponse=(...e)=>this.#a(...e);body=(e,t,s)=>this.#a(e,t,s);text=(e,t,s)=>!this.#i&&!this.#n&&!t&&!s&&!this.finalized?new Response(e):this.#a(e,t,de(kt,s));json=(e,t,s)=>this.#a(JSON.stringify(e),t,de("application/json",s));html=(e,t,s)=>{let r=o=>this.#a(o,t,de("text/html; charset=UTF-8",s));return typeof e=="object"?fe(e,Le.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let s=String(e);return this.header("Location",/[^\x00-\xFF]/.test(s)?encodeURI(s):s),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>new Response,this.#l(this))};var m="ALL",qe="all",Fe=["get","post","put","delete","options","patch"],K="Can not add a route since the matcher is already built.",X=class extends Error{};var Ne="__COMPOSED_HANDLER";var $t=e=>e.text("404 Not Found",404),Be=(e,t)=>{if("getResponse"in e){let s=e.getResponse();return t.newResponse(s.body,s)}return console.error(e),t.text("Internal Server Error",500)},Ue=class ze{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Fe,qe].forEach(n=>{this[n]=(a,...i)=>(typeof a=="string"?this.#t=a:this.#n(n,this.#t,a),i.forEach(c=>{this.#n(n,this.#t,c)}),this)}),this.on=(n,a,...i)=>{for(let c of[a].flat()){this.#t=c;for(let l of[n].flat())i.map(h=>{this.#n(l.toUpperCase(),this.#t,h)})}return this},this.use=(n,...a)=>(typeof n=="string"?this.#t=n:(this.#t="*",a.unshift(n)),a.forEach(i=>{this.#n(m,this.#t,i)}),this);let{strict:r,...o}=t;Object.assign(this,o),this.getPath=r??!0?t.getPath??he:He}#e(){let t=new ze({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=$t;errorHandler=Be;route(t,s){let r=this.basePath(t);return s.routes.map(o=>{let n;s.errorHandler===Be?n=o.handler:(n=async(a,i)=>(await ie([],s.errorHandler)(a,()=>o.handler(a,i))).res,n[Ne]=o.handler),r.#n(o.method,o.path,n)}),this}basePath(t){let s=this.#e();return s._basePath=j(this._basePath,t),s}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,s,r){let o,n;r&&(typeof r=="function"?n=r:(n=r.optionHandler,r.replaceRequest===!1?o=c=>c:o=r.replaceRequest));let a=n?c=>{let l=n(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=j(this._basePath,t),l=c==="/"?0:c.length;return h=>{let u=new URL(h.url);return u.pathname=u.pathname.slice(l)||"/",new Request(u,h)}})();let i=async(c,l)=>{let h=await s(o(c.req.raw),...a(c));if(h)return h;await l()};return this.#n(m,j(t,"*"),i),this}#n(t,s,r){t=t.toUpperCase(),s=j(this._basePath,s);let o={basePath:this._basePath,path:s,method:t,handler:r};this.router.add(t,s,[r,o]),this.routes.push(o)}#o(t,s){if(t instanceof Error)return this.errorHandler(t,s);throw t}#s(t,s,r,o){if(o==="HEAD")return(async()=>new Response(null,await this.#s(t,s,r,"GET")))();let n=this.getPath(t,{env:r}),a=this.router.match(o,n),i=new De(t,{path:n,matchResult:a,env:r,executionCtx:s,notFoundHandler:this.#r});if(a[0].length===1){let l;try{l=a[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(h){return this.#o(h,i)}return l instanceof Promise?l.then(h=>h||(i.finalized?i.res:this.#r(i))).catch(h=>this.#o(h,i)):l??this.#r(i)}let c=ie(a[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(i);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,i)}})()}fetch=(t,...s)=>this.#s(t,s[1],s[0],t.method);request=(t,s,r,o)=>t instanceof Request?this.fetch(s?new Request(t,s):t,r,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${j("/",t)}`,s),r,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#s(t.request,t,void 0,t.request.method))})}};var J=[];function pe(e,t){let s=this.buildAllMatchers(),r=((o,n)=>{let a=s[o]||s[m],i=a[2][n];if(i)return i;let c=n.match(a[0]);if(!c)return[[],J];let l=c.indexOf("",1);return[a[1][l],c]});return this.match=r,r(e,t)}var Z="[^/]+",L=".*",D="(?:|/.*)",S=Symbol(),_t=new Set(".\\+*[^]$()");function Lt(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===L||e===D?1:t===L||t===D?-1:e===Z?1:t===Z?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Ve=class me{#t;#e;#r=Object.create(null);insert(t,s,r,o,n){if(t.length===0){if(this.#t!==void 0)throw S;if(n)return;this.#t=s;return}let[a,...i]=t,c=a==="*"?i.length===0?["","",L]:["","",Z]:a==="/*"?["","",D]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let h=c[1],u=c[2]||Z;if(h&&c[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw S;if(l=this.#r[u],!l){if(Object.keys(this.#r).some(p=>p!==L&&p!==D))throw S;if(n)return;l=this.#r[u]=new me,h!==""&&(l.#e=o.varIndex++)}!n&&h!==""&&r.push([h,l.#e])}else if(l=this.#r[a],!l){if(Object.keys(this.#r).some(h=>h.length>1&&h!==L&&h!==D))throw S;if(n)return;l=this.#r[a]=new me}l.insert(i,s,r,o,n)}buildRegExpStr(){let s=Object.keys(this.#r).sort(Lt).map(r=>{let o=this.#r[r];return(typeof o.#e=="number"?`(${r})@${o.#e}`:_t.has(r)?`\\${r}`:r)+o.buildRegExpStr()});return typeof this.#t=="number"&&s.unshift(`#${this.#t}`),s.length===0?"":s.length===1?s[0]:"(?:"+s.join("|")+")"}};var We=class{#t={varIndex:0};#e=new Ve;insert(e,t,s){let r=[],o=[];for(let a=0;;){let i=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${a}`;return o[a]=[l,c],a++,i=!0,l}),!i)break}let n=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=o.length-1;a>=0;a--){let[i]=o[a];for(let c=n.length-1;c>=0;c--)if(n[c].indexOf(i)!==-1){n[c]=n[c].replace(i,o[a][1]);break}}return this.#e.insert(n,t,r,this.#t,s),r}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,s=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,n,a)=>n!==void 0?(s[++t]=Number(n),"$()"):(a!==void 0&&(r[Number(a)]=++t),"")),[new RegExp(`^${e}`),s,r]}};var Dt=[/^$/,[],Object.create(null)],Ge=Object.create(null);function Ke(e){return Ge[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,s)=>s?`\\${s}`:"(?:|/.*)")}$`)}function qt(){Ge=Object.create(null)}function Ft(e){let t=new We,s=[];if(e.length===0)return Dt;let r=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,h],[u,p])=>l?1:u?-1:h.length-p.length),o=Object.create(null);for(let l=0,h=-1,u=r.length;l<u;l++){let[p,d,g]=r[l];p?o[d]=[g.map(([y])=>[y,Object.create(null)]),J]:h++;let f;try{f=t.insert(d,h,p)}catch(y){throw y===S?new X(d):y}p||(s[h]=g.map(([y,v])=>{let B=Object.create(null);for(v-=1;v>=0;v--){let[U,w]=f[v];B[U]=w}return[y,B]}))}let[n,a,i]=t.buildRegExp();for(let l=0,h=s.length;l<h;l++)for(let u=0,p=s[l].length;u<p;u++){let d=s[l][u]?.[1];if(!d)continue;let g=Object.keys(d);for(let f=0,y=g.length;f<y;f++)d[g[f]]=i[d[g[f]]]}let c=[];for(let l in a)c[l]=s[a[l]];return[n,c,o]}function A(e,t){if(e){for(let s of Object.keys(e).sort((r,o)=>o.length-r.length))if(Ke(s).test(t))return[...e[s]]}}var Q=class{name="RegExpRouter";#t;#e;constructor(){this.#t={[m]:Object.create(null)},this.#e={[m]:Object.create(null)}}add(e,t,s){let r=this.#t,o=this.#e;if(!r||!o)throw new Error(K);r[e]||[r,o].forEach(i=>{i[e]=Object.create(null),Object.keys(i[m]).forEach(c=>{i[e][c]=[...i[m][c]]})}),t==="/*"&&(t="*");let n=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let i=Ke(t);e===m?Object.keys(r).forEach(c=>{r[c][t]||=A(r[c],t)||A(r[m],t)||[]}):r[e][t]||=A(r[e],t)||A(r[m],t)||[],Object.keys(r).forEach(c=>{(e===m||e===c)&&Object.keys(r[c]).forEach(l=>{i.test(l)&&r[c][l].push([s,n])})}),Object.keys(o).forEach(c=>{(e===m||e===c)&&Object.keys(o[c]).forEach(l=>i.test(l)&&o[c][l].push([s,n]))});return}let a=G(t)||[t];for(let i=0,c=a.length;i<c;i++){let l=a[i];Object.keys(o).forEach(h=>{(e===m||e===h)&&(o[h][l]||=[...A(r[h],l)||A(r[m],l)||[]],o[h][l].push([s,n-c+i+1]))})}}match=pe;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#e).concat(Object.keys(this.#t)).forEach(t=>{e[t]||=this.#r(t)}),this.#t=this.#e=void 0,qt(),e}#r(e){let t=[],s=e===m;return[this.#t,this.#e].forEach(r=>{let o=r[e]?Object.keys(r[e]).map(n=>[n,r[e][n]]):[];o.length!==0?(s||=!0,t.push(...o)):e!==m&&t.push(...Object.keys(r[m]).map(n=>[n,r[m][n]]))}),s?Ft(t):null}};var ye=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,s){if(!this.#e)throw new Error(K);this.#e.push([e,t,s])}match(e,t){if(!this.#e)throw new Error("Fatal error");let s=this.#t,r=this.#e,o=s.length,n=0,a;for(;n<o;n++){let i=s[n];try{for(let c=0,l=r.length;c<l;c++)i.add(...r[c]);a=i.match(e,t)}catch(c){if(c instanceof X)continue;throw c}this.match=i.match.bind(i),this.#t=[i],this.#e=void 0;break}if(n===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var q=Object.create(null),Xe=class Je{#t;#e;#r;#n=0;#o=q;constructor(t,s,r){if(this.#e=r||Object.create(null),this.#t=[],t&&s){let o=Object.create(null);o[t]={handler:s,possibleKeys:[],score:0},this.#t=[o]}this.#r=[]}insert(t,s,r){this.#n=++this.#n;let o=this,n=Ie(s),a=[];for(let i=0,c=n.length;i<c;i++){let l=n[i],h=n[i+1],u=Te(l,h),p=Array.isArray(u)?u[0]:l;if(p in o.#e){o=o.#e[p],u&&a.push(u[1]);continue}o.#e[p]=new Je,u&&(o.#r.push(u),a.push(u[1])),o=o.#e[p]}return o.#t.push({[t]:{handler:r,possibleKeys:a.filter((i,c,l)=>l.indexOf(i)===c),score:this.#n}}),o}#s(t,s,r,o){let n=[];for(let a=0,i=t.#t.length;a<i;a++){let c=t.#t[a],l=c[s]||c[m],h={};if(l!==void 0&&(l.params=Object.create(null),n.push(l),r!==q||o&&o!==q))for(let u=0,p=l.possibleKeys.length;u<p;u++){let d=l.possibleKeys[u],g=h[l.score];l.params[d]=o?.[d]&&!g?o[d]:r[d]??o?.[d],h[l.score]=!0}}return n}search(t,s){let r=[];this.#o=q;let n=[this],a=le(s),i=[];for(let c=0,l=a.length;c<l;c++){let h=a[c],u=c===l-1,p=[];for(let d=0,g=n.length;d<g;d++){let f=n[d],y=f.#e[h];y&&(y.#o=f.#o,u?(y.#e["*"]&&r.push(...this.#s(y.#e["*"],t,f.#o)),r.push(...this.#s(y,t,f.#o))):p.push(y));for(let v=0,B=f.#r.length;v<B;v++){let U=f.#r[v],w=f.#o===q?{}:{...f.#o};if(U==="*"){let x=f.#e["*"];x&&(r.push(...this.#s(x,t,f.#o)),x.#o=w,p.push(x));continue}let[Pt,Ce,_]=U;if(!h&&!(_ instanceof RegExp))continue;let b=f.#e[Pt],Rt=a.slice(c).join("/");if(_ instanceof RegExp){let x=_.exec(Rt);if(x){if(w[Ce]=x[0],r.push(...this.#s(b,t,f.#o,w)),Object.keys(b.#e).length){b.#o=w;let jt=x[0].match(/\//)?.length??0;(i[jt]||=[]).push(b)}continue}}(_===!0||_.test(h))&&(w[Ce]=h,u?(r.push(...this.#s(b,t,w,f.#o)),b.#e["*"]&&r.push(...this.#s(b.#e["*"],t,w,f.#o))):(b.#o=w,p.push(b)))}}n=p.concat(i.shift()??[])}return r.length>1&&r.sort((c,l)=>c.score-l.score),[r.map(({handler:c,params:l})=>[c,l])]}};var ge=class{name="TrieRouter";#t;constructor(){this.#t=new Xe}add(e,t,s){let r=G(t);if(r){for(let o=0,n=r.length;o<n;o++)this.#t.insert(e,r[o],s);return}this.#t.insert(e,t,s)}match(e,t){return this.#t.search(e,t)}};var ve=class extends Ue{constructor(e={}){super(e),this.router=e.router??new ye({routers:[new Q,new ge]})}};import{mkdir as Re,writeFile as yr,readFile as gr,stat as gt}from"node:fs/promises";import{randomBytes as vr}from"node:crypto";import{createServer as Nt}from"http";import{Http2ServerRequest as Bt}from"http2";import{Http2ServerRequest as we}from"http2";import{Readable as Ze}from"stream";import er from"crypto";var C=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},Ut=e=>e instanceof C?e:new C(e.message,{cause:e}),zt=global.Request,F=class extends zt{constructor(e,t){typeof e=="object"&&H in e&&(e=e[H]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},Vt=e=>{let t=[],s=e.rawHeaders;for(let r=0;r<s.length;r+=2){let{[r]:o,[r+1]:n}=s;o.charCodeAt(0)!==58&&t.push([o,n])}return new Headers(t)},Ye=Symbol("wrapBodyStream"),Wt=(e,t,s,r,o)=>{let n={method:e,headers:s,signal:o.signal};if(e==="TRACE"){n.method="GET";let a=new F(t,n);return Object.defineProperty(a,"method",{get(){return"TRACE"}}),a}if(!(e==="GET"||e==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)n.body=new ReadableStream({start(a){a.enqueue(r.rawBody),a.close()}});else if(r[Ye]){let a;n.body=new ReadableStream({async pull(i){try{a||=Ze.toWeb(r).getReader();let{done:c,value:l}=await a.read();c?i.close():i.enqueue(l)}catch(c){i.error(c)}}})}else n.body=Ze.toWeb(r);return new F(t,n)},H=Symbol("getRequestCache"),Gt=Symbol("requestCache"),Y=Symbol("incomingKey"),ee=Symbol("urlKey"),Kt=Symbol("headersKey"),T=Symbol("abortControllerKey"),Xt=Symbol("getAbortController"),te={get method(){return this[Y].method||"GET"},get url(){return this[ee]},get headers(){return this[Kt]||=Vt(this[Y])},[Xt](){return this[H](),this[T]},[H](){return this[T]||=new AbortController,this[Gt]||=Wt(this.method,this[ee],this.headers,this[Y],this[T])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(te,e,{get(){return this[H]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(te,e,{value:function(){return this[H]()[e]()}})});Object.setPrototypeOf(te,F.prototype);var Jt=(e,t)=>{let s=Object.create(te);s[Y]=e;let r=e.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(e instanceof we)throw new C("Absolute URL for :path is not allowed in HTTP/2");try{let i=new URL(r);s[ee]=i.href}catch(i){throw new C("Invalid absolute URL",{cause:i})}return s}let o=(e instanceof we?e.authority:e.headers.host)||t;if(!o)throw new C("Missing host header");let n;if(e instanceof we){if(n=e.scheme,!(n==="http"||n==="https"))throw new C("Unsupported scheme")}else n=e.socket&&e.socket.encrypted?"https":"http";let a=new URL(`${n}://${o}${r}`);if(a.hostname.length!==o.length&&a.hostname!==o.replace(/:\d+$/,""))throw new C("Invalid host header");return s[ee]=a.href,s},Qe=Symbol("responseCache"),I=Symbol("getResponseCache"),O=Symbol("cache"),Ee=global.Response,N=class et{#t;#e;[I](){return delete this[O],this[Qe]||=new Ee(this.#t,this.#e)}constructor(t,s){let r;if(this.#t=t,s instanceof et){let o=s[Qe];if(o){this.#e=o,this[I]();return}else this.#e=s.#e,r=new Headers(s.#e.headers)}else this.#e=s;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(r||=s?.headers||{"content-type":"text/plain; charset=UTF-8"},this[O]=[s?.status||200,t,r])}get headers(){let t=this[O];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2])),t[2]):this[I]().headers}get status(){return this[O]?.[0]??this[I]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(N.prototype,e,{get(){return this[I]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(N.prototype,e,{value:function(){return this[I]()[e]()}})});Object.setPrototypeOf(N,Ee);Object.setPrototypeOf(N.prototype,Ee.prototype);async function Zt(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function tt(e,t,s){let r=i=>{e.cancel(i).catch(()=>{})};return t.on("close",r),t.on("error",r),(s??e.read()).then(a,o),e.closed.finally(()=>{t.off("close",r),t.off("error",r)});function o(i){i&&t.destroy(i)}function n(){e.read().then(a,o)}function a({done:i,value:c}){try{if(i)t.end();else if(!t.write(c))t.once("drain",n);else return e.read().then(a,o)}catch(l){o(l)}}}function Qt(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:tt(e.getReader(),t)}var rt=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let s=[];for(let[r,o]of e)r==="set-cookie"?s.push(o):t[r]=o;return s.length>0&&(t["set-cookie"]=s),t["content-type"]??="text/plain; charset=UTF-8",t},Yt="x-hono-already-sent",tr=global.fetch;typeof global.crypto>"u"&&(global.crypto=er);global.fetch=(e,t)=>(t={compress:!1,...t},tr(e,t));var xe=Symbol("outgoingEnded"),rr=()=>new Response(null,{status:400}),st=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),be=(e,t)=>{let s=e instanceof Error?e:new Error("unknown error",{cause:e});s.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${s.message}`),t.destroy(s))},ot=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},nt=async(e,t)=>{let[s,r,o]=e[O];o instanceof Headers&&(o=rt(o)),typeof r=="string"?o["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?o["Content-Length"]=r.byteLength:r instanceof Blob&&(o["Content-Length"]=r.size),t.writeHead(s,o),typeof r=="string"||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(ot(t),await Qt(r,t)?.catch(n=>be(n,t))),t[xe]?.()},sr=e=>typeof e.then=="function",or=async(e,t,s={})=>{if(sr(e))if(s.errorHandler)try{e=await e}catch(o){let n=await s.errorHandler(o);if(!n)return;e=n}else e=await e.catch(st);if(O in e)return nt(e,t);let r=rt(e.headers);if(e.body){let o=e.body.getReader(),n=[],a=!1,i;if(r["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){i||=o.read();let h=await Zt(i).catch(u=>{console.error(u),a=!0});if(!h){if(l===1){await new Promise(u=>setTimeout(u)),c=3;continue}break}if(i=void 0,h.value&&n.push(h.value),h.done){a=!0;break}}a&&!("content-length"in r)&&(r["content-length"]=n.reduce((l,h)=>l+h.length,0))}t.writeHead(e.status,r),n.forEach(c=>{t.write(c)}),a?t.end():(n.length===0&&ot(t),await tt(o,t,i))}else r[Yt]||(t.writeHead(e.status,r),t.end());t[xe]?.()},nr=(e,t={})=>{let s=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==F&&(Object.defineProperty(global,"Request",{value:F}),Object.defineProperty(global,"Response",{value:N})),async(r,o)=>{let n,a;try{a=Jt(r,t.hostname);let i=!s||r.method==="GET"||r.method==="HEAD";if(i||(r[Ye]=!0,r.on("end",()=>{i=!0}),r instanceof Bt&&(o[xe]=()=>{i||setTimeout(()=>{i||setTimeout(()=>{r.destroy(),o.destroy()})})})),o.on("close",()=>{a[T]&&(r.errored?a[T].abort(r.errored.toString()):o.writableFinished||a[T].abort("Client connection prematurely closed.")),i||setTimeout(()=>{i||setTimeout(()=>{r.destroy()})})}),n=e(a,{incoming:r,outgoing:o}),O in n)return nt(n,o)}catch(i){if(n)return be(i,o);if(t.errorHandler){if(n=await t.errorHandler(a?i:Ut(i)),!n)return}else a?n=st(i):n=rr()}try{return await or(n,o,t)}catch(i){return be(i,o)}}},ar=e=>{let t=e.fetch,s=nr(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||Nt)(e.serverOptions||{},s)},at=(e,t)=>{let s=ar(e);return s.listen(e?.port??3e3,e.hostname,()=>{let r=s.address();t&&t(r)}),s};import{readFileSync as ir,existsSync as cr}from"node:fs";function it(){let e=process.env.MOLNOS_RUNTIME_CONFIG;if(!e||!cr(e))return{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}};try{let t=ir(e,"utf-8");return JSON.parse(t)}catch(t){return console.error("[loadRuntimeConfig] Failed to load runtime config:",t),{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}}}}var M=class extends Error{constructor(t){super(),this.name="ValidationError",this.message=t||"Invalid input",this.cause={statusCode:400}}};var re=class extends Error{constructor(t){super(),this.name="InvalidPathError",this.message=t||"Invalid file path",this.cause={statusCode:400}}},k=class extends Error{constructor(t){super(),this.name="InvalidFormatError",this.message=t||"Invalid format",this.cause={statusCode:400}}},se=class extends Error{constructor(t){super(),this.name="FileTooLargeError",this.message=t||"File exceeds maximum size",this.cause={statusCode:413}}},oe=class extends Error{constructor(t){super(),this.name="ProjectTooLargeError",this.message=t||"Project exceeds maximum size",this.cause={statusCode:413}}},ne=class extends Error{constructor(t){super(),this.name="InvalidContentError",this.message=t||"Invalid content",this.cause={statusCode:400}}};function P(e,t="An error occurred"){let s=e?.message||e||t,r=e?.cause?.statusCode||e?.statusCode||400;return{message:s,status:r}}function ct(e,t,s={}){let r=Array.isArray(t)?t:[t];if(!e||!e.roles||!Array.isArray(e.roles)){let a=new Error("Unauthorized: User or roles missing");throw a.cause={statusCode:403},a}let o=e.roles.flatMap(a=>a?.policies?.flatMap(i=>(i?.permissions||[]).flatMap(l=>typeof l=="string"?l:l&&typeof l=="object"&&l.actions?l.actions:[]))||[]);if(!r.every(a=>o.includes(a)||o.includes("*")?!0:o.some(i=>{if(i.endsWith(".*")){let c=i.slice(0,-2);return a.startsWith(`${c}.`)}return!1}))){let a=new Error("Unauthorized");throw a.cause={statusCode:403},a}return!0}function lt(e,t,s,r,o){let n=e.find(c=>c.service===t);if(!n){let c=new Error(`Function bindings do not include access to service: ${t}`);throw c.cause={statusCode:403},c}if(!n.permissions||n.permissions.length===0)return;for(let c of n.permissions)if(!(c.resource&&c.resource!==s)){if(!c.resource||!c.actions||c.actions.length===0)return;if(c.actions.includes(r)){if(c.targets&&c.targets.length>0){if(!o)return;if(!c.targets.includes(o))continue}return}}let a=o?`:${o}`:"",i=new Error(`Function bindings do not allow: ${t}.${s}.${r}${a}`);throw i.cause={statusCode:403},i}async function R(e,t,s,r,o,n,a){if(!t)return null;let i=e.get("user");if(!i){let l=e.req.header("authorization");if(!l){let u=new Error("Unauthorized: No authentication provided");throw u.cause={statusCode:401},u}let h=l.replace(/^Bearer\s+/i,"");if(i=await t.getUserFromToken(h),!i){let u=new Error("Unauthorized: Invalid token");throw u.cause={statusCode:401},u}}ct(i,s,{});let c=e.req.header("x-function-bindings");if(c)try{let l=JSON.parse(c);lt(l,r,o,n,a)}catch(l){if(l.cause?.statusCode===403)throw l;let h=new Error("Invalid function bindings header");throw h.cause={statusCode:400},h}return i}async function ht(e,t,s){try{await R(e,s,"sites.project.list","sites","project","list");let r=e.req.header("x-forwarded-proto")||"http",o=e.req.header("host")||"localhost:3003",n=`${r}://${o}`,a=await t.listProjects(n);return e.json({success:!0,count:a.length,projects:a},200)}catch(r){let{message:o,status:n}=P(r,"Error listing projects");return e.json({error:o},n)}}var Pe=class{isSilent;propertyPath="";constructor(e=!1){this.isSilent=e}test(e,t){if(!t)throw new Error("Missing input!");this.updatePropertyPath();let{results:s,errors:r}=this.validate(e.properties,t),o=this.compileErrors(s,r),n=this.isSuccessful(s,o);return{errors:o,success:n}}compileErrors(e,t){let s=e.filter(r=>r.success===!1);return[...t,...s].flatMap(r=>r)}isSuccessful(e,t){return e.every(s=>s.success===!0)&&t.length===0}validate(e,t,s=[],r=[]){let o=e?.additionalProperties??!0,n=e?.required||[];r=this.checkForRequiredKeysErrors(n,t,r),r=this.checkForDisallowedProperties(Object.keys(t),Object.keys(e),r,o);for(let a in e){let i=n.includes(a)&&a!=="required",c=e[a],l=t[a],h=c.additionalProperties??!0;i&&(r=this.checkForRequiredKeysErrors(c.required||[],l,r)),this.isDefined(l)&&(this.handleValidation(a,l,c,s),r=this.checkForDisallowedProperties(Object.keys(l),Object.keys(c),r,h),this.handleNestedObject(l,c,s,r))}return{results:s,errors:r}}updatePropertyPath(e,t=""){if(!e){this.propertyPath="";return}t&&(this.propertyPath=t),this.propertyPath=`${this.propertyPath}.${e}`,this.propertyPath.startsWith(".")&&(this.propertyPath=this.propertyPath.substring(1,this.propertyPath.length))}isDefined(e){return!!(typeof e=="number"&&e===0||e||e===""||typeof e=="boolean")}checkForRequiredKeysErrors(e,t,s){if(!this.areRequiredKeysPresent(e,t)){let r=t?Object.keys(t):[],o=this.findNonOverlappingElements(e,r),n=o.length>0?`Missing the required key: '${o.join(", ")}'!`:`Missing values for required keys: '${r.filter(a=>!t[a]).join(", ")}'!`;s.push({key:"",value:t,success:!1,error:n})}return s}checkForDisallowedProperties(e,t,s,r){if(!r){let o=this.findNonOverlappingElements(e,t);o.length>0&&s.push({key:`${t}`,value:e,success:!1,error:`Has additional (disallowed) properties: '${o.join(", ")}'!`})}return s}handleValidation(e,t,s,r){this.updatePropertyPath(e);let o=this.validateProperty(this.propertyPath,s,t);r.push(...o);let n=(i,c)=>{i.forEach(l=>{let h=this.validateProperty(this.propertyPath,c.items,l);r.push(...h)}),this.updatePropertyPath()},a=i=>{let c=Object.keys(i),l=this.propertyPath;c.forEach(h=>{if(this.updatePropertyPath(h,l),this.isArray(i[h])&&s[h]?.items!=null)n(i[h],s[h]);else{let u=this.validateProperty(this.propertyPath,s[h],i[h]);r.push(...u)}})};this.isArray(t)&&s.items!=null?n(t,s):this.isObject(t)?a(t):this.updatePropertyPath()}handleNestedObject(e,t,s,r){if(this.isObject(e)){let o=this.getNestedObjects(e);for(let n of o){let a=t[n],i=e[n];a&&typeof i=="object"&&this.validate(a,i,s,r)}}}getNestedObjects(e){return Object.keys(e).filter(t=>{if(this.isObject(e))return t})}findNonOverlappingElements(e,t){return e.filter(s=>!t.includes(s))}areRequiredKeysPresent(e,t=[]){return e.every(s=>Object.keys(t).includes(s)?this.isDefined(t[s]):!1)}validateProperty(e,t,s){return this.validateInput(t,s).map(o=>{let{success:n,error:a}=o;return{key:e,value:s,success:n,error:a??""}})}validateInput(e,t){if(e){let s=[{condition:()=>e.type,validator:()=>this.isCorrectType(e.type,t),error:"Invalid type"},{condition:()=>e.format,validator:()=>this.isCorrectFormat(e.format,t),error:"Invalid format"},{condition:()=>e.minLength,validator:()=>this.isMinimumLength(e.minLength,t),error:"Length too short"},{condition:()=>e.maxLength,validator:()=>this.isMaximumLength(e.maxLength,t),error:"Length too long"},{condition:()=>e.minValue,validator:()=>this.isMinimumValue(e.minValue,t),error:"Value too small"},{condition:()=>e.maxValue,validator:()=>this.isMaximumValue(e.maxValue,t),error:"Value too large"},{condition:()=>e.matchesPattern,validator:()=>this.matchesPattern(e.matchesPattern,t),error:"Pattern does not match"}],r=[];for(let o of s)o.condition()&&!o.validator()&&r.push({success:!1,error:o.error});return r}else this.isSilent||console.warn(`Missing property '${e}' for match '${t}'. Skipping...`);return[{success:!0}]}isCorrectType(e,t){return Array.isArray(e)||(e=[e]),e.some(s=>{switch(s){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"object":return this.isObject(t);case"array":return this.isArray(t)}})}isObject(e){return e!==null&&!this.isArray(e)&&typeof e=="object"&&e instanceof Object&&Object.prototype.toString.call(e)==="[object Object]"}isArray(e){return Array.isArray(e)}isCorrectFormat(e,t){switch(e){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(t);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(t);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(t);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(t);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(t);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(t)}}isMinimumLength(e,t){return Array.isArray(t)?t.length>=e:t?.toString().length>=e}isMaximumLength(e,t){return Array.isArray(t)?t.length<=e:t.toString().length<=e}isMinimumValue(e,t){return t>=e}isMaximumValue(e,t){return t<=e}matchesPattern(e,t){return new RegExp(e).test(t)}schemaFrom(e){let t={properties:{additionalProperties:!1,required:[]}};for(let s in e){let r=e[s];t.properties.required.push(s),Array.isArray(r)?t.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?t.properties[s]=this.generateNestedObjectSchema(r):t.properties[s]=this.generatePropertySchema(r)}return t}generateArraySchema(e){let t={type:"array"},s=e.filter(r=>r);if(s.length>0){let r=s[0];s.every(n=>typeof n==typeof r)?typeof r=="object"&&!Array.isArray(r)?t.items=this.generateNestedObjectSchema(r):t.items=this.generatePropertySchema(r):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return t}generateNestedObjectSchema(e){let t={type:"object",additionalProperties:!1,required:[]};for(let s in e){let r=e[s];t.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?t[s]=this.generateNestedObjectSchema(r):t[s]=this.generatePropertySchema(r)}return t}generatePropertySchema(e){let t=typeof e,s={type:t};return t==="string"&&(s.minLength=1),s}};async function ut(e){try{return await e.req.json()}catch{return{}}}var ft={properties:{files:{type:"array",minItems:1,items:{type:"object",properties:{path:{type:"string",minLength:1},content:{type:"string",minLength:1}},required:["path","content"]}},projectId:{type:"string",pattern:"^[a-f0-9]+$"}},required:["files"],additionalProperties:!1};var hr=new Pe;async function dt(e,t,s){try{let r=await ut(e),o=hr.test(ft,r);if(!o.success)return e.json({error:"Invalid input",details:o.errors},400);await R(e,s,"sites.project.create","sites","project","create");let{files:n,projectId:a}=r;if(!n)return e.json({error:"files array is required"},400);let i=await t.uploadProject(n,a);return e.json({success:!0,projectId:i},200)}catch(r){let{message:o,status:n}=P(r,"Error uploading project");return e.json({error:o},n)}}async function pt(e,t,s){try{let{projectId:r}=e.req.param();return r?/^[a-f0-9]+$/.test(r)?(await R(e,s,"sites.project.delete","sites","project","delete",r),await t.projectExists(r)?(await t.deleteProject(r),e.json({success:!0,projectId:r},200)):e.json({error:"Project not found"},404)):e.json({error:"Invalid projectId format"},400):e.json({error:"projectId parameter is required"},400)}catch(r){let{message:o,status:n}=P(r,"Error deleting project");return e.json({error:o},n)}}import{extname as ur}from"node:path";function mt(e){let t=ur(e).toLowerCase();return{".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".ico":"image/x-icon",".txt":"text/plain",".pdf":"application/pdf",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject",".otf":"font/otf",".xml":"application/xml",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}[t]||"application/octet-stream"}async function yt(e,t,s){try{let r=e.req.param("projectId");if(!r)return e.json({error:"projectId is required"},400);await R(e,s,"sites.file.read","sites","file","read");let a=new URL(e.req.url).pathname.split(`/projects/${r}/`)[1]||""||"index.html";if(!await t.fileExists(r,a))return e.text("Not Found",404);let c=await t.getFile(r,a),l=mt(a);return e.body(c,200,{"Content-Type":l})}catch(r){let{message:o,status:n}=P(r,"Error serving file");return e.json({error:o},n)}}var wr=10,br=100,vt=xt(wr),wt=xt(br),Er="index.html";function xt(e){return e&&typeof e=="number"&&e>0?e*1024*1024:0}function $(e){return/^[a-z0-9-]{4,40}$/.test(e)}function je(e){if(!e)throw new M("File path is required");let t=mr(e.replace(/^\/+/,""));if(t.includes("..")||pr(t))throw new re("Invalid file path");return t===""||t==="/"?Er:t}var Se=class{rootPath;constructor(t){this.rootPath=t.path||"sites-data"}async start(){await Re(this.rootPath,{recursive:!0})}generateProjectId(t=8){return vr(Math.ceil(t/2)).toString("hex").slice(0,t)}async uploadProject(t,s=null){if(!t||!Array.isArray(t))throw new M("Invalid request format. Expected array of files in the request body.");s||(s=this.generateProjectId());let r=E(this.rootPath,s);if(!$(s))throw new k("Invalid project ID format");dr(r)&&ae(r,{recursive:!0,force:!0}),await Re(r,{recursive:!0});let o=0;for(let n of t){if(!n.path||!n.content)continue;let a=await this.saveFile(r,n.path,n.content);if(o+=a,o>wt)throw ae(r,{recursive:!0,force:!0}),new oe(`Project exceeds maximum size of ${wt/1024/1024}MB`)}if(t.length===0||o===0)throw ae(r,{recursive:!0,force:!0}),new M("No valid files were provided");return s}async saveFile(t,s,r){let o=je(s),n=E(t,o),a=fr(n);await Re(a,{recursive:!0});let i;try{i=Buffer.from(r,"base64")}catch(c){throw new ne(`Invalid content for file "${o}": ${c.message}`)}if(i.length>vt)throw new se(`File "${o}" exceeds maximum size of ${vt/1024/1024}MB`);return await yr(n,i),i.length}async getFile(t,s){if(!$(t))throw new k("Invalid project ID format");let r=je(s),o=E(this.rootPath,t,r);return await gr(o)}async fileExists(t,s){try{if(!$(t))return!1;let r=je(s),o=E(this.rootPath,t,r);return(await gt(o)).isFile()}catch{return!1}}async projectExists(t){try{if(!$(t))return!1;let s=E(this.rootPath,t);return(await gt(s)).isDirectory()}catch{return!1}}async deleteProject(t){if(!$(t))throw new k("Invalid project ID format");let s=E(this.rootPath,t);ae(s,{recursive:!0,force:!0})}async listProjects(t){try{let{readdir:s,stat:r}=await import("node:fs/promises"),o=await s(this.rootPath,{withFileTypes:!0}),n=[];for(let a of o)if(a.isDirectory()&&$(a.name)){let i=E(this.rootPath,a.name),c=await r(i),l=0,h=0,u=async d=>{let g=await s(d,{withFileTypes:!0});for(let f of g){let y=E(d,f.name);if(f.isDirectory())await u(y);else if(f.isFile()){l++;let v=await r(y);h+=v.size}}};await u(i);let p=d=>{if(d===0)return"0 B";let g=1024,f=["B","KB","MB","GB"],y=Math.floor(Math.log(d)/Math.log(g));return`${(d/g**y).toFixed(1)} ${f[y]}`};n.push({projectId:a.name,name:a.name,url:`${t}/projects/${a.name}/`,status:"active",files:l,size:p(h),lastDeployed:c.mtime.toISOString(),createdAt:c.birthtime.toISOString()})}return n}catch{return[]}}};async function xr(e){let t=e.dataPath||"data",s=E(t,"sites"),r=new Se({path:e.sites?.path||s});await r.start();let o=e.identityService||null,n=new ve;return n.get("/projects",async a=>ht(a,r,o)),n.post("/projects",async a=>dt(a,r,o)),n.delete("/projects/:projectId",async a=>pt(a,r,o)),n.get("/projects/:projectId",async a=>{let i=a.req.param("projectId");return a.redirect(`/projects/${i}/`,301)}),n.get("/projects/:projectId/*",async a=>yt(a,r,o)),at({fetch:n.fetch,port:e.server.port||3003,hostname:e.server.host||"localhost"}),console.log(`Sites server started on ${e.server.host||"localhost"}:${e.server.port||3003}`),n}var Pr=process.argv.slice(2),bt=Pr.find(e=>e.startsWith("--port=")),Rr=bt?parseInt(bt.split("=")[1],10):3003,Et=it(),jr={molnos:{dataPath:Et.molnos.dataPath},sites:{},server:{port:Rr,host:Et.server.host}};xr(jr);export{xr as startServer};
|
package/dist/storage.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// MolnOS Core - See LICENSE file for copyright and license details.
|
|
2
|
+
var st=(t,e,s)=>(r,o)=>{let n=-1;return a(0);async function a(i){if(i<=n)throw new Error("next() called multiple times");n=i;let u,c=!1,l;if(t[i]?(l=t[i][0][0],r.req.routeIndex=i):l=i===t.length&&o||void 0,l)try{u=await l(r,()=>a(i+1))}catch(h){if(h instanceof Error&&e)r.error=h,u=await e(h,r),c=!0;else throw h}else r.finalized===!1&&s&&(u=await s(r));return u&&(r.finalized===!1||c)&&(r.res=u),r}};var xt=Symbol();var Et=async(t,e=Object.create(null))=>{let{all:s=!1,dot:r=!1}=e,n=(t instanceof G?t.raw.headers:t.headers).get("Content-Type");return n?.startsWith("multipart/form-data")||n?.startsWith("application/x-www-form-urlencoded")?je(t,{all:s,dot:r}):{}};async function je(t,e){let s=await t.formData();return s?Pe(s,e):{}}function Pe(t,e){let s=Object.create(null);return t.forEach((r,o)=>{e.all||o.endsWith("[]")?Re(s,o,r):s[o]=r}),e.dot&&Object.entries(s).forEach(([r,o])=>{r.includes(".")&&(ke(s,r,o),delete s[r])}),s}var Re=(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},ke=(t,e,s)=>{let r=t,o=e.split(".");o.forEach((n,a)=>{a===o.length-1?r[n]=s:((!r[n]||typeof r[n]!="object"||Array.isArray(r[n])||r[n]instanceof File)&&(r[n]=Object.create(null)),r=r[n])})};var nt=t=>{let e=t.split("/");return e[0]===""&&e.shift(),e},jt=t=>{let{groups:e,path:s}=Ce(t),r=nt(s);return Se(r,e)},Ce=t=>{let e=[];return t=t.replace(/\{[^}]+\}/g,(s,r)=>{let o=`@${r}`;return e.push([o,s]),o}),{groups:e,path:t}},Se=(t,e)=>{for(let s=e.length-1;s>=0;s--){let[r]=e[s];for(let o=t.length-1;o>=0;o--)if(t[o].includes(r)){t[o]=t[o].replace(r,e[s][1]);break}}return t},V={},Pt=(t,e)=>{if(t==="*")return"*";let s=t.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(s){let r=`${t}#${e}`;return V[r]||(s[2]?V[r]=e&&e[0]!==":"&&e[0]!=="*"?[r,s[1],new RegExp(`^${s[2]}(?=/${e})`)]:[t,s[1],new RegExp(`^${s[2]}$`)]:V[r]=[t,s[1],!0]),V[r]}return null},W=(t,e)=>{try{return e(t)}catch{return t.replace(/(?:%[0-9A-Fa-f]{2})+/g,s=>{try{return e(s)}catch{return s}})}},Oe=t=>W(t,decodeURI),at=t=>{let e=t.url,s=e.indexOf("/",e.indexOf(":")+4),r=s;for(;r<e.length;r++){let o=e.charCodeAt(r);if(o===37){let n=e.indexOf("?",r),a=e.slice(s,n===-1?void 0:n);return Oe(a.includes("%25")?a.replace(/%25/g,"%2525"):a)}else if(o===63)break}return e.slice(s,r)};var Rt=t=>{let e=at(t);return e.length>1&&e.at(-1)==="/"?e.slice(0,-1):e},C=(t,e,...s)=>(s.length&&(e=C(e,...s)),`${t?.[0]==="/"?"":"/"}${t}${e==="/"?"":`${t?.at(-1)==="/"?"":"/"}${e?.[0]==="/"?e.slice(1):e}`}`),K=t=>{if(t.charCodeAt(t.length-1)!==63||!t.includes(":"))return null;let e=t.split("/"),s=[],r="";return e.forEach(o=>{if(o!==""&&!/\:/.test(o))r+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){s.length===0&&r===""?s.push("/"):s.push(r);let n=o.replace("?","");r+="/"+n,s.push(r)}else r+="/"+o}),s.filter((o,n,a)=>a.indexOf(o)===n)},ot=t=>/[%+]/.test(t)?(t.indexOf("+")!==-1&&(t=t.replace(/\+/g," ")),t.indexOf("%")!==-1?W(t,it):t):t,kt=(t,e,s)=>{let r;if(!s&&e&&!/[%+]/.test(e)){let a=t.indexOf("?",8);if(a===-1)return;for(t.startsWith(e,a+1)||(a=t.indexOf(`&${e}`,a+1));a!==-1;){let i=t.charCodeAt(a+e.length+1);if(i===61){let u=a+e.length+2,c=t.indexOf("&",u);return ot(t.slice(u,c===-1?void 0:c))}else if(i==38||isNaN(i))return"";a=t.indexOf(`&${e}`,a+1)}if(r=/[%+]/.test(t),!r)return}let o={};r??=/[%+]/.test(t);let n=t.indexOf("?",8);for(;n!==-1;){let a=t.indexOf("&",n+1),i=t.indexOf("=",n);i>a&&a!==-1&&(i=-1);let u=t.slice(n+1,i===-1?a===-1?void 0:a:i);if(r&&(u=ot(u)),n=a,u==="")continue;let c;i===-1?c="":(c=t.slice(i+1,a===-1?void 0:a),r&&(c=ot(c))),s?(o[u]&&Array.isArray(o[u])||(o[u]=[]),o[u].push(c)):o[u]??=c}return e?o[e]:o},Ct=kt,St=(t,e)=>kt(t,e,!0),it=decodeURIComponent;var Ot=t=>W(t,it),G=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(t,e="/",s=[[]]){this.raw=t,this.path=e,this.#t=s,this.#e={}}param(t){return t?this.#r(t):this.#n()}#r(t){let e=this.#t[0][this.routeIndex][1][t],s=this.#o(e);return s&&/\%/.test(s)?Ot(s):s}#n(){let t={},e=Object.keys(this.#t[0][this.routeIndex][1]);for(let s of e){let r=this.#o(this.#t[0][this.routeIndex][1][s]);r!==void 0&&(t[s]=/\%/.test(r)?Ot(r):r)}return t}#o(t){return this.#t[1]?this.#t[1][t]:t}query(t){return Ct(this.url,t)}queries(t){return St(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 Et(this,t)}#s=t=>{let{bodyCache:e,raw:s}=this,r=e[t];if(r)return r;let o=Object.keys(e)[0];return o?e[o].then(n=>(o==="json"&&(n=JSON.stringify(n)),new Response(n)[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.#e[t]=e}valid(t){return this.#e[t]}get url(){return this.raw.url}get method(){return this.raw.method}get[xt](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,t]])=>t)}get routePath(){return this.#t[0].map(([[,t]])=>t)[this.routeIndex].path}};var At={Stringify:1,BeforeStream:2,Stream:3},Ae=(t,e)=>{let s=new String(t);return s.isEscaped=!0,s.callbacks=e,s};var ct=async(t,e,s,r,o)=>{typeof t=="object"&&!(t instanceof String)&&(t instanceof Promise||(t=t.toString()),t instanceof Promise&&(t=await t));let n=t.callbacks;if(!n?.length)return Promise.resolve(t);o?o[0]+=t:o=[t];let a=Promise.all(n.map(i=>i({phase:e,buffer:o,context:r}))).then(i=>Promise.all(i.filter(Boolean).map(u=>ct(u,e,!1,r,o))).then(()=>o[0]));return s?Ae(await a,n):a};var Me="text/plain; charset=UTF-8",ut=(t,e)=>({"Content-Type":t,...e}),Mt=class{#e;#t;env={};#r;finalized=!1;error;#n;#o;#s;#l;#c;#u;#i;#h;#d;constructor(t,e){this.#e=t,e&&(this.#o=e.executionCtx,this.env=e.env,this.#u=e.notFoundHandler,this.#d=e.path,this.#h=e.matchResult)}get req(){return this.#t??=new G(this.#e,this.#d,this.#h),this.#t}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=new Response(null,{headers:this.#i??=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 o of r)t.headers.append("set-cookie",o)}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.#i??=new Headers;e===void 0?r.delete(t):s?.append?r.append(t,e):r.set(t,e)};status=t=>{this.#n=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):{}}#a(t,e,s){let r=this.#s?new Headers(this.#s.headers):this.#i??new Headers;if(typeof e=="object"&&"headers"in e){let n=e.headers instanceof Headers?e.headers:new Headers(e.headers);for(let[a,i]of n)a.toLowerCase()==="set-cookie"?r.append(a,i):r.set(a,i)}if(s)for(let[n,a]of Object.entries(s))if(typeof a=="string")r.set(n,a);else{r.delete(n);for(let i of a)r.append(n,i)}let o=typeof e=="number"?e:e?.status??this.#n;return new Response(t,{status:o,headers:r})}newResponse=(...t)=>this.#a(...t);body=(t,e,s)=>this.#a(t,e,s);text=(t,e,s)=>!this.#i&&!this.#n&&!e&&!s&&!this.finalized?new Response(t):this.#a(t,e,ut(Me,s));json=(t,e,s)=>this.#a(JSON.stringify(t),e,ut("application/json",s));html=(t,e,s)=>{let r=o=>this.#a(o,e,ut("text/html; charset=UTF-8",s));return typeof t=="object"?ct(t,At.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 p="ALL",Bt="all",qt=["get","post","put","delete","options","patch"],J="Can not add a route since the matcher is already built.",Q=class extends Error{};var Tt="__COMPOSED_HANDLER";var Be=t=>t.text("404 Not Found",404),Ht=(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)},It=class Dt{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(e={}){[...qt,Bt].forEach(n=>{this[n]=(a,...i)=>(typeof a=="string"?this.#e=a:this.#n(n,this.#e,a),i.forEach(u=>{this.#n(n,this.#e,u)}),this)}),this.on=(n,a,...i)=>{for(let u of[a].flat()){this.#e=u;for(let c of[n].flat())i.map(l=>{this.#n(c.toUpperCase(),this.#e,l)})}return this},this.use=(n,...a)=>(typeof n=="string"?this.#e=n:(this.#e="*",a.unshift(n)),a.forEach(i=>{this.#n(p,this.#e,i)}),this);let{strict:r,...o}=e;Object.assign(this,o),this.getPath=r??!0?e.getPath??at:Rt}#t(){let e=new Dt({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#r=this.#r,e.routes=this.routes,e}#r=Be;errorHandler=Ht;route(e,s){let r=this.basePath(e);return s.routes.map(o=>{let n;s.errorHandler===Ht?n=o.handler:(n=async(a,i)=>(await st([],s.errorHandler)(a,()=>o.handler(a,i))).res,n[Tt]=o.handler),r.#n(o.method,o.path,n)}),this}basePath(e){let s=this.#t();return s._basePath=C(this._basePath,e),s}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#r=e,this);mount(e,s,r){let o,n;r&&(typeof r=="function"?n=r:(n=r.optionHandler,r.replaceRequest===!1?o=u=>u:o=r.replaceRequest));let a=n?u=>{let c=n(u);return Array.isArray(c)?c:[c]}:u=>{let c;try{c=u.executionCtx}catch{}return[u.env,c]};o||=(()=>{let u=C(this._basePath,e),c=u==="/"?0:u.length;return l=>{let h=new URL(l.url);return h.pathname=h.pathname.slice(c)||"/",new Request(h,l)}})();let i=async(u,c)=>{let l=await s(o(u.req.raw),...a(u));if(l)return l;await c()};return this.#n(p,C(e,"*"),i),this}#n(e,s,r){e=e.toUpperCase(),s=C(this._basePath,s);let o={basePath:this._basePath,path:s,method:e,handler:r};this.router.add(e,s,[r,o]),this.routes.push(o)}#o(e,s){if(e instanceof Error)return this.errorHandler(e,s);throw e}#s(e,s,r,o){if(o==="HEAD")return(async()=>new Response(null,await this.#s(e,s,r,"GET")))();let n=this.getPath(e,{env:r}),a=this.router.match(o,n),i=new Mt(e,{path:n,matchResult:a,env:r,executionCtx:s,notFoundHandler:this.#r});if(a[0].length===1){let c;try{c=a[0][0][0][0](i,async()=>{i.res=await this.#r(i)})}catch(l){return this.#o(l,i)}return c instanceof Promise?c.then(l=>l||(i.finalized?i.res:this.#r(i))).catch(l=>this.#o(l,i)):c??this.#r(i)}let u=st(a[0],this.errorHandler,this.#r);return(async()=>{try{let c=await u(i);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#o(c,i)}})()}fetch=(e,...s)=>this.#s(e,s[1],s[0],e.method);request=(e,s,r,o)=>e instanceof Request?this.fetch(s?new Request(e,s):e,r,o):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${C("/",e)}`,s),r,o));fire=()=>{addEventListener("fetch",e=>{e.respondWith(this.#s(e.request,e,void 0,e.request.method))})}};var X=[];function lt(t,e){let s=this.buildAllMatchers(),r=((o,n)=>{let a=s[o]||s[p],i=a[2][n];if(i)return i;let u=n.match(a[0]);if(!u)return[[],X];let c=u.indexOf("",1);return[a[1][c],u]});return this.match=r,r(t,e)}var Y="[^/]+",L=".*",$="(?:|/.*)",S=Symbol(),qe=new Set(".\\+*[^]$()");function Te(t,e){return t.length===1?e.length===1?t<e?-1:1:-1:e.length===1||t===L||t===$?1:e===L||e===$?-1:t===Y?1:e===Y?-1:t.length===e.length?t<e?-1:1:e.length-t.length}var Lt=class ht{#e;#t;#r=Object.create(null);insert(e,s,r,o,n){if(e.length===0){if(this.#e!==void 0)throw S;if(n)return;this.#e=s;return}let[a,...i]=e,u=a==="*"?i.length===0?["","",L]:["","",Y]:a==="/*"?["","",$]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(u){let l=u[1],h=u[2]||Y;if(l&&u[2]&&(h===".*"||(h=h.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(h))))throw S;if(c=this.#r[h],!c){if(Object.keys(this.#r).some(d=>d!==L&&d!==$))throw S;if(n)return;c=this.#r[h]=new ht,l!==""&&(c.#t=o.varIndex++)}!n&&l!==""&&r.push([l,c.#t])}else if(c=this.#r[a],!c){if(Object.keys(this.#r).some(l=>l.length>1&&l!==L&&l!==$))throw S;if(n)return;c=this.#r[a]=new ht}c.insert(i,s,r,o,n)}buildRegExpStr(){let s=Object.keys(this.#r).sort(Te).map(r=>{let o=this.#r[r];return(typeof o.#t=="number"?`(${r})@${o.#t}`:qe.has(r)?`\\${r}`:r)+o.buildRegExpStr()});return typeof this.#e=="number"&&s.unshift(`#${this.#e}`),s.length===0?"":s.length===1?s[0]:"(?:"+s.join("|")+")"}};var $t=class{#e={varIndex:0};#t=new Lt;insert(t,e,s){let r=[],o=[];for(let a=0;;){let i=!1;if(t=t.replace(/\{[^}]+\}/g,u=>{let c=`@\\${a}`;return o[a]=[c,u],a++,i=!0,c}),!i)break}let n=t.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let a=o.length-1;a>=0;a--){let[i]=o[a];for(let u=n.length-1;u>=0;u--)if(n[u].indexOf(i)!==-1){n[u]=n[u].replace(i,o[a][1]);break}}return this.#t.insert(n,e,r,this.#e,s),r}buildRegExp(){let t=this.#t.buildRegExpStr();if(t==="")return[/^$/,[],[]];let e=0,s=[],r=[];return t=t.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,n,a)=>n!==void 0?(s[++e]=Number(n),"$()"):(a!==void 0&&(r[Number(a)]=++e),"")),[new RegExp(`^${t}`),s,r]}};var He=[/^$/,[],Object.create(null)],Nt=Object.create(null);function _t(t){return Nt[t]??=new RegExp(t==="*"?"":`^${t.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,s)=>s?`\\${s}`:"(?:|/.*)")}$`)}function Ie(){Nt=Object.create(null)}function De(t){let e=new $t,s=[];if(t.length===0)return He;let r=t.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,l],[h,d])=>c?1:h?-1:l.length-d.length),o=Object.create(null);for(let c=0,l=-1,h=r.length;c<h;c++){let[d,m,x]=r[c];d?o[m]=[x.map(([w])=>[w,Object.create(null)]),X]:l++;let f;try{f=e.insert(m,l,d)}catch(w){throw w===S?new Q(m):w}d||(s[l]=x.map(([w,R])=>{let U=Object.create(null);for(R-=1;R>=0;R--){let[z,j]=f[R];U[z]=j}return[w,U]}))}let[n,a,i]=e.buildRegExp();for(let c=0,l=s.length;c<l;c++)for(let h=0,d=s[c].length;h<d;h++){let m=s[c][h]?.[1];if(!m)continue;let x=Object.keys(m);for(let f=0,w=x.length;f<w;f++)m[x[f]]=i[m[x[f]]]}let u=[];for(let c in a)u[c]=s[a[c]];return[n,u,o]}function B(t,e){if(t){for(let s of Object.keys(t).sort((r,o)=>o.length-r.length))if(_t(s).test(e))return[...t[s]]}}var Z=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[p]:Object.create(null)},this.#t={[p]:Object.create(null)}}add(t,e,s){let r=this.#e,o=this.#t;if(!r||!o)throw new Error(J);r[t]||[r,o].forEach(i=>{i[t]=Object.create(null),Object.keys(i[p]).forEach(u=>{i[t][u]=[...i[p][u]]})}),e==="/*"&&(e="*");let n=(e.match(/\/:/g)||[]).length;if(/\*$/.test(e)){let i=_t(e);t===p?Object.keys(r).forEach(u=>{r[u][e]||=B(r[u],e)||B(r[p],e)||[]}):r[t][e]||=B(r[t],e)||B(r[p],e)||[],Object.keys(r).forEach(u=>{(t===p||t===u)&&Object.keys(r[u]).forEach(c=>{i.test(c)&&r[u][c].push([s,n])})}),Object.keys(o).forEach(u=>{(t===p||t===u)&&Object.keys(o[u]).forEach(c=>i.test(c)&&o[u][c].push([s,n]))});return}let a=K(e)||[e];for(let i=0,u=a.length;i<u;i++){let c=a[i];Object.keys(o).forEach(l=>{(t===p||t===l)&&(o[l][c]||=[...B(r[l],c)||B(r[p],c)||[]],o[l][c].push([s,n-u+i+1]))})}}match=lt;buildAllMatchers(){let t=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(e=>{t[e]||=this.#r(e)}),this.#e=this.#t=void 0,Ie(),t}#r(t){let e=[],s=t===p;return[this.#e,this.#t].forEach(r=>{let o=r[t]?Object.keys(r[t]).map(n=>[n,r[t][n]]):[];o.length!==0?(s||=!0,e.push(...o)):t!==p&&e.push(...Object.keys(r[p]).map(n=>[n,r[p][n]]))}),s?De(e):null}};var dt=class{name="SmartRouter";#e=[];#t=[];constructor(t){this.#e=t.routers}add(t,e,s){if(!this.#t)throw new Error(J);this.#t.push([t,e,s])}match(t,e){if(!this.#t)throw new Error("Fatal error");let s=this.#e,r=this.#t,o=s.length,n=0,a;for(;n<o;n++){let i=s[n];try{for(let u=0,c=r.length;u<c;u++)i.add(...r[u]);a=i.match(t,e)}catch(u){if(u instanceof Q)continue;throw u}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(n===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,a}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var N=Object.create(null),Ft=class Ut{#e;#t;#r;#n=0;#o=N;constructor(e,s,r){if(this.#t=r||Object.create(null),this.#e=[],e&&s){let o=Object.create(null);o[e]={handler:s,possibleKeys:[],score:0},this.#e=[o]}this.#r=[]}insert(e,s,r){this.#n=++this.#n;let o=this,n=jt(s),a=[];for(let i=0,u=n.length;i<u;i++){let c=n[i],l=n[i+1],h=Pt(c,l),d=Array.isArray(h)?h[0]:c;if(d in o.#t){o=o.#t[d],h&&a.push(h[1]);continue}o.#t[d]=new Ut,h&&(o.#r.push(h),a.push(h[1])),o=o.#t[d]}return o.#e.push({[e]:{handler:r,possibleKeys:a.filter((i,u,c)=>c.indexOf(i)===u),score:this.#n}}),o}#s(e,s,r,o){let n=[];for(let a=0,i=e.#e.length;a<i;a++){let u=e.#e[a],c=u[s]||u[p],l={};if(c!==void 0&&(c.params=Object.create(null),n.push(c),r!==N||o&&o!==N))for(let h=0,d=c.possibleKeys.length;h<d;h++){let m=c.possibleKeys[h],x=l[c.score];c.params[m]=o?.[m]&&!x?o[m]:r[m]??o?.[m],l[c.score]=!0}}return n}search(e,s){let r=[];this.#o=N;let n=[this],a=nt(s),i=[];for(let u=0,c=a.length;u<c;u++){let l=a[u],h=u===c-1,d=[];for(let m=0,x=n.length;m<x;m++){let f=n[m],w=f.#t[l];w&&(w.#o=f.#o,h?(w.#t["*"]&&r.push(...this.#s(w.#t["*"],e,f.#o)),r.push(...this.#s(w,e,f.#o))):d.push(w));for(let R=0,U=f.#r.length;R<U;R++){let z=f.#r[R],j=f.#o===N?{}:{...f.#o};if(z==="*"){let k=f.#t["*"];k&&(r.push(...this.#s(k,e,f.#o)),k.#o=j,d.push(k));continue}let[ve,vt,D]=z;if(!l&&!(D instanceof RegExp))continue;let P=f.#t[ve],xe=a.slice(u).join("/");if(D instanceof RegExp){let k=D.exec(xe);if(k){if(j[vt]=k[0],r.push(...this.#s(P,e,f.#o,j)),Object.keys(P.#t).length){P.#o=j;let Ee=k[0].match(/\//)?.length??0;(i[Ee]||=[]).push(P)}continue}}(D===!0||D.test(l))&&(j[vt]=l,h?(r.push(...this.#s(P,e,j,f.#o)),P.#t["*"]&&r.push(...this.#s(P.#t["*"],e,j,f.#o))):(P.#o=j,d.push(P)))}}n=d.concat(i.shift()??[])}return r.length>1&&r.sort((u,c)=>u.score-c.score),[r.map(({handler:u,params:c})=>[u,c])]}};var ft=class{name="TrieRouter";#e;constructor(){this.#e=new Ft}add(t,e,s){let r=K(e);if(r){for(let o=0,n=r.length;o<n;o++)this.#e.insert(t,r[o],s);return}this.#e.insert(t,e,s)}match(t,e){return this.#e.search(t,e)}};var pt=class extends It{constructor(t={}){super(t),this.router=t.router??new dt({routers:[new Z,new ft]})}};import{join as v,dirname as gr}from"node:path";import{promises as b}from"node:fs";import{createServer as Le}from"http";import{Http2ServerRequest as $e}from"http2";import{Http2ServerRequest as mt}from"http2";import{Readable as zt}from"stream";import Xe from"crypto";var O=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},Ne=t=>t instanceof O?t:new O(t.message,{cause:t}),_e=global.Request,_=class extends _e{constructor(t,e){typeof t=="object"&&H in t&&(t=t[H]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},Fe=t=>{let e=[],s=t.rawHeaders;for(let r=0;r<s.length;r+=2){let{[r]:o,[r+1]:n}=s;o.charCodeAt(0)!==58&&e.push([o,n])}return new Headers(e)},Vt=Symbol("wrapBodyStream"),Ue=(t,e,s,r,o)=>{let n={method:t,headers:s,signal:o.signal};if(t==="TRACE"){n.method="GET";let a=new _(e,n);return Object.defineProperty(a,"method",{get(){return"TRACE"}}),a}if(!(t==="GET"||t==="HEAD"))if("rawBody"in r&&r.rawBody instanceof Buffer)n.body=new ReadableStream({start(a){a.enqueue(r.rawBody),a.close()}});else if(r[Vt]){let a;n.body=new ReadableStream({async pull(i){try{a||=zt.toWeb(r).getReader();let{done:u,value:c}=await a.read();u?i.close():i.enqueue(c)}catch(u){i.error(u)}}})}else n.body=zt.toWeb(r);return new _(e,n)},H=Symbol("getRequestCache"),ze=Symbol("requestCache"),tt=Symbol("incomingKey"),et=Symbol("urlKey"),Ge=Symbol("headersKey"),T=Symbol("abortControllerKey"),Ve=Symbol("getAbortController"),rt={get method(){return this[tt].method||"GET"},get url(){return this[et]},get headers(){return this[Ge]||=Fe(this[tt])},[Ve](){return this[H](),this[T]},[H](){return this[T]||=new AbortController,this[ze]||=Ue(this.method,this[et],this.headers,this[tt],this[T])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(rt,t,{get(){return this[H]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(rt,t,{value:function(){return this[H]()[t]()}})});Object.setPrototypeOf(rt,_.prototype);var We=(t,e)=>{let s=Object.create(rt);s[tt]=t;let r=t.url||"";if(r[0]!=="/"&&(r.startsWith("http://")||r.startsWith("https://"))){if(t instanceof mt)throw new O("Absolute URL for :path is not allowed in HTTP/2");try{let i=new URL(r);s[et]=i.href}catch(i){throw new O("Invalid absolute URL",{cause:i})}return s}let o=(t instanceof mt?t.authority:t.headers.host)||e;if(!o)throw new O("Missing host header");let n;if(t instanceof mt){if(n=t.scheme,!(n==="http"||n==="https"))throw new O("Unsupported scheme")}else n=t.socket&&t.socket.encrypted?"https":"http";let a=new URL(`${n}://${o}${r}`);if(a.hostname.length!==o.length&&a.hostname!==o.replace(/:\d+$/,""))throw new O("Invalid host header");return s[et]=a.href,s},Gt=Symbol("responseCache"),q=Symbol("getResponseCache"),A=Symbol("cache"),gt=global.Response,F=class Wt{#e;#t;[q](){return delete this[A],this[Gt]||=new gt(this.#e,this.#t)}constructor(e,s){let r;if(this.#e=e,s instanceof Wt){let o=s[Gt];if(o){this.#t=o,this[q]();return}else this.#t=s.#t,r=new Headers(s.#t.headers)}else this.#t=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[A]=[s?.status||200,e,r])}get headers(){let e=this[A];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[q]().headers}get status(){return this[A]?.[0]??this[q]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(F.prototype,t,{get(){return this[q]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(F.prototype,t,{value:function(){return this[q]()[t]()}})});Object.setPrototypeOf(F,gt);Object.setPrototypeOf(F.prototype,gt.prototype);async function Ke(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Kt(t,e,s){let r=i=>{t.cancel(i).catch(()=>{})};return e.on("close",r),e.on("error",r),(s??t.read()).then(a,o),t.closed.finally(()=>{e.off("close",r),e.off("error",r)});function o(i){i&&e.destroy(i)}function n(){t.read().then(a,o)}function a({done:i,value:u}){try{if(i)e.end();else if(!e.write(u))e.once("drain",n);else return t.read().then(a,o)}catch(c){o(c)}}}function Je(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:Kt(t.getReader(),e)}var Jt=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let s=[];for(let[r,o]of t)r==="set-cookie"?s.push(o):e[r]=o;return s.length>0&&(e["set-cookie"]=s),e["content-type"]??="text/plain; charset=UTF-8",e},Qe="x-hono-already-sent",Ye=global.fetch;typeof global.crypto>"u"&&(global.crypto=Xe);global.fetch=(t,e)=>(e={compress:!1,...e},Ye(t,e));var bt=Symbol("outgoingEnded"),Ze=()=>new Response(null,{status:400}),Qt=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),yt=(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))},Xt=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},Yt=async(t,e)=>{let[s,r,o]=t[A];o instanceof Headers&&(o=Jt(o)),typeof r=="string"?o["Content-Length"]=Buffer.byteLength(r):r instanceof Uint8Array?o["Content-Length"]=r.byteLength:r instanceof Blob&&(o["Content-Length"]=r.size),e.writeHead(s,o),typeof r=="string"||r instanceof Uint8Array?e.end(r):r instanceof Blob?e.end(new Uint8Array(await r.arrayBuffer())):(Xt(e),await Je(r,e)?.catch(n=>yt(n,e))),e[bt]?.()},tr=t=>typeof t.then=="function",er=async(t,e,s={})=>{if(tr(t))if(s.errorHandler)try{t=await t}catch(o){let n=await s.errorHandler(o);if(!n)return;t=n}else t=await t.catch(Qt);if(A in t)return Yt(t,e);let r=Jt(t.headers);if(t.body){let o=t.body.getReader(),n=[],a=!1,i;if(r["transfer-encoding"]!=="chunked"){let u=2;for(let c=0;c<u;c++){i||=o.read();let l=await Ke(i).catch(h=>{console.error(h),a=!0});if(!l){if(c===1){await new Promise(h=>setTimeout(h)),u=3;continue}break}if(i=void 0,l.value&&n.push(l.value),l.done){a=!0;break}}a&&!("content-length"in r)&&(r["content-length"]=n.reduce((c,l)=>c+l.length,0))}e.writeHead(t.status,r),n.forEach(u=>{e.write(u)}),a?e.end():(n.length===0&&Xt(e),await Kt(o,e,i))}else r[Qe]||(e.writeHead(t.status,r),e.end());e[bt]?.()},rr=(t,e={})=>{let s=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==_&&(Object.defineProperty(global,"Request",{value:_}),Object.defineProperty(global,"Response",{value:F})),async(r,o)=>{let n,a;try{a=We(r,e.hostname);let i=!s||r.method==="GET"||r.method==="HEAD";if(i||(r[Vt]=!0,r.on("end",()=>{i=!0}),r instanceof $e&&(o[bt]=()=>{i||setTimeout(()=>{i||setTimeout(()=>{r.destroy(),o.destroy()})})})),o.on("close",()=>{a[T]&&(r.errored?a[T].abort(r.errored.toString()):o.writableFinished||a[T].abort("Client connection prematurely closed.")),i||setTimeout(()=>{i||setTimeout(()=>{r.destroy()})})}),n=t(a,{incoming:r,outgoing:o}),A in n)return Yt(n,o)}catch(i){if(n)return yt(i,o);if(e.errorHandler){if(n=await e.errorHandler(a?i:Ne(i)),!n)return}else a?n=Qt(i):n=Ze()}try{return await er(n,o,e)}catch(i){return yt(i,o)}}},sr=t=>{let e=t.fetch,s=rr(e,{hostname:t.hostname,overrideGlobalObjects:t.overrideGlobalObjects,autoCleanupIncoming:t.autoCleanupIncoming});return(t.createServer||Le)(t.serverOptions||{},s)},Zt=(t,e)=>{let s=sr(t);return s.listen(t?.port??3e3,t.hostname,()=>{let r=s.address();e&&e(r)}),s};import{readFileSync as or,existsSync as nr}from"node:fs";function te(){let t=process.env.MOLNOS_RUNTIME_CONFIG;if(!t||!nr(t))return{molnos:{dataPath:"data"},server:{host:"localhost",port:3e3}};try{let e=or(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 M=class extends Error{constructor(e){super(),this.name="NotFoundError",this.message=e||"Resource not found",this.cause={statusCode:404}}};function y(t,e="An error occurred"){let s=t?.message||t||e,r=t?.cause?.statusCode||t?.statusCode||400;return{message:s,status:r}}function ee(t,e,s={}){let r=Array.isArray(e)?e:[e];if(!t||!t.roles||!Array.isArray(t.roles)){let a=new Error("Unauthorized: User or roles missing");throw a.cause={statusCode:403},a}let o=t.roles.flatMap(a=>a?.policies?.flatMap(i=>(i?.permissions||[]).flatMap(c=>typeof c=="string"?c:c&&typeof c=="object"&&c.actions?c.actions:[]))||[]);if(!r.every(a=>o.includes(a)||o.includes("*")?!0:o.some(i=>{if(i.endsWith(".*")){let u=i.slice(0,-2);return a.startsWith(`${u}.`)}return!1}))){let a=new Error("Unauthorized");throw a.cause={statusCode:403},a}return!0}function re(t,e,s,r,o){let n=t.find(u=>u.service===e);if(!n){let u=new Error(`Function bindings do not include access to service: ${e}`);throw u.cause={statusCode:403},u}if(!n.permissions||n.permissions.length===0)return;for(let u of n.permissions)if(!(u.resource&&u.resource!==s)){if(!u.resource||!u.actions||u.actions.length===0)return;if(u.actions.includes(r)){if(u.targets&&u.targets.length>0){if(!o)return;if(!u.targets.includes(o))continue}return}}let a=o?`:${o}`:"",i=new Error(`Function bindings do not allow: ${e}.${s}.${r}${a}`);throw i.cause={statusCode:403},i}async function g(t,e,s,r,o,n,a){if(!e)return null;let i=t.get("user");if(!i){let c=t.req.header("authorization");if(!c){let h=new Error("Unauthorized: No authentication provided");throw h.cause={statusCode:401},h}let l=c.replace(/^Bearer\s+/i,"");if(i=await e.getUserFromToken(l),!i){let h=new Error("Unauthorized: Invalid token");throw h.cause={statusCode:401},h}}ee(i,s,{});let u=t.req.header("x-function-bindings");if(u)try{let c=JSON.parse(u);re(c,r,o,n,a)}catch(c){if(c.cause?.statusCode===403)throw c;let l=new Error("Invalid function bindings header");throw l.cause={statusCode:400},l}return i}async function se(t,e,s){try{await g(t,s,"storage.bucket.list","storage","bucket","list");let r=await e.listBuckets();return t.json({buckets:r},200)}catch(r){let{message:o,status:n}=y(r,"Error listing buckets");return t.json({error:o},n)}}var E=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),o=this.compileErrors(s,r),n=this.isSuccessful(s,o);return{errors:o,success:n}}compileErrors(t,e){let s=t.filter(r=>r.success===!1);return[...e,...s].flatMap(r=>r)}isSuccessful(t,e){return t.every(s=>s.success===!0)&&e.length===0}validate(t,e,s=[],r=[]){let o=t?.additionalProperties??!0,n=t?.required||[];r=this.checkForRequiredKeysErrors(n,e,r),r=this.checkForDisallowedProperties(Object.keys(e),Object.keys(t),r,o);for(let a in t){let i=n.includes(a)&&a!=="required",u=t[a],c=e[a],l=u.additionalProperties??!0;i&&(r=this.checkForRequiredKeysErrors(u.required||[],c,r)),this.isDefined(c)&&(this.handleValidation(a,c,u,s),r=this.checkForDisallowedProperties(Object.keys(c),Object.keys(u),r,l),this.handleNestedObject(c,u,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):[],o=this.findNonOverlappingElements(t,r),n=o.length>0?`Missing the required key: '${o.join(", ")}'!`:`Missing values for required keys: '${r.filter(a=>!e[a]).join(", ")}'!`;s.push({key:"",value:e,success:!1,error:n})}return s}checkForDisallowedProperties(t,e,s,r){if(!r){let o=this.findNonOverlappingElements(t,e);o.length>0&&s.push({key:`${e}`,value:t,success:!1,error:`Has additional (disallowed) properties: '${o.join(", ")}'!`})}return s}handleValidation(t,e,s,r){this.updatePropertyPath(t);let o=this.validateProperty(this.propertyPath,s,e);r.push(...o);let n=(i,u)=>{i.forEach(c=>{let l=this.validateProperty(this.propertyPath,u.items,c);r.push(...l)}),this.updatePropertyPath()},a=i=>{let u=Object.keys(i),c=this.propertyPath;u.forEach(l=>{if(this.updatePropertyPath(l,c),this.isArray(i[l])&&s[l]?.items!=null)n(i[l],s[l]);else{let h=this.validateProperty(this.propertyPath,s[l],i[l]);r.push(...h)}})};this.isArray(e)&&s.items!=null?n(e,s):this.isObject(e)?a(e):this.updatePropertyPath()}handleNestedObject(t,e,s,r){if(this.isObject(t)){let o=this.getNestedObjects(t);for(let n of o){let a=e[n],i=t[n];a&&typeof i=="object"&&this.validate(a,i,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(o=>{let{success:n,error:a}=o;return{key:t,value:s,success:n,error:a??""}})}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 o of s)o.condition()&&!o.validator()&&r.push({success:!1,error:o.error});return r}else this.isSilent||console.warn(`Missing property '${t}' for match '${e}'. Skipping...`);return[{success:!0}]}isCorrectType(t,e){return Array.isArray(t)||(t=[t]),t.some(s=>{switch(s){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"object":return this.isObject(e);case"array":return this.isArray(e)}})}isObject(t){return t!==null&&!this.isArray(t)&&typeof t=="object"&&t instanceof Object&&Object.prototype.toString.call(t)==="[object Object]"}isArray(t){return Array.isArray(t)}isCorrectFormat(t,e){switch(t){case"alphanumeric":return new RegExp(/^[a-zA-Z0-9]+$/).test(e);case"numeric":return new RegExp(/^-?\d+(\.\d+)?$/).test(e);case"email":return new RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/).test(e);case"date":return new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(e);case"url":return new RegExp(/^(https?):\/\/[^\s$.?#].[^\s]*$/).test(e);case"hexColor":return new RegExp(/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i).test(e)}}isMinimumLength(t,e){return Array.isArray(e)?e.length>=t:e?.toString().length>=t}isMaximumLength(t,e){return Array.isArray(e)?e.length<=t:e.toString().length<=t}isMinimumValue(t,e){return e>=t}isMaximumValue(t,e){return e<=t}matchesPattern(t,e){return new RegExp(t).test(e)}schemaFrom(t){let e={properties:{additionalProperties:!1,required:[]}};for(let s in t){let r=t[s];e.properties.required.push(s),Array.isArray(r)?e.properties[s]=this.generateArraySchema(r):typeof r=="object"&&r!==null?e.properties[s]=this.generateNestedObjectSchema(r):e.properties[s]=this.generatePropertySchema(r)}return e}generateArraySchema(t){let e={type:"array"},s=t.filter(r=>r);if(s.length>0){let r=s[0];s.every(n=>typeof n==typeof r)?typeof r=="object"&&!Array.isArray(r)?e.items=this.generateNestedObjectSchema(r):e.items=this.generatePropertySchema(r):console.warn("All elements in array are not of the same type. Unable to generate a schema for these elements.")}return e}generateNestedObjectSchema(t){let e={type:"object",additionalProperties:!1,required:[]};for(let s in t){let r=t[s];e.required.push(s),typeof r=="object"&&!Array.isArray(r)&&r!==null?e[s]=this.generateNestedObjectSchema(r):e[s]=this.generatePropertySchema(r)}return e}generatePropertySchema(t){let e=typeof t,s={type:e};return e==="string"&&(s.minLength=1),s}};async function I(t){try{return await t.req.json()}catch{return{}}}var oe={properties:{public:{type:"boolean"}},additionalProperties:!1};var ir=new E;async function ne(t,e,s){try{let{bucket:r}=t.req.param();if(!r)return t.json({error:"bucket parameter is required"},400);let o=await I(t),n=ir.test(oe,o||{});if(!n.success)return t.json({error:"Invalid input",details:n.errors},400);await g(t,s,"storage.bucket.create","storage","bucket","create");let{public:a}=o||{};return await e.createBucket(r,a),t.json({success:!0,bucket:r,public:a||!1},200)}catch(r){let{message:o,status:n}=y(r,"Error creating bucket");return t.json({error:o},n)}}async function ae(t,e,s){try{let{bucket:r}=t.req.param();if(!r)return t.json({error:"bucket parameter is required"},400);await g(t,s,"storage.bucket.read","storage","bucket","read",r);let o=await e.getBucketStats(r),n=await e.isBucketPublic(r);return t.json({bucket:r,...o,public:n},200)}catch(r){let{message:o,status:n}=y(r,"Error getting bucket stats");return t.json({error:o},n)}}var ie={properties:{public:{type:"boolean"}},required:["public"],additionalProperties:!1};var ur=new E;async function ce(t,e,s){try{let{bucket:r}=t.req.param();if(!r)return t.json({error:"bucket parameter is required"},400);let o;try{o=await t.req.json()}catch{return t.json({error:"Invalid JSON body"},400)}let{public:n}=o;if(n===void 0)return t.json({error:"No valid configuration provided"},400);let a=ur.test(ie,o);if(!a.success)return t.json({error:"Invalid input",details:a.errors},400);if(await g(t,s,"storage.bucket.update","storage","bucket","update",r),!await e.bucketExists(r))return t.json({error:"Bucket not found"},404);await e.updateBucket(r,{public:n});let u=await e.isBucketPublic(r);return t.json({success:!0,bucket:r,public:u},200)}catch(r){let{message:o,status:n}=y(r,"Error updating bucket");return t.json({error:o},n)}}async function ue(t,e,s){try{let{bucket:r}=t.req.param();return r?(await g(t,s,"storage.bucket.delete","storage","bucket","delete",r),await e.bucketExists(r)?(await e.deleteBucket(r),t.json({success:!0,bucket:r},200)):t.json({error:"Bucket not found"},404)):t.json({error:"bucket parameter is required"},400)}catch(r){let{message:o,status:n}=y(r,"Error deleting bucket");return t.json({error:o},n)}}async function le(t,e,s){try{let{bucket:r}=t.req.param();if(!r)return t.json({error:"bucket parameter is required"},400);let o=t.req.query("prefix")||"";await g(t,s,"storage.object.list","storage","object","list");let n=await e.listObjects(r,o);return t.json({objects:n,prefix:o},200)}catch(r){let{message:o,status:n}=y(r,"Error listing objects");return t.json({error:o},n)}}var he={properties:{key:{type:"string",minLength:1},content:{type:"string"}},required:["key"],additionalProperties:!1};var hr=new E;async function de(t,e,s){try{let{bucket:r}=t.req.param(),o=t.req.header("content-type")||"";if(!r)return t.json({error:"bucket parameter is required"},400);if(await g(t,s,"storage.object.write","storage","object","write"),o.includes("multipart/form-data")){let c=await t.req.formData(),l=c.get("file"),h=c.get("key");if(!h)return t.json({error:"key is required"},400);if(!l)return t.json({error:"file is required"},400);let d=await l.arrayBuffer(),m=Buffer.from(d);return await e.putObject(r,h,m),t.json({success:!0,bucket:r,key:h},200)}if(o.includes("application/octet-stream")||o.includes("video/")||o.includes("image/")){let c=t.req.query("key");if(!c)return t.json({error:"key query parameter is required for binary uploads"},400);let l=await t.req.arrayBuffer(),h=Buffer.from(l);return await e.putObject(r,c,h),t.json({success:!0,bucket:r,key:c},200)}let n=await t.req.json(),a=hr.test(he,n);if(!a.success)return t.json({error:"Invalid input",details:a.errors},400);let{key:i,content:u}=n;return i?u?(await e.putObject(r,i,u),t.json({success:!0,bucket:r,key:i},200)):t.json({error:"content is required"},400):t.json({error:"key is required"},400)}catch(r){let{message:o,status:n}=y(r,"Error storing object");return t.json({error:o},n)}}var fe={properties:{key:{type:"string",minLength:1}},required:["key"],additionalProperties:!1};var fr=new E;async function pe(t,e,s){try{let{bucket:r}=t.req.param();if(!r)return t.json({error:"bucket parameter is required"},400);let o=await I(t),n=fr.test(fe,o);if(!n.success)return t.json({error:"Invalid input",details:n.errors},400);await g(t,s,"storage.object.read","storage","object","read");let{key:a}=o;if(!await e.objectExists(r,a))return t.json({error:"Object not found"},404);let u=await e.getObject(r,a);return t.json({bucket:r,key:a,content:u.toString()},200)}catch(r){let{message:o,status:n}=y(r,"Error getting object");return t.json({error:o},n)}}var me={properties:{key:{type:"string",minLength:1}},required:["key"],additionalProperties:!1};var mr=new E;async function ye(t,e,s){try{let{bucket:r}=t.req.param();if(!r)return t.json({error:"bucket parameter is required"},400);let o=await I(t),n=mr.test(me,o);if(!n.success)return t.json({error:"Invalid input",details:n.errors},400);await g(t,s,"storage.object.delete","storage","object","delete");let{key:a}=o;return await e.objectExists(r,a)?(await e.deleteObject(r,a),t.json({success:!0,bucket:r,key:a},200)):t.json({error:"Object not found"},404)}catch(r){let{message:o,status:n}=y(r,"Error deleting object");return t.json({error:o},n)}}function yr(t){let e=t.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",pdf:"application/pdf",json:"application/json",txt:"text/plain",html:"text/html",css:"text/css",js:"application/javascript",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav"}[e||""]||"application/octet-stream"}async function ge(t,e,s){try{let{bucket:r}=t.req.param(),n=t.req.path.match(/^\/buckets\/[^/]+\/objects\/(.+)$/);if(!n)return t.json({error:"Invalid object path"},400);let a=decodeURIComponent(n[1]);if(!r)return t.json({error:"bucket parameter is required"},400);if(await g(t,s,"storage.object.read","storage","object","read"),!await e.objectExists(r,a))return t.json({error:"Object not found"},404);let u=await e.getObject(r,a),c=yr(a),l=new Uint8Array(u);return new Response(l,{status:200,headers:{"Content-Type":c,"Content-Length":u.length.toString()}})}catch(r){let{message:o,status:n}=y(r,"Error retrieving object");return t.json({error:o},n)}}var wt=class{rootPath;metadataPath;constructor(e){this.rootPath=e.path||"storage-data",this.metadataPath=v(this.rootPath,".metadata")}async start(){await b.mkdir(this.rootPath,{recursive:!0}),await b.mkdir(this.metadataPath,{recursive:!0})}getBucketMetadataPath(e){return v(this.metadataPath,`${e}.json`)}async readBucketMetadata(e){let s=this.getBucketMetadataPath(e);try{let r=await b.readFile(s,"utf-8");return JSON.parse(r)}catch{return{public:!1}}}async writeBucketMetadata(e,s){let r=this.getBucketMetadataPath(e);await b.writeFile(r,JSON.stringify(s,null,2))}async deleteBucketMetadata(e){let s=this.getBucketMetadataPath(e);try{await b.unlink(s)}catch{}}async putObject(e,s,r){let o=v(this.rootPath,e,s);await b.mkdir(gr(o),{recursive:!0}),await b.writeFile(o,r)}async getObject(e,s){let r=v(this.rootPath,e,s);return await b.readFile(r)}async deleteObject(e,s){let r=v(this.rootPath,e,s);await b.unlink(r)}async objectExists(e,s){let r=v(this.rootPath,e,s);try{return await b.access(r),!0}catch{return!1}}async createBucket(e,s=!1){let r=v(this.rootPath,e);await b.mkdir(r,{recursive:!0}),await this.writeBucketMetadata(e,{public:s})}async deleteBucket(e){let s=v(this.rootPath,e);await b.rm(s,{recursive:!0,force:!0}),await this.deleteBucketMetadata(e)}async bucketExists(e){let s=v(this.rootPath,e);try{return(await b.stat(s)).isDirectory()}catch{return!1}}async isBucketPublic(e){return(await this.readBucketMetadata(e)).public}async updateBucket(e,s){if(!await this.bucketExists(e))throw new Error("Bucket not found");let n={...await this.readBucketMetadata(e),...s.public!==void 0&&{public:s.public}};await this.writeBucketMetadata(e,n)}async listBuckets(){try{return(await b.readdir(this.rootPath,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return[]}}async getBucketStats(e){let s=v(this.rootPath,e);try{if(!(await b.stat(s)).isDirectory())throw new M("Bucket not found")}catch(a){throw a.code==="ENOENT"?new M("Bucket not found"):a}let r=0,o=0,n=async a=>{let i=await b.readdir(a,{withFileTypes:!0});for(let u of i){let c=v(a,u.name);if(u.isDirectory())await n(c);else if(u.isFile()){r++;let l=await b.stat(c);o+=l.size}}};try{await n(s)}catch{return{objectCount:0,totalSize:0}}return{objectCount:r,totalSize:o}}async listObjects(e,s=""){let r=v(this.rootPath,e);try{if(!(await b.stat(r)).isDirectory())throw new M("Bucket not found")}catch(c){throw c.code==="ENOENT"?new M("Bucket not found"):c}let o=[],n=async(c,l="")=>{let h=await b.readdir(c,{withFileTypes:!0});for(let d of h){let m=v(c,d.name),x=l?`${l}/${d.name}`:d.name;if(d.isDirectory())await n(m,x);else if(d.isFile()){let f=await b.stat(m);o.push({key:x,size:f.size,lastModified:f.mtime,type:"file"})}}};try{await n(r)}catch{return[]}let a=s?o.filter(c=>c.key.startsWith(s)):o,i=[],u=new Set;for(let c of a){let l=s?c.key.substring(s.length):c.key,h=l.indexOf("/");if(h===-1)i.push({key:l,size:c.size,lastModified:c.lastModified,type:"file"});else{let d=l.substring(0,h);u.has(d)||(u.add(d),i.push({key:`${d}/`,size:0,lastModified:c.lastModified,type:"folder"}))}}return i.sort((c,l)=>c.type!==l.type?c.type==="folder"?-1:1:c.key.localeCompare(l.key))}};async function br(t){let e=t.dataPath||"data",s=v(e,"storage"),r=new wt({path:t.storage?.path||s});await r.start();let o=t.identityService||null,n=new pt;return n.get("/buckets",async a=>se(a,r,o)),n.post("/buckets/:bucket",async a=>ne(a,r,o)),n.get("/buckets/:bucket",async a=>ae(a,r,o)),n.patch("/buckets/:bucket",async a=>ce(a,r,o)),n.delete("/buckets/:bucket",async a=>ue(a,r,o)),n.get("/buckets/:bucket/objects",async a=>le(a,r,o)),n.put("/buckets/:bucket/objects",async a=>de(a,r,o)),n.post("/buckets/:bucket/objects",async a=>pe(a,r,o)),n.delete("/buckets/:bucket/objects",async a=>ye(a,r,o)),n.get("/buckets/:bucket/objects/*",async a=>ge(a,r,o)),Zt({fetch:n.fetch,port:t.server.port||3001,hostname:t.server.host||"localhost"}),console.log(`Storage server started on ${t.server.host||"localhost"}:${t.server.port||3001}`),n}var wr=process.argv.slice(2),be=wr.find(t=>t.startsWith("--port=")),vr=be?parseInt(be.split("=")[1],10):3001,we=te(),xr={molnos:{dataPath:we.molnos.dataPath},storage:{},server:{port:vr,host:we.server.host}};br(xr);export{br as startServer};
|
package/package.json
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "molnos",
|
|
3
|
+
"description": "The core API for MolnOS.",
|
|
4
|
+
"version": "1.0.3",
|
|
5
|
+
"author": "MolnOS",
|
|
6
|
+
"license": "COMMERCIAL",
|
|
7
|
+
"keywords": [],
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "dist/molnos_core.mjs",
|
|
10
|
+
"bin": {
|
|
11
|
+
"molnos": "dist/bin.mjs"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/mikaelvesavuori/molnos-core"
|
|
16
|
+
},
|
|
17
|
+
"bugs": {
|
|
18
|
+
"url": "https://github.com/mikaelvesavuori/molnos-core/issues"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/mikaelvesavuori/molnos-core",
|
|
21
|
+
"files": [
|
|
22
|
+
"/dist",
|
|
23
|
+
"!/dist/**/*.map",
|
|
24
|
+
"!/tests"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"start": "bash clean-build.sh && npm run build:local && npx tsx src/index.ts",
|
|
28
|
+
"start:clean": "npm run build:services && rm -f management-db.json && rm -rf molnosdb && npx tsx src/index.ts",
|
|
29
|
+
"start:docker": "docker run -d -v $(pwd)/molnos.config.json:/app/molnos.config.json:ro -p 3000:3000 --name molnos ghcr.io/molnos/molnos-core:latest",
|
|
30
|
+
"inspect": "docker run --rm -it -v $(pwd)/molnos.config.json:/app/molnos.config.json:ro ghcr.io/molnos/molnos-core:latest sh",
|
|
31
|
+
"build": "npm run clean && node esbuild.config.mjs --esm && cp src/bin.ts dist/bin.mjs && chmod +x dist/bin.mjs",
|
|
32
|
+
"build:docker": "docker build -t ghcr.io/molnos/molnos-core:$(node -p \"require('./package.json' with { type: 'json' };).version\") -t ghcr.io/molnos/molnos-core:latest .",
|
|
33
|
+
"push:docker": "docker push ghcr.io/molnos/molnos-core:$(node -p \"require('./package.json' with { type: 'json' };).version\") && docker push ghcr.io/molnos/molnos-core:latest",
|
|
34
|
+
"build:local": "npm run build && cp dist/*.mjs .",
|
|
35
|
+
"build:examples": "npx esbuild examples/function-with-import.mjs --bundle --outfile=examples/function-with-import-bundled.mjs --platform=node --format=esm",
|
|
36
|
+
"test": "npm run lint && npm run test:unit",
|
|
37
|
+
"test:unit": "npx vitest run --coverage",
|
|
38
|
+
"test:watch": "npx vitest --watch",
|
|
39
|
+
"docs": "npm run docs:licenses",
|
|
40
|
+
"docs:licenses": "npx license-checker-rseidelsohn --production --plainVertical --excludePackagesStartingWith \"molnos;esbuild;@esbuild\" --out oss-licenses.txt",
|
|
41
|
+
"sbom": "syft file:package-lock.json --output spdx-json > ./sbom.json",
|
|
42
|
+
"scan": "grype ./sbom.json -o json",
|
|
43
|
+
"licenses": "grant check sbom.json --config .grant.yaml",
|
|
44
|
+
"release": "bash release.sh",
|
|
45
|
+
"clean": "rm -rf lib && rm -rf dist && mkdir lib",
|
|
46
|
+
"clean:processes": "lsof -ti:3000,3001,3002,3003,3004,3005 | xargs kill -9 2>/dev/null; sleep 2",
|
|
47
|
+
"lint": "npx @biomejs/biome check --write ./src",
|
|
48
|
+
"package": "npm pack",
|
|
49
|
+
"prepublishOnly": "npm run build",
|
|
50
|
+
"prepare": "husky",
|
|
51
|
+
"tunnel": "cloudflared tunnel --url http://localhost:3000"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@biomejs/biome": "2",
|
|
55
|
+
"@types/node": "latest",
|
|
56
|
+
"@vitest/coverage-v8": "4",
|
|
57
|
+
"esbuild": "latest",
|
|
58
|
+
"html-minifier-terser": "7",
|
|
59
|
+
"http-server": "14",
|
|
60
|
+
"husky": "9",
|
|
61
|
+
"license-checker-rseidelsohn": "4",
|
|
62
|
+
"lightningcss": "1",
|
|
63
|
+
"tsup": "8",
|
|
64
|
+
"tsx": "4",
|
|
65
|
+
"typescript": "5",
|
|
66
|
+
"vitest": "4"
|
|
67
|
+
},
|
|
68
|
+
"dependencies": {
|
|
69
|
+
"@hono/node-server": "1",
|
|
70
|
+
"hono": "4",
|
|
71
|
+
"mikroauth": "1",
|
|
72
|
+
"mikroconf": "1",
|
|
73
|
+
"mikrodb": "1",
|
|
74
|
+
"mikroevent": "1",
|
|
75
|
+
"mikroid": "1",
|
|
76
|
+
"mikropermit": "1",
|
|
77
|
+
"mikrovalid": "1",
|
|
78
|
+
"pikodb": "1"
|
|
79
|
+
}
|
|
80
|
+
}
|