miolo 0.9.22 → 0.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1168,8 +1168,6 @@ var geoip_localize_ip = function geoip_localize_ip(ip, config, logger) {
1168
1168
  if (logger === void 0) {
1169
1169
  logger = console;
1170
1170
  }
1171
- console.log(_geoip_local_ips);
1172
- console.log(ip);
1173
1171
  if (_geoip_local_ips.indexOf(ip) >= 0) {
1174
1172
  return {
1175
1173
  local: true,
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * @license MIT
10
10
  */
11
- import e from"node:http";import r from"koa";import{createHttpTerminator as o}from"http-terminator";import t from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import l from"nodemailer";import{uncolor as u,gray as c,magenta as s,cyan as d,yellow as f,red_light as v,red as p,cyan_light as m,green as h,blue as y,green_bold as g,yellow_bold as b}from"tinguir";import S,{promisify as E}from"node:util";import _,{transports as x,createLogger as w,format as k}from"winston";import R from"koa-better-body";import O from"koa-convert";import q from"koa-compress";import{constants as C}from"node:zlib";import M from"koa-mount";import j from"koa-static";import J from"koa-favicon";import{performance as T}from"node:perf_hooks";import A,{readFileSync as L}from"node:fs";import{Reader as P}from"@maxmind/geoip2-node";import U from"@koa/router";import N from"jwt-simple";import z from"koa-passport";import F from"passport-local";import V from"koa-session";import B from"koa-redis";import D from"@koa/cors";import I from"koa-proxies";import G from"qs";import{renderToString as W}from"react-dom/server";import{CronJob as Y}from"cron";import K from"node:os";import H from"diskspace";import X from"redis";function Z(e,r){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),o.push.apply(o,t)}return o}function Q(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?Z(Object(o),!0).forEach((function(r){re(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):Z(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function $(e,r,o,t,n,i,a){try{var l=e[i](a),u=l.value}catch(c){return void o(c)}l.done?r(u):Promise.resolve(u).then(t,n)}function ee(e){return function(){var r=this,o=arguments;return new Promise((function(t,n){var i=e.apply(r,o);function a(e){$(i,t,n,a,l,"next",e)}function l(e){$(i,t,n,a,l,"throw",e)}a(void 0)}))}}function re(e,r,o){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var t=o.call(e,r||"default");if("object"!=typeof t)return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"==typeof r?r:String(r)}(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var oe=i(import.meta.url),te=n.dirname(oe),ne={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(te,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,request:{lazy:1,slow:2,onStart:void 0,onDone:void 0,geoip:{enabled:!1,db:"/var/lib/GeoIP/GeoLite2-City.mmdb",local_ips:["127.0.0.1"]}}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:864e5,secure:!0,sameSite:null}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{log:"silly",tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0,level:"silly"},file:{enabled:!0,level:"silly",filename:"/var/log/miolo.log"},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},mail:{silent:!0,options:{port:25,host:"mail.com",authMethod:"PLAIN",secure:!1,tls:{rejectUnauthorized:!1},logger:!1,debug:!1},defaults:{name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},auth:{},render:{},middlewares:[],cron:[]};function ie(e){var{options:r,defaults:o,silent:t}=e,n=l.createTransport(r,o);function i(){return(i=ee((function*(e){if(!0===t)return console.info("*********************************"),console.info("This mail will not be send (emailing is disabled):"),console.info(e),console.info("*********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var r=n.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(o){return{error:o,ok:!1}}}))).apply(this,arguments)}var a={send:function(e){return i.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),n.verify((function(e,r){e?(console.error("[miolo][Verify][MAILER] Verifying ERROR"),console.error(e)):console.info("[miolo][Verify][MAILER] Verifyed OK: Server is ready to take our messages")}))},options:r,defaults:o,silent:t};return a}var{combine:ae,timestamp:le,_label:ue,printf:ce,errors:se}=k,de=function(e,r){var o,t,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",i={silly:c,debug:s,verbose:d,info:f,warn:v,error:p},a={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},l=ce((r=>{var o,t=i[r.level],l=new Date(r.timestamp).toLocaleString((null==e||null===(o=e.format)||void 0===o?void 0:o.locale)||"en"),u="[".concat(n,"] ").concat(t(l)," ").concat(t(a[r.level])," ").concat(r.message);return r.stack?"".concat(u,"\n").concat(r.stack):u})),m=[];e.console.enabled&&m.push(new x.Console({humanReadableUnhandledException:!0,level:(null==e||null===(o=e.console)||void 0===o?void 0:o.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));e.file.enabled&&m.push(new x.File({filename:e.file.filename,level:(null==e||null===(t=e.file)||void 0===t?void 0:t.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(e.mail.enabled){var h=function(e,r){var o=function(o){_.Transport.call(this,o),o=o||{},this.level=e.level||"info",this.ename=(null==e?void 0:e.name)||r.defaults.name,this.to=e.to||r.defaults.to,this.from=e.from||r.defaults.from,this.humanReadableUnhandledException=o.humanReadableUnhandledException||!0,this.handleExceptions=o.handleExceptions||!0,this.json=o.json||!1,this.colorize=o.colorize||!1};return S.inherits(o,_.Transport),o.prototype.name="MailerLogger",o.prototype.log=function(o,t){var n=this,i="";try{i=o.message.split("\n")[0]}catch(c){i=o.message.toString()}i=u(i);var a=e.name+": ["+o.level.toUpperCase()+"] "+i,l={from:this.from,to:this.to,subject:a,text:u(o.message)};r.send(l,(function(){n.emit("logged"),t(null,!0)}))},o}(e.mail,r);x.MailerLogger=h,m.push(new x.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return w({level:(null==e?void 0:e.level)||"silly",format:ae(se({stack:!0}),le(),l),transports:m})},fe=(e,r)=>{var o=ie(r.mail),t=de(r.log,o,null==r?void 0:r.name),n=Q(Q({},r.db.options),{},{log:t}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:Q({},r),emailer:o,logger:t,db:i};function u(){return(u=ee((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return u.apply(this,arguments)})),e.context.miolo=l},ve=[401];var pe=i(import.meta.url),me=n.dirname(pe),he=n.resolve(me,"./miolo.ico"),ye=n.resolve(me,"../../../.."),ge=void 0,be=["127.0.0.1"];var Se=function(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(console.log(be),console.log(e),be.indexOf(e)>=0)return{local:!0,country:"",city:""};try{var t,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/var/lib/GeoIP/GeoLite2-City.mmdb",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["127.0.0.1"],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;try{if(null!=ge)return ge;be=[...be,...r||[]];var t=A.readFileSync(e);return ge=P.openBuffer(t)}catch(n){return o.error("[geoip] Error initing:"),void o.error(n)}}(null==r?void 0:r.db,null==r?void 0:r.local_ipds,o),i=n.city(e);return{country:i.country.isoCode,city:null===(t=i.city)||void 0===t||null===(t=t.names)||void 0===t?void 0:t.en}}catch(a){o.error("[geoip] Error localizing IP ".concat(e,":")),o.error(a)}return{country:"",city:""}},Ee={total:0};var _e=i(import.meta.url),xe=n.dirname(_e),we=L(n.resolve(xe,"./robots.txt"),"utf8");var ke=(e,r,o)=>{var t=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(o||{})}catch(n){}return function(e,r){var o=Math.random().toString(),t=null==e?void 0:e.secret;t||(t="miolo_unsafe_secret",r.error("Guest token made with an unsafe secret string. Please, configure your own through session.secret."));var n={admin:!1,buid:o};return N.encode(n,t)}(o||{},t)};function i(){return i=ee((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),t.debug("Guest token conceeded"));var a=function(e){var r,o=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(o)&&(o=86400);var t=new Date;return t.setSeconds(t.getSeconds()+o),{expires:t,httpOnly:!1}}(o);e.cookies.set("token",i,a),e.session={user:{name:"guest"},authenticated:!0,token:i},yield r()})),i.apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))},Re=(e,r)=>{var{auth_user:o,realm:t,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=ee((function*(r,n){var i;try{i=(e=>{var r,o=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(o)try{o=o.replace("Basic ","");try{o=Buffer.from(o,"base64").toString()}catch(i){o=atob(o)}var[t,n]=o.split(":");return{username:t,password:n}}catch(i){return}})(r.request)}catch(u){}var a=()=>{r.session={user:void 0,authenticated:!1},r.body={user:void 0,authenticated:!1},r.response.status=401,r.response.headers["WWW-Authenticate"]='Basic realm="'+t.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield o(i.username,i.password,e.context.miolo);if(!1===l||null==l)return a();r.session={user:l,authenticated:!0},yield n()}))).apply(this,arguments)}t||(t="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(M(r,i))))},Oe=new B;var qe=(e,r,o)=>r(null,e.id),Ce=(e,r,o)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},Me=(e,r,o,t)=>{o(Error("You need to define auth.passport.local_auth_user"),null)},je=(e,r,o)=>{var{get_user_id:t,find_user_by_id:n,local_auth_user:i,url_login:a,url_logout:l,url_login_redirect:u,url_logout_redirect:c}=r,s=t||qe,d=n||Ce,f=i||Me,v=a||"/login",p=l||"/logout",m=new F.Strategy(((r,o,t)=>{f(r,o,t,e.context.miolo)}));function h(){return(h=ee((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(o){}yield r()}))).apply(this,arguments)}!function(e,r){e.keys=[r.secret||"*secret*"];var o=Q({store:Oe},r.options||{});e.use(V(o,e))}(e,o),z.serializeUser(((r,o)=>{process.nextTick((function(){s(r,o,e.context.miolo)}))})),z.deserializeUser(((r,o)=>{process.nextTick((function(){d(r,o,e.context.miolo)}))})),z.use(m),e.use(z.initialize()),e.use(z.session()),e.use((function(e,r){return h.apply(this,arguments)}));var y=function(){var e=ee((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,yield e.logout(),e.body={user:void 0,authenticated:!1},null!=c&&e.redirect(c)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,o){return e.apply(this,arguments)}}(),g=new U;g.post(v,((e,r)=>z.authenticate("local",function(){var r=ee((function*(r,o,t,n){if(!1!==o)return e.session.user=e.state.user,e.session.authenticated=!0,e.body={user:o,authenticated:!0},null!=u&&e.redirect(u),yield e.login(o);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:t,error:r},e.response.status=401}));return function(e,o,t,n){return r.apply(this,arguments)}}())(e))),g.get(p,y),g.post(p,y),e.use(g.routes())},Je=(e,r,o)=>{try{var t=e[r];if(null!=t&&0!=t)return o(t)}catch(n){}},Te=(e,r)=>{var o=e.context.miolo.logger;Je(r,"cors",(r=>{if("simple"==r)o.debug("Setting CORS the simple way"),e.use(function(){var e=ee((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,o){return e.apply(this,arguments)}}());else{var t=(e=>"object"==typeof e?e:{})(r);o.debug("Setting CORS headers for ".concat(JSON.stringify(t))),e.use(D(t))}})),Je(r,"proxy",(r=>{var[t,n]=(e=>{var r,o,t,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(o=e)||void 0===o?void 0:o.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(t=e)||void 0===t?void 0:t.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);o.debug("Setting Proxy for ".concat(t," to ").concat(n.target," ")),e.use(I(t,n))}))},Ae=function(){var e=ee((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Le=function(){var e=ee((function*(e,r){return r}));return function(r,o){return e.apply(this,arguments)}}(),Pe={require:!1,action:"redirect",redirect_url:"/",error_code:401},Ue={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Ne=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var o=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.bodyField)||(null==e?void 0:e.bodyField),a=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ae,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Le,u=t(Pe,(null==e?void 0:e.auth)||{},(null==r?void 0:r.auth)||{}),c=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var f={name:d.name,url:(null==d?void 0:d.url)||d.name,mode:(null==d?void 0:d.mode)||"rw",bodyField:(null==d?void 0:d.bodyField)||i,useUserFields:t(Ue,(null==d?void 0:d.useUserFields)||{}),auth:t(u,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};c.push(f)}}c.length>0&&o.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),o};function ze(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?G.parse(r):{}}function Fe(e,r,o,t){o.map((o=>{var n=o.prefix;o.routes.map((o=>{var i=e.getModel(o.name);if(i){for(var a=function(){var e=ee((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=o.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(t.error("[miolo-router] Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(t.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(t.error("[miolo-router] Crud path ".concat(o.url," specified auth but no action")),e.body={})),i)}));return function(r,o){return e.apply(this,arguments)}}(),l=function(){var e=ee((function*(e,r,n){var i,l={};try{var u;if(!(yield a(e,r)))return void(e.body={});var c=!0;if(null!=o&&o.before&&(c=yield o.before(e)),!c)return void(e.body={});var s=null==e||null===(u=e.session)||void 0===u||null===(u=u.user)||void 0===u?void 0:u.id,d={};!0===o.useUserFields.use&&(d=o.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield n(f),null!=o&&o.after&&(l=yield o.after(e,l))}catch(v){t.error("[miolo-router] Unexpected error on CRUD ".concat(o.name,"-").concat(r)),t.error(v)}i=l,l=null==o.bodyField?i:{[o.bodyField]:i},e.body=l}));return function(r,o,t){return e.apply(this,arguments)}}(),u=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.read(o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.keyList(o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.find(o.id,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.distinct(o.distinct_field,o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=ee((function*(e){yield l(e,"w",function(){var r=ee((function*(r){var o,t=e.request.fields;null!=r&&null!==(o=r.fieldNames)&&void 0!==o&&o.created_by&&(t[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(t,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=ee((function*(e){yield l(e,"w",function(){var r=ee((function*(r){var o,t=e.request.fields;null!=r&&null!==(o=r.fieldNames)&&void 0!==o&&o.last_update_by&&(t[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(t,{id:t.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=function(){var e=ee((function*(e){yield l(e,"w",function(){var r=ee((function*(r){var o=e.request.fields,t={transaction:void 0};return yield i.delete({id:o.id},t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=n?"/".concat(n,"/").concat(o.url):"/".concat(o.url);m.indexOf("//")>=0;)m=m.replace(/\/\//g,"/");t.info("[miolo-router] Routing table ".concat(o.name," to ").concat(m));var h=o.mode.indexOf("r")>=0,y=o.mode.indexOf("w")>=0,g=o.mode.indexOf("u")>=0||y;h&&(r.get("".concat(m,"/find"),(e=>s(e))),r.get("".concat(m,"/read"),(e=>u(e))),r.get("".concat(m,"/distinct"),(e=>d(e))),r.get("".concat(m,"/key_list"),(e=>c(e)))),g&&(r.post("".concat(m,"/save"),(e=>f(e))),r.post("".concat(m,"/update"),(e=>v(e)))),y&&r.post("".concat(m,"/delete"),(e=>p(e)))}else t.error("[miolo-router] Could not get model for ".concat(o.name))}))}))}var Ve=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var o=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ae,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Le,l=t(Pe,(null==r?void 0:r.auth)||{},(null==e?void 0:e.auth)||{}),u=[];for(var c of n)if(c.url&&c.callback){var s={url:c.url,method:(null==c?void 0:c.method)||"GET",callback:c.callback,auth:t(l,(null==c?void 0:c.auth)||{}),before:(null==c?void 0:c.before)||i,after:(null==c?void 0:c.after)||a};u.push(s)}o.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),o};function Be(e,r,o){var t=e.context.miolo.logger,n=new U;try{var i=Ne(o),a=Ve(o),l=i.length>0,u=a.length>0;if(!l&&!u)throw"[miolo-router] Could not get any route from the passed <routes> param";l&&Fe(r,n,i,t),u&&function(e,r,o){r.map((r=>{var t=r.prefix;r.routes.map((r=>{for(var n,i=t?"/".concat(t,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");o.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i));var a=function(){var e=ee((function*(e){var t,n=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"POST"===r.method)||(n||("error"==i.action?(o.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(o.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(o.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=ee((function*(e){var t={};try{try{var n;if("GET"==r.method&&(null===(n=e.request)||void 0===n||!n.fields)&&e.request.url.indexOf("?")>0){var i=ze(e.request.url);i&&(e.request.fields=i)}}catch(u){o.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield a(e)))return;var l=!0;if(null!=r&&r.before&&(l=yield r.before(e)),!l)return;t=yield r.callback(e),null!=r&&r.after&&(t=yield r.after(e,t))}catch(c){o.error("[miolo-router] Unexpected error on Query ".concat(r.name)),o.error(c)}return t}));return function(r){return e.apply(this,arguments)}}(),u=r.method.toLowerCase();e[u](i,(e=>l(e,r)))}))}))}(n,a,t)}catch(c){t.error(c),t.error("[miolo-router] Error initing the router. Probably config objects are not ok"),t.error("[miolo-router] connOrConfig:"),t.error(null==r?void 0:r.config),t.error("[miolo-router] routes:"),t.error(o)}e.use(n.routes())}var De=i(import.meta.url),Ie=n.dirname(De),Ge=L(n.resolve(Ie,"fallback_index.html"),"utf8");function We(e){return e?e/1e6:0}function Ye(e){return e?e/1e6:0}function Ke(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var o,t,n,i;o=e.logger,t=Math.round(We(K.freemem()),2),n=Math.round(We(K.totalmem()),2),(i=Math.round(100*t/n,2))>80?o.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")):o.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")),H.check("/",(function(e,r){var t=Math.round(Ye(r.used),2),n=Math.round(Ye(r.total),2),i=Math.round(Ye(r.free),2);i<1?o.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)")):o.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function He(e,r){var o=e.context.miolo,t=o.logger,n=[Ke(),...r||[]],i=[];n.map((e=>{var r=e.name,t=function(e,r){var o,t=e.logger,n=null!=r&&null!==(o=r.onTick)&&void 0!==o&&o.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new Y((null==r?void 0:r.cronTime)||"*/5 * * * *",(o=>{try{t.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,o)}catch(n){t.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),t.error(n)}}),(()=>{if(t.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(o){t.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),t.error(o)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(o,e);i.push({name:r,job:t,running:!0===(null==e?void 0:e.start)})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||t.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,t.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){t.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),t.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,t.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(g("manually started!")))}catch(r){t.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),t.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function Xe(n,i){var a,l,u=new r,c=function(e){var r,o=t(ne,e);return o.auth_type=function(e){var r,o,t;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.credentials?"credentials":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.custom?"custom":"guest"}(e),o.use_catcher=!(null==o||null===(r=o.http)||void 0===r||!r.catcher_url),o}(n);fe(u,c),Te(u,c.http),(e=>{e.use(q({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:C.Z_SYNC_FLUSH},deflate:{flush:C.Z_SYNC_FLUSH},br:!1})),e.use(O(R({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(u),function(e){var r=e.context.miolo.logger;function o(){return(o=ee((function*(e){if(e){var o=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof o&&(o=500):(o=406,e.message="Unsupported type"),ve.indexOf(o)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(o,": ").concat(e.message)):r.error(e),this.headerSent||!this.writable)return r.debug("headers were already sent, returning early"),void(e.headerSent=!0);this.type="json",this.status=o,this.body=JSON.stringify(this.body||"",null,2),this.length=Buffer.byteLength(this.body),this.res.end(this.body)}}))).apply(this,arguments)}e.context.onerror=function(e){return o.apply(this,arguments)}}(u),((e,r)=>{var{favicon:o,folders:t}=r,n=o||he;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(ye,""))),e.use(J(n)),Object.entries(t)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(ye,""))),e.use(M(i,j(a,{index:!1})))})(u,null===(a=c.http)||void 0===a?void 0:a.static),function(e,r){var o=function(){var e=ee((function*(e,r){return{}}));return function(r,o){return e.apply(this,arguments)}}(),t=function(){var e=ee((function*(e,r,o){}));return function(r,o,t){return e.apply(this,arguments)}}(),n={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2,onStart:(null==r?void 0:r.onStart)||o,onDone:(null==r?void 0:r.onDone)||t,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=ee((function*(e,r){var o,t,i,a,l,u,c=e.miolo.logger,v=e.headers["x-real-ip"]||"127.0.0.1",y=T.now();e.request.body=Q(Q({},e.request.fields),e.request.files),Ee.total+=1,Ee[v]=(Ee[v]||0)+1,e.requestId=Ee.total,e.request.ip=v;var g=!0===(null==n||null===(o=n.geoip)||void 0===o?void 0:o.enabled),b={};g&&(b=Se(v,n.geoip,c)),e.request.geoip=b;var S=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,E=g?!0===(null===(t=b)||void 0===t?void 0:t.local)?"":null!==(i=b)&&void 0!==i&&i.country?null!==(a=b)&&void 0!==a&&a.city?" (".concat(null===(l=b)||void 0===l?void 0:l.city,", ").concat(b.country,")"):" (".concat(b.country,")"):"":"",_="".concat(s(v)).concat(E," ").concat(d(e.request.method)," ").concat(d(S)," [").concat(m(Ee[v]),"/").concat(m(e.requestId),"]"),x=null!=e.request.body?JSON.stringify(e.request.body):"";c.info("".concat(_," - START")),c.debug("".concat(_," - Body: ").concat(x));var w=yield n.onStart(e,{started:y,description:"pending"});yield r();var k=null==e||null===(u=e.session)||void 0===u?void 0:u.user,R="";null!=k&&(null!=k&&k.id?R=" - uid ".concat(null==k?void 0:k.id):null!=k&&k.token&&(R=" - token ".concat(null==k?void 0:k.token)));var O,q=e.response.status,C=q;200==q?O=h:q>200&&q<=299?(O=f,e.response.redirected&&e.response.url&&(C+=" -> ".concat(e.response.url))):O=p;var M="[".concat(O(C),"]"),j=parseFloat((T.now()-y)/1e3).toFixed(2),J=j<n.lazy?h:j<n.slow?f:p,A=j<n.lazy?"Ok":j<n.slow?"lazy":"slow",L=null!=e.session?JSON.stringify(e.session):"";c.debug("".concat(_," - Session: ").concat(L));var P=null!=e.body?JSON.stringify(e.body):"";c.debug("".concat(_," - Response: ").concat(P)),yield n.onDone(e,w,{started:y,elapsed:j,description:A}),c.info("".concat(_," - DONE ").concat(M).concat(R," (").concat(J(A),": ").concat(J(j),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(u,null==c||null===(l=c.http)||void 0===l?void 0:l.request),function(e){function r(){return(r=ee((function*(e){e.body=we}))).apply(this,arguments)}var o=new U;o.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(o.routes())}(u),c.use_catcher&&function(e,r){function o(){return o=ee((function*(e){var{error:r,warning:o,path:t,agent:n}=e.request.body,i=e.miolo.logger;if(o){var a="".concat(f("[JS Warning]")," on ").concat(y(t),": ").concat(o.msg,"\n")+"".concat(f("[JS Warning]")," File => ").concat(o.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(o.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(o.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(o.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(p("[JS Error]")," on ").concat(y(t),": ").concat(r.msg,"\n")+"".concat(p("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(p("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(p("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(p("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(p("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),o.apply(this,arguments)}var t=new U;t.post(r,(function(e){return o.apply(this,arguments)})),e.use(t.routes())}(u,c.http.catcher_url),"guest"==c.auth_type&&ke(u,c.auth.guest,null==c?void 0:c.session),"basic"==c.auth_type&&Re(u,c.auth.basic),"credentials"==c.auth_type&&je(u,c.auth.credentials,null==c?void 0:c.session),"custom"==c.auth_type&&((e,r)=>{var o=e.context.miolo.logger;try{var t=r(e);if("function"==typeof t)e.use(t);else if(Array.isArray(t)){var n=new U;t.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){o.error("Custom auth error: ".concat(i,"'"))}})(u,c.auth.custom);var v=null==c?void 0:c.middlewares;if(v&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(u,v),null!=c&&c.routes){var g=u.context.miolo.db.getConnection();Be(u,g,c.routes)}null!=(null==i?void 0:i.middleware)?u.use(i.middleware):function(e,r,o,t){var n=(null==r?void 0:r.html)||Ge;n.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),n.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var i=function(){var e=ee((function*(e){var o={};try{var t;null!=r&&null!==(t=r.ssr)&&void 0!==t&&t.loader&&(o=yield r.ssr.loader(e))}catch(u){var n,i="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(n=e.request)||void 0===n?void 0:n.fields)||{})),a=null!=u&&u.stack?"".concat(u.toString(),"\n").concat(u.stack):u.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return o}));return function(r){return e.apply(this,arguments)}}(),a=(e,r,o)=>{var t,n,i=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:o,extra:null==e?void 0:e.extra}},l=(e,o)=>{var t="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?t=W(r.ssr.renderer(e,o)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware)"),e.miolo.logger.error(a),t="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(o,null,2)).replace("{children}",t)};function u(){return(u=ee((function*(e){var r,n,u={hostname:null==o?void 0:o.hostname,port:null==o?void 0:o.port,catcher_url:null==o?void 0:o.catcher_url,login_url:null==t||null===(r=t.credentials)||void 0===r?void 0:r.url_login,logout_url:null==t||null===(n=t.credentials)||void 0===n?void 0:n.url_logout},c=yield i(e),s=a(e,u,c),d=l(e,s);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(d,"utf8")," bytes")),e.body=d}))).apply(this,arguments)}e.use((function(e){return u.apply(this,arguments)}))}(u,i,c.http,null==c?void 0:c.auth);var b=function(){var r=ee((function*(){var r=e.createServer(u.callback());yield((e,r,o)=>new Promise(((t,n)=>{e.listen(r,o,(e=>{e?n(e):t()}))})))(r,c.http.port,c.http.hostname),u.context.miolo.logger.info("miolo is listening on ".concat(c.http.hostname,":").concat(c.http.port)),u.server=r;var t=o({server:r});return u.stop_server=ee((function*(){yield t.terminate(),u.context.miolo.logger.info("miolo has been shutdowned from ".concat(c.http.hostname,":").concat(c.http.port))})),He(u,null==c?void 0:c.cron),u}));return function(){return r.apply(this,arguments)}}();return u.run=b,u}function Ze(e){var r=X.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(s("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof X.ReplyError?"".concat(s("REDIS")," ").concat(p("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(p("Error "+e.code)," ").concat(e.toString())}catch(o){r="".concat(s("REDIS")," ").concat(p("Error ")," ").concat(o)}console.error(r)})),o=E(r.get).bind(r),t=E(r.exists).bind(r),n=E(r.set).bind(r),i=E(r.del).bind(r);function a(){return(a=ee((function*(e){return yield o(e)}))).apply(this,arguments)}function l(){return(l=ee((function*(e){return 1==(yield t(e))}))).apply(this,arguments)}function u(){return u=ee((function*(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",o))})),u.apply(this,arguments)}function c(){return(c=ee((function*(e){return(yield i(e))>=1}))).apply(this,arguments)}var d={get:function(e){return a.apply(this,arguments)},exists:function(e){return l.apply(this,arguments)},set:function(e,r){return u.apply(this,arguments)},del:function(e){return c.apply(this,arguments)}};return d}export{Xe as miolo,Ze as miolo_cacher,ie as miolo_emailer,de as miolo_logger};
11
+ import e from"node:http";import r from"koa";import{createHttpTerminator as o}from"http-terminator";import t from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import l from"nodemailer";import{uncolor as u,gray as c,magenta as s,cyan as d,yellow as f,red_light as v,red as p,cyan_light as m,green as h,blue as y,green_bold as g,yellow_bold as b}from"tinguir";import S,{promisify as E}from"node:util";import _,{transports as x,createLogger as w,format as k}from"winston";import R from"koa-better-body";import O from"koa-convert";import q from"koa-compress";import{constants as C}from"node:zlib";import M from"koa-mount";import j from"koa-static";import J from"koa-favicon";import{performance as T}from"node:perf_hooks";import A,{readFileSync as L}from"node:fs";import{Reader as P}from"@maxmind/geoip2-node";import U from"@koa/router";import N from"jwt-simple";import z from"koa-passport";import F from"passport-local";import V from"koa-session";import B from"koa-redis";import D from"@koa/cors";import I from"koa-proxies";import G from"qs";import{renderToString as W}from"react-dom/server";import{CronJob as Y}from"cron";import K from"node:os";import H from"diskspace";import X from"redis";function Z(e,r){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),o.push.apply(o,t)}return o}function Q(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?Z(Object(o),!0).forEach((function(r){re(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):Z(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function $(e,r,o,t,n,i,a){try{var l=e[i](a),u=l.value}catch(c){return void o(c)}l.done?r(u):Promise.resolve(u).then(t,n)}function ee(e){return function(){var r=this,o=arguments;return new Promise((function(t,n){var i=e.apply(r,o);function a(e){$(i,t,n,a,l,"next",e)}function l(e){$(i,t,n,a,l,"throw",e)}a(void 0)}))}}function re(e,r,o){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var o=e[Symbol.toPrimitive];if(void 0!==o){var t=o.call(e,r||"default");if("object"!=typeof t)return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===r?String:Number)(e)}(e,"string");return"symbol"==typeof r?r:String(r)}(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var oe=i(import.meta.url),te=n.dirname(oe),ne={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(te,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,request:{lazy:1,slow:2,onStart:void 0,onDone:void 0,geoip:{enabled:!1,db:"/var/lib/GeoIP/GeoLite2-City.mmdb",local_ips:["127.0.0.1"]}}},session:{salt:"SUPER_SALTY_YES?",secret:"SUPER_SECRET_KEY_KERE",options:{maxAge:864e5,secure:!0,sameSite:null}},db:{config:{dialect:"postgres",host:"localhost",port:5432,database:"miolo",user:"postgres",password:"postgres",max:5,min:0,idleTimeoutMillis:1e4},options:{log:"silly",tables:[]}},routes:{bodyField:void 0,crud:[{prefix:"",routes:[]}],queries:[]},log:{level:"debug",format:{locale:"en-GB"},console:{enabled:!0,level:"silly"},file:{enabled:!0,level:"silly",filename:"/var/log/miolo.log"},mail:{enabled:!1,level:"warn",name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},mail:{silent:!0,options:{port:25,host:"mail.com",authMethod:"PLAIN",secure:!1,tls:{rejectUnauthorized:!1},logger:!1,debug:!1},defaults:{name:"miolo",from:"miolo@mail.com",to:"errors@mail.com"}},auth:{},render:{},middlewares:[],cron:[]};function ie(e){var{options:r,defaults:o,silent:t}=e,n=l.createTransport(r,o);function i(){return(i=ee((function*(e){if(!0===t)return console.info("*********************************"),console.info("This mail will not be send (emailing is disabled):"),console.info(e),console.info("*********************************"),{ok:!0,silent:!0,error:void 0,messageId:void 0};try{var r=n.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(o){return{error:o,ok:!1}}}))).apply(this,arguments)}var a={send:function(e){return i.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),n.verify((function(e,r){e?(console.error("[miolo][Verify][MAILER] Verifying ERROR"),console.error(e)):console.info("[miolo][Verify][MAILER] Verifyed OK: Server is ready to take our messages")}))},options:r,defaults:o,silent:t};return a}var{combine:ae,timestamp:le,_label:ue,printf:ce,errors:se}=k,de=function(e,r){var o,t,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",i={silly:c,debug:s,verbose:d,info:f,warn:v,error:p},a={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},l=ce((r=>{var o,t=i[r.level],l=new Date(r.timestamp).toLocaleString((null==e||null===(o=e.format)||void 0===o?void 0:o.locale)||"en"),u="[".concat(n,"] ").concat(t(l)," ").concat(t(a[r.level])," ").concat(r.message);return r.stack?"".concat(u,"\n").concat(r.stack):u})),m=[];e.console.enabled&&m.push(new x.Console({humanReadableUnhandledException:!0,level:(null==e||null===(o=e.console)||void 0===o?void 0:o.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));e.file.enabled&&m.push(new x.File({filename:e.file.filename,level:(null==e||null===(t=e.file)||void 0===t?void 0:t.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(e.mail.enabled){var h=function(e,r){var o=function(o){_.Transport.call(this,o),o=o||{},this.level=e.level||"info",this.ename=(null==e?void 0:e.name)||r.defaults.name,this.to=e.to||r.defaults.to,this.from=e.from||r.defaults.from,this.humanReadableUnhandledException=o.humanReadableUnhandledException||!0,this.handleExceptions=o.handleExceptions||!0,this.json=o.json||!1,this.colorize=o.colorize||!1};return S.inherits(o,_.Transport),o.prototype.name="MailerLogger",o.prototype.log=function(o,t){var n=this,i="";try{i=o.message.split("\n")[0]}catch(c){i=o.message.toString()}i=u(i);var a=e.name+": ["+o.level.toUpperCase()+"] "+i,l={from:this.from,to:this.to,subject:a,text:u(o.message)};r.send(l,(function(){n.emit("logged"),t(null,!0)}))},o}(e.mail,r);x.MailerLogger=h,m.push(new x.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return w({level:(null==e?void 0:e.level)||"silly",format:ae(se({stack:!0}),le(),l),transports:m})},fe=(e,r)=>{var o=ie(r.mail),t=de(r.log,o,null==r?void 0:r.name),n=Q(Q({},r.db.options),{},{log:t}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:Q({},r),emailer:o,logger:t,db:i};function u(){return(u=ee((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return u.apply(this,arguments)})),e.context.miolo=l},ve=[401];var pe=i(import.meta.url),me=n.dirname(pe),he=n.resolve(me,"./miolo.ico"),ye=n.resolve(me,"../../../.."),ge=void 0,be=["127.0.0.1"];var Se=function(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(be.indexOf(e)>=0)return{local:!0,country:"",city:""};try{var t,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/var/lib/GeoIP/GeoLite2-City.mmdb",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["127.0.0.1"],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;try{if(null!=ge)return ge;be=[...be,...r||[]];var t=A.readFileSync(e);return ge=P.openBuffer(t)}catch(n){return o.error("[geoip] Error initing:"),void o.error(n)}}(null==r?void 0:r.db,null==r?void 0:r.local_ipds,o),i=n.city(e);return{country:i.country.isoCode,city:null===(t=i.city)||void 0===t||null===(t=t.names)||void 0===t?void 0:t.en}}catch(a){o.error("[geoip] Error localizing IP ".concat(e,":")),o.error(a)}return{country:"",city:""}},Ee={total:0};var _e=i(import.meta.url),xe=n.dirname(_e),we=L(n.resolve(xe,"./robots.txt"),"utf8");var ke=(e,r,o)=>{var t=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(o||{})}catch(n){}return function(e,r){var o=Math.random().toString(),t=null==e?void 0:e.secret;t||(t="miolo_unsafe_secret",r.error("Guest token made with an unsafe secret string. Please, configure your own through session.secret."));var n={admin:!1,buid:o};return N.encode(n,t)}(o||{},t)};function i(){return i=ee((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),t.debug("Guest token conceeded"));var a=function(e){var r,o=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(o)&&(o=86400);var t=new Date;return t.setSeconds(t.getSeconds()+o),{expires:t,httpOnly:!1}}(o);e.cookies.set("token",i,a),e.session={user:{name:"guest"},authenticated:!0,token:i},yield r()})),i.apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))},Re=(e,r)=>{var{auth_user:o,realm:t,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=ee((function*(r,n){var i;try{i=(e=>{var r,o=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(o)try{o=o.replace("Basic ","");try{o=Buffer.from(o,"base64").toString()}catch(i){o=atob(o)}var[t,n]=o.split(":");return{username:t,password:n}}catch(i){return}})(r.request)}catch(u){}var a=()=>{r.session={user:void 0,authenticated:!1},r.body={user:void 0,authenticated:!1},r.response.status=401,r.response.headers["WWW-Authenticate"]='Basic realm="'+t.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield o(i.username,i.password,e.context.miolo);if(!1===l||null==l)return a();r.session={user:l,authenticated:!0},yield n()}))).apply(this,arguments)}t||(t="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(M(r,i))))},Oe=new B;var qe=(e,r,o)=>r(null,e.id),Ce=(e,r,o)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},Me=(e,r,o,t)=>{o(Error("You need to define auth.passport.local_auth_user"),null)},je=(e,r,o)=>{var{get_user_id:t,find_user_by_id:n,local_auth_user:i,url_login:a,url_logout:l,url_login_redirect:u,url_logout_redirect:c}=r,s=t||qe,d=n||Ce,f=i||Me,v=a||"/login",p=l||"/logout",m=new F.Strategy(((r,o,t)=>{f(r,o,t,e.context.miolo)}));function h(){return(h=ee((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(o){}yield r()}))).apply(this,arguments)}!function(e,r){e.keys=[r.secret||"*secret*"];var o=Q({store:Oe},r.options||{});e.use(V(o,e))}(e,o),z.serializeUser(((r,o)=>{process.nextTick((function(){s(r,o,e.context.miolo)}))})),z.deserializeUser(((r,o)=>{process.nextTick((function(){d(r,o,e.context.miolo)}))})),z.use(m),e.use(z.initialize()),e.use(z.session()),e.use((function(e,r){return h.apply(this,arguments)}));var y=function(){var e=ee((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,yield e.logout(),e.body={user:void 0,authenticated:!1},null!=c&&e.redirect(c)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,o){return e.apply(this,arguments)}}(),g=new U;g.post(v,((e,r)=>z.authenticate("local",function(){var r=ee((function*(r,o,t,n){if(!1!==o)return e.session.user=e.state.user,e.session.authenticated=!0,e.body={user:o,authenticated:!0},null!=u&&e.redirect(u),yield e.login(o);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:t,error:r},e.response.status=401}));return function(e,o,t,n){return r.apply(this,arguments)}}())(e))),g.get(p,y),g.post(p,y),e.use(g.routes())},Je=(e,r,o)=>{try{var t=e[r];if(null!=t&&0!=t)return o(t)}catch(n){}},Te=(e,r)=>{var o=e.context.miolo.logger;Je(r,"cors",(r=>{if("simple"==r)o.debug("Setting CORS the simple way"),e.use(function(){var e=ee((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,o){return e.apply(this,arguments)}}());else{var t=(e=>"object"==typeof e?e:{})(r);o.debug("Setting CORS headers for ".concat(JSON.stringify(t))),e.use(D(t))}})),Je(r,"proxy",(r=>{var[t,n]=(e=>{var r,o,t,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(o=e)||void 0===o?void 0:o.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(t=e)||void 0===t?void 0:t.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);o.debug("Setting Proxy for ".concat(t," to ").concat(n.target," ")),e.use(I(t,n))}))},Ae=function(){var e=ee((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Le=function(){var e=ee((function*(e,r){return r}));return function(r,o){return e.apply(this,arguments)}}(),Pe={require:!1,action:"redirect",redirect_url:"/",error_code:401},Ue={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Ne=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var o=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.bodyField)||(null==e?void 0:e.bodyField),a=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ae,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Le,u=t(Pe,(null==e?void 0:e.auth)||{},(null==r?void 0:r.auth)||{}),c=[];for(var s of n){var d="string"==typeof s?{name:s}:s;if(d.name){var f={name:d.name,url:(null==d?void 0:d.url)||d.name,mode:(null==d?void 0:d.mode)||"rw",bodyField:(null==d?void 0:d.bodyField)||i,useUserFields:t(Ue,(null==d?void 0:d.useUserFields)||{}),auth:t(u,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};c.push(f)}}c.length>0&&o.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),o};function ze(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?G.parse(r):{}}function Fe(e,r,o,t){o.map((o=>{var n=o.prefix;o.routes.map((o=>{var i=e.getModel(o.name);if(i){for(var a=function(){var e=ee((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=o.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(t.error("[miolo-router] Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(t.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(t.error("[miolo-router] Crud path ".concat(o.url," specified auth but no action")),e.body={})),i)}));return function(r,o){return e.apply(this,arguments)}}(),l=function(){var e=ee((function*(e,r,n){var i,l={};try{var u;if(!(yield a(e,r)))return void(e.body={});var c=!0;if(null!=o&&o.before&&(c=yield o.before(e)),!c)return void(e.body={});var s=null==e||null===(u=e.session)||void 0===u||null===(u=u.user)||void 0===u?void 0:u.id,d={};!0===o.useUserFields.use&&(d=o.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield n(f),null!=o&&o.after&&(l=yield o.after(e,l))}catch(v){t.error("[miolo-router] Unexpected error on CRUD ".concat(o.name,"-").concat(r)),t.error(v)}i=l,l=null==o.bodyField?i:{[o.bodyField]:i},e.body=l}));return function(r,o,t){return e.apply(this,arguments)}}(),u=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.read(o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.keyList(o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.find(o.id,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=ee((function*(e){yield l(e,"r",function(){var r=ee((function*(r){var o=ze(e.request.url),t={transaction:void 0};return yield i.distinct(o.distinct_field,o,t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=ee((function*(e){yield l(e,"w",function(){var r=ee((function*(r){var o,t=e.request.fields;null!=r&&null!==(o=r.fieldNames)&&void 0!==o&&o.created_by&&(t[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(t,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=function(){var e=ee((function*(e){yield l(e,"w",function(){var r=ee((function*(r){var o,t=e.request.fields;null!=r&&null!==(o=r.fieldNames)&&void 0!==o&&o.last_update_by&&(t[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(t,{id:t.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=function(){var e=ee((function*(e){yield l(e,"w",function(){var r=ee((function*(r){var o=e.request.fields,t={transaction:void 0};return yield i.delete({id:o.id},t)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=n?"/".concat(n,"/").concat(o.url):"/".concat(o.url);m.indexOf("//")>=0;)m=m.replace(/\/\//g,"/");t.info("[miolo-router] Routing table ".concat(o.name," to ").concat(m));var h=o.mode.indexOf("r")>=0,y=o.mode.indexOf("w")>=0,g=o.mode.indexOf("u")>=0||y;h&&(r.get("".concat(m,"/find"),(e=>s(e))),r.get("".concat(m,"/read"),(e=>u(e))),r.get("".concat(m,"/distinct"),(e=>d(e))),r.get("".concat(m,"/key_list"),(e=>c(e)))),g&&(r.post("".concat(m,"/save"),(e=>f(e))),r.post("".concat(m,"/update"),(e=>v(e)))),y&&r.post("".concat(m,"/delete"),(e=>p(e)))}else t.error("[miolo-router] Could not get model for ".concat(o.name))}))}))}var Ve=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var o=[];return r.map((r=>{var n=null==r?void 0:r.routes;if(n&&Array.isArray(n)){var i=(null==r?void 0:r.before)||(null==e?void 0:e.before)||Ae,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Le,l=t(Pe,(null==r?void 0:r.auth)||{},(null==e?void 0:e.auth)||{}),u=[];for(var c of n)if(c.url&&c.callback){var s={url:c.url,method:(null==c?void 0:c.method)||"GET",callback:c.callback,auth:t(l,(null==c?void 0:c.auth)||{}),before:(null==c?void 0:c.before)||i,after:(null==c?void 0:c.after)||a};u.push(s)}o.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),o};function Be(e,r,o){var t=e.context.miolo.logger,n=new U;try{var i=Ne(o),a=Ve(o),l=i.length>0,u=a.length>0;if(!l&&!u)throw"[miolo-router] Could not get any route from the passed <routes> param";l&&Fe(r,n,i,t),u&&function(e,r,o){r.map((r=>{var t=r.prefix;r.routes.map((r=>{for(var n,i=t?"/".concat(t,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");o.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i));var a=function(){var e=ee((function*(e){var t,n=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"POST"===r.method)||(n||("error"==i.action?(o.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(o.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(o.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=ee((function*(e){var t={};try{try{var n;if("GET"==r.method&&(null===(n=e.request)||void 0===n||!n.fields)&&e.request.url.indexOf("?")>0){var i=ze(e.request.url);i&&(e.request.fields=i)}}catch(u){o.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield a(e)))return;var l=!0;if(null!=r&&r.before&&(l=yield r.before(e)),!l)return;t=yield r.callback(e),null!=r&&r.after&&(t=yield r.after(e,t))}catch(c){o.error("[miolo-router] Unexpected error on Query ".concat(r.name)),o.error(c)}return t}));return function(r){return e.apply(this,arguments)}}(),u=r.method.toLowerCase();e[u](i,(e=>l(e,r)))}))}))}(n,a,t)}catch(c){t.error(c),t.error("[miolo-router] Error initing the router. Probably config objects are not ok"),t.error("[miolo-router] connOrConfig:"),t.error(null==r?void 0:r.config),t.error("[miolo-router] routes:"),t.error(o)}e.use(n.routes())}var De=i(import.meta.url),Ie=n.dirname(De),Ge=L(n.resolve(Ie,"fallback_index.html"),"utf8");function We(e){return e?e/1e6:0}function Ye(e){return e?e/1e6:0}function Ke(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var o,t,n,i;o=e.logger,t=Math.round(We(K.freemem()),2),n=Math.round(We(K.totalmem()),2),(i=Math.round(100*t/n,2))>80?o.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")):o.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")),H.check("/",(function(e,r){var t=Math.round(Ye(r.used),2),n=Math.round(Ye(r.total),2),i=Math.round(Ye(r.free),2);i<1?o.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)")):o.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function He(e,r){var o=e.context.miolo,t=o.logger,n=[Ke(),...r||[]],i=[];n.map((e=>{var r=e.name,t=function(e,r){var o,t=e.logger,n=null!=r&&null!==(o=r.onTick)&&void 0!==o&&o.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new Y((null==r?void 0:r.cronTime)||"*/5 * * * *",(o=>{try{t.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,o)}catch(n){t.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),t.error(n)}}),(()=>{if(t.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(o){t.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),t.error(o)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(o,e);i.push({name:r,job:t,running:!0===(null==e?void 0:e.start)})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||t.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,t.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){t.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),t.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,t.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(g("manually started!")))}catch(r){t.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),t.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function Xe(n,i){var a,l,u=new r,c=function(e){var r,o=t(ne,e);return o.auth_type=function(e){var r,o,t;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.credentials?"credentials":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.custom?"custom":"guest"}(e),o.use_catcher=!(null==o||null===(r=o.http)||void 0===r||!r.catcher_url),o}(n);fe(u,c),Te(u,c.http),(e=>{e.use(q({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:C.Z_SYNC_FLUSH},deflate:{flush:C.Z_SYNC_FLUSH},br:!1})),e.use(O(R({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(u),function(e){var r=e.context.miolo.logger;function o(){return(o=ee((function*(e){if(e){var o=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof o&&(o=500):(o=406,e.message="Unsupported type"),ve.indexOf(o)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(o,": ").concat(e.message)):r.error(e),this.headerSent||!this.writable)return r.debug("headers were already sent, returning early"),void(e.headerSent=!0);this.type="json",this.status=o,this.body=JSON.stringify(this.body||"",null,2),this.length=Buffer.byteLength(this.body),this.res.end(this.body)}}))).apply(this,arguments)}e.context.onerror=function(e){return o.apply(this,arguments)}}(u),((e,r)=>{var{favicon:o,folders:t}=r,n=o||he;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(ye,""))),e.use(J(n)),Object.entries(t)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(ye,""))),e.use(M(i,j(a,{index:!1})))})(u,null===(a=c.http)||void 0===a?void 0:a.static),function(e,r){var o=function(){var e=ee((function*(e,r){return{}}));return function(r,o){return e.apply(this,arguments)}}(),t=function(){var e=ee((function*(e,r,o){}));return function(r,o,t){return e.apply(this,arguments)}}(),n={lazy:(null==r?void 0:r.lazy)||1,slow:(null==r?void 0:r.slow)||2,onStart:(null==r?void 0:r.onStart)||o,onDone:(null==r?void 0:r.onDone)||t,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=ee((function*(e,r){var o,t,i,a,l,u,c=e.miolo.logger,v=e.headers["x-real-ip"]||"127.0.0.1",y=T.now();e.request.body=Q(Q({},e.request.fields),e.request.files),Ee.total+=1,Ee[v]=(Ee[v]||0)+1,e.requestId=Ee.total,e.request.ip=v;var g=!0===(null==n||null===(o=n.geoip)||void 0===o?void 0:o.enabled),b={};g&&(b=Se(v,n.geoip,c)),e.request.geoip=b;var S=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,E=g?!0===(null===(t=b)||void 0===t?void 0:t.local)?"":null!==(i=b)&&void 0!==i&&i.country?null!==(a=b)&&void 0!==a&&a.city?" (".concat(null===(l=b)||void 0===l?void 0:l.city,", ").concat(b.country,")"):" (".concat(b.country,")"):"":"",_="".concat(s(v)).concat(E," ").concat(d(e.request.method)," ").concat(d(S)," [").concat(m(Ee[v]),"/").concat(m(e.requestId),"]"),x=null!=e.request.body?JSON.stringify(e.request.body):"";c.info("".concat(_," - START")),c.debug("".concat(_," - Body: ").concat(x));var w=yield n.onStart(e,{started:y,description:"pending"});yield r();var k=null==e||null===(u=e.session)||void 0===u?void 0:u.user,R="";null!=k&&(null!=k&&k.id?R=" - uid ".concat(null==k?void 0:k.id):null!=k&&k.token&&(R=" - token ".concat(null==k?void 0:k.token)));var O,q=e.response.status,C=q;200==q?O=h:q>200&&q<=299?(O=f,e.response.redirected&&e.response.url&&(C+=" -> ".concat(e.response.url))):O=p;var M="[".concat(O(C),"]"),j=parseFloat((T.now()-y)/1e3).toFixed(2),J=j<n.lazy?h:j<n.slow?f:p,A=j<n.lazy?"Ok":j<n.slow?"lazy":"slow",L=null!=e.session?JSON.stringify(e.session):"";c.debug("".concat(_," - Session: ").concat(L));var P=null!=e.body?JSON.stringify(e.body):"";c.debug("".concat(_," - Response: ").concat(P)),yield n.onDone(e,w,{started:y,elapsed:j,description:A}),c.info("".concat(_," - DONE ").concat(M).concat(R," (").concat(J(A),": ").concat(J(j),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(u,null==c||null===(l=c.http)||void 0===l?void 0:l.request),function(e){function r(){return(r=ee((function*(e){e.body=we}))).apply(this,arguments)}var o=new U;o.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(o.routes())}(u),c.use_catcher&&function(e,r){function o(){return o=ee((function*(e){var{error:r,warning:o,path:t,agent:n}=e.request.body,i=e.miolo.logger;if(o){var a="".concat(f("[JS Warning]")," on ").concat(y(t),": ").concat(o.msg,"\n")+"".concat(f("[JS Warning]")," File => ").concat(o.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(o.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(o.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(o.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(p("[JS Error]")," on ").concat(y(t),": ").concat(r.msg,"\n")+"".concat(p("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(p("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(p("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(p("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(p("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),o.apply(this,arguments)}var t=new U;t.post(r,(function(e){return o.apply(this,arguments)})),e.use(t.routes())}(u,c.http.catcher_url),"guest"==c.auth_type&&ke(u,c.auth.guest,null==c?void 0:c.session),"basic"==c.auth_type&&Re(u,c.auth.basic),"credentials"==c.auth_type&&je(u,c.auth.credentials,null==c?void 0:c.session),"custom"==c.auth_type&&((e,r)=>{var o=e.context.miolo.logger;try{var t=r(e);if("function"==typeof t)e.use(t);else if(Array.isArray(t)){var n=new U;t.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){o.error("Custom auth error: ".concat(i,"'"))}})(u,c.auth.custom);var v=null==c?void 0:c.middlewares;if(v&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(u,v),null!=c&&c.routes){var g=u.context.miolo.db.getConnection();Be(u,g,c.routes)}null!=(null==i?void 0:i.middleware)?u.use(i.middleware):function(e,r,o,t){var n=(null==r?void 0:r.html)||Ge;n.indexOf("{context}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {context} template variable"),n.indexOf("{children}")<0&&e.context.miolo.logger.error("Provided HTML for rendering has no {children} template variable");var i=function(){var e=ee((function*(e){var o={};try{var t;null!=r&&null!==(t=r.ssr)&&void 0!==t&&t.loader&&(o=yield r.ssr.loader(e))}catch(u){var n,i="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(n=e.request)||void 0===n?void 0:n.fields)||{})),a=null!=u&&u.stack?"".concat(u.toString(),"\n").concat(u.stack):u.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return o}));return function(r){return e.apply(this,arguments)}}(),a=(e,r,o)=>{var t,n,i=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:o,extra:null==e?void 0:e.extra}},l=(e,o)=>{var t="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?t=W(r.ssr.renderer(e,o)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware)"),e.miolo.logger.error(a),t="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(o,null,2)).replace("{children}",t)};function u(){return(u=ee((function*(e){var r,n,u={hostname:null==o?void 0:o.hostname,port:null==o?void 0:o.port,catcher_url:null==o?void 0:o.catcher_url,login_url:null==t||null===(r=t.credentials)||void 0===r?void 0:r.url_login,logout_url:null==t||null===(n=t.credentials)||void 0===n?void 0:n.url_logout},c=yield i(e),s=a(e,u,c),d=l(e,s);e.miolo.logger.debug("[render-ssr] Returned body is ".concat(Buffer.byteLength(d,"utf8")," bytes")),e.body=d}))).apply(this,arguments)}e.use((function(e){return u.apply(this,arguments)}))}(u,i,c.http,null==c?void 0:c.auth);var b=function(){var r=ee((function*(){var r=e.createServer(u.callback());yield((e,r,o)=>new Promise(((t,n)=>{e.listen(r,o,(e=>{e?n(e):t()}))})))(r,c.http.port,c.http.hostname),u.context.miolo.logger.info("miolo is listening on ".concat(c.http.hostname,":").concat(c.http.port)),u.server=r;var t=o({server:r});return u.stop_server=ee((function*(){yield t.terminate(),u.context.miolo.logger.info("miolo has been shutdowned from ".concat(c.http.hostname,":").concat(c.http.port))})),He(u,null==c?void 0:c.cron),u}));return function(){return r.apply(this,arguments)}}();return u.run=b,u}function Ze(e){var r=X.createClient(e.redis.port,e.redis.host).on("connect",(function(){console.info("".concat(s("REDIS")," Connection established!"))})).on("error",(function(e){var r;try{r=e instanceof X.ReplyError?"".concat(s("REDIS")," ").concat(p("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(p("Error "+e.code)," ").concat(e.toString())}catch(o){r="".concat(s("REDIS")," ").concat(p("Error ")," ").concat(o)}console.error(r)})),o=E(r.get).bind(r),t=E(r.exists).bind(r),n=E(r.set).bind(r),i=E(r.del).bind(r);function a(){return(a=ee((function*(e){return yield o(e)}))).apply(this,arguments)}function l(){return(l=ee((function*(e){return 1==(yield t(e))}))).apply(this,arguments)}function u(){return u=ee((function*(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",o))})),u.apply(this,arguments)}function c(){return(c=ee((function*(e){return(yield i(e))>=1}))).apply(this,arguments)}var d={get:function(e){return a.apply(this,arguments)},exists:function(e){return l.apply(this,arguments)},set:function(e,r){return u.apply(this,arguments)},del:function(e){return c.apply(this,arguments)}};return d}export{Xe as miolo,Ze as miolo_cacher,ie as miolo_emailer,de as miolo_logger};
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.9.22
2
+ * miolo v0.9.23
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -827,8 +827,6 @@ function _geoip_init() {
827
827
  }
828
828
  var geoip_localize_ip = function geoip_localize_ip(ip, config) {
829
829
  var logger = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console;
830
- console.log(_geoip_local_ips);
831
- console.log(ip);
832
830
  if (_geoip_local_ips.indexOf(ip) >= 0) {
833
831
  return {
834
832
  local: true,