miolo 0.7.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -44,6 +44,7 @@ var server = require('react-dom/server');
44
44
  var cron = require('cron');
45
45
  var os = require('node:os');
46
46
  var diskspace = require('diskspace');
47
+ var redis = require('redis');
47
48
 
48
49
  function _regeneratorRuntime() {
49
50
  _regeneratorRuntime = function () {
@@ -712,10 +713,10 @@ function init_config(config) {
712
713
  return all_config;
713
714
  }
714
715
 
715
- function init_emailer(options, defaults, silent) {
716
- if (silent === void 0) {
717
- silent = false;
718
- }
716
+ function init_emailer(_ref) {
717
+ var options = _ref.options,
718
+ defaults = _ref.defaults,
719
+ silent = _ref.silent;
719
720
  var nmailer = nodemailer.createTransport(options, defaults);
720
721
  function send_email(_x) {
721
722
  return _send_email.apply(this, arguments);
@@ -726,7 +727,7 @@ function init_emailer(options, defaults, silent) {
726
727
  return _regeneratorRuntime().wrap(function _callee$(_context) {
727
728
  while (1) switch (_context.prev = _context.next) {
728
729
  case 0:
729
- if (!silent) {
730
+ if (!(silent === true)) {
730
731
  _context.next = 8;
731
732
  break;
732
733
  }
@@ -916,7 +917,7 @@ var init_logger = function init_logger(config, emailer) {
916
917
  };
917
918
 
918
919
  var init_context_middleware = function init_context_middleware(app, config) {
919
- var emailer = init_emailer(config.mail.options, config.mail.defaults);
920
+ var emailer = init_emailer(config.mail);
920
921
  var logger = init_logger(config.log, emailer);
921
922
  var dbOptions = _extends({}, config.db.options, {
922
923
  log: logger
@@ -2917,6 +2918,9 @@ function miolo(sconfig, render) {
2917
2918
  // attach to app some custom miolo methods
2918
2919
  init_context_middleware(app, config);
2919
2920
 
2921
+ // CORS and other headers
2922
+ init_headers_middleware(app, config.http);
2923
+
2920
2924
  // Compress and body parser
2921
2925
  init_body_middleware(app);
2922
2926
 
@@ -2961,9 +2965,6 @@ function miolo(sconfig, render) {
2961
2965
  init_extra_middlewares(app, extra_middlewares);
2962
2966
  }
2963
2967
 
2964
- // CORS and other headers
2965
- init_headers_middleware(app, config.http);
2966
-
2967
2968
  // Routes to /crud
2968
2969
  if (config != null && config.routes) {
2969
2970
  var conn = app.context.miolo.db.getConnection();
@@ -3062,8 +3063,125 @@ function miolo(sconfig, render) {
3062
3063
  return app;
3063
3064
  }
3064
3065
 
3065
- Object.defineProperty(exports, 'getConnection', {
3066
+ function init_cacher(config) {
3067
+ var client = redis.createClient(config.redis.port, config.redis.host).on('connect', function () {
3068
+ console.info(tinguir.magenta('REDIS') + " Connection established!");
3069
+ }).on('error', function (err) {
3070
+ var msg;
3071
+ try {
3072
+ if (err instanceof redis.ReplyError) msg = tinguir.magenta('REDIS') + " " + tinguir.red('Error ' + err.code) + " Command: " + err.command + " " + err.toString();else msg = tinguir.magenta('REDIS') + " " + tinguir.red('Error ' + err.code) + " " + err.toString();
3073
+ } catch (e) {
3074
+ msg = tinguir.magenta('REDIS') + " " + tinguir.red('Error ') + " " + e;
3075
+ }
3076
+ console.error(msg);
3077
+ });
3078
+ var _getKey = util.promisify(client.get).bind(client);
3079
+ var _existsKey = util.promisify(client.exists).bind(client);
3080
+ var _setKey = util.promisify(client.set).bind(client);
3081
+ var _delKey = util.promisify(client.del).bind(client);
3082
+ function redisGet(_x) {
3083
+ return _redisGet.apply(this, arguments);
3084
+ }
3085
+ function _redisGet() {
3086
+ _redisGet = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(key) {
3087
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
3088
+ while (1) switch (_context.prev = _context.next) {
3089
+ case 0:
3090
+ _context.next = 2;
3091
+ return _getKey(key);
3092
+ case 2:
3093
+ return _context.abrupt("return", _context.sent);
3094
+ case 3:
3095
+ case "end":
3096
+ return _context.stop();
3097
+ }
3098
+ }, _callee);
3099
+ }));
3100
+ return _redisGet.apply(this, arguments);
3101
+ }
3102
+ function redisExists(_x2) {
3103
+ return _redisExists.apply(this, arguments);
3104
+ }
3105
+ function _redisExists() {
3106
+ _redisExists = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(key) {
3107
+ var r;
3108
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3109
+ while (1) switch (_context2.prev = _context2.next) {
3110
+ case 0:
3111
+ _context2.next = 2;
3112
+ return _existsKey(key);
3113
+ case 2:
3114
+ r = _context2.sent;
3115
+ return _context2.abrupt("return", r == 1 ? true : false);
3116
+ case 4:
3117
+ case "end":
3118
+ return _context2.stop();
3119
+ }
3120
+ }, _callee2);
3121
+ }));
3122
+ return _redisExists.apply(this, arguments);
3123
+ }
3124
+ function redisSet(_x3, _x4, _x5) {
3125
+ return _redisSet.apply(this, arguments);
3126
+ }
3127
+ function _redisSet() {
3128
+ _redisSet = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key, value, expiration) {
3129
+ var r;
3130
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
3131
+ while (1) switch (_context3.prev = _context3.next) {
3132
+ case 0:
3133
+ if (expiration === void 0) {
3134
+ expiration = 86400;
3135
+ }
3136
+ _context3.next = 3;
3137
+ return _setKey(key, value, 'EX', expiration);
3138
+ case 3:
3139
+ r = _context3.sent;
3140
+ return _context3.abrupt("return", r == 'OK' ? true : false);
3141
+ case 5:
3142
+ case "end":
3143
+ return _context3.stop();
3144
+ }
3145
+ }, _callee3);
3146
+ }));
3147
+ return _redisSet.apply(this, arguments);
3148
+ }
3149
+ function redisDel(_x6) {
3150
+ return _redisDel.apply(this, arguments);
3151
+ }
3152
+ function _redisDel() {
3153
+ _redisDel = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(key) {
3154
+ var r;
3155
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
3156
+ while (1) switch (_context4.prev = _context4.next) {
3157
+ case 0:
3158
+ _context4.next = 2;
3159
+ return _delKey(key);
3160
+ case 2:
3161
+ r = _context4.sent;
3162
+ return _context4.abrupt("return", r >= 1 ? true : false);
3163
+ case 4:
3164
+ case "end":
3165
+ return _context4.stop();
3166
+ }
3167
+ }, _callee4);
3168
+ }));
3169
+ return _redisDel.apply(this, arguments);
3170
+ }
3171
+ var cacher = {
3172
+ get: redisGet,
3173
+ exists: redisExists,
3174
+ set: redisSet,
3175
+ del: redisDel
3176
+ };
3177
+ return cacher;
3178
+ }
3179
+
3180
+ Object.defineProperty(exports, 'miolo_db_connection', {
3066
3181
  enumerable: true,
3067
3182
  get: function () { return calustra.getConnection; }
3068
3183
  });
3069
3184
  exports.miolo = miolo;
3185
+ exports.miolo_cacher = init_cacher;
3186
+ exports.miolo_emailer = init_emailer;
3187
+ exports.miolo_logger = init_logger;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.7.8
2
+ * miolo v0.9.0
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 t}from"http-terminator";import o from"deepmerge";import n from"node:path";import{fileURLToPath as i}from"node:url";import{getConnection as a}from"calustra";export{getConnection}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 p,red as m,cyan_light as v,green as h,blue as y,green_bold as g,yellow_bold as b}from"tinguir";import x from"node:util";import S,{transports as _,createLogger as w,format as E}from"winston";import k from"koa-better-body";import O from"koa-convert";import R from"koa-compress";import{constants as q}from"node:zlib";import M from"koa-mount";import C from"koa-static";import T from"koa-favicon";import{performance as j}from"node:perf_hooks";import J from"@koa/router";import{readFileSync as L}from"node:fs";import N from"jwt-simple";import A from"koa-passport";import P from"passport-local";import U from"koa-session";import F from"koa-redis";import V from"@koa/cors";import B from"koa-proxies";import z from"koa-router";import G from"qs";import{renderToString as I}from"react-dom/server";import{CronJob as D}from"cron";import H from"node:os";import W from"diskspace";function Y(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function K(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?Y(Object(t),!0).forEach((function(r){Q(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):Y(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function Z(e,r,t,o,n,i,a){try{var l=e[i](a),u=l.value}catch(c){return void t(c)}l.done?r(u):Promise.resolve(u).then(o,n)}function X(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){Z(i,o,n,a,l,"next",e)}function l(e){Z(i,o,n,a,l,"throw",e)}a(void 0)}))}}function Q(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r||"default");if("object"!=typeof o)return o;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:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var $=i(import.meta.url),ee=n.dirname($),re={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:n.resolve(ee,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!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:void 0},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:[]};var{combine:te,timestamp:oe,_label:ne,printf:ie,errors:ae}=E,le=(e,r)=>{var t,o,n={silly:c,debug:s,verbose:d,info:f,warn:p,error:m},i={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},a=ie((r=>{var t,o=n[r.level],a=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),l="[miolo] ".concat(o(a)," ").concat(o(i[r.level])," ").concat(r.message);return r.stack?"".concat(l,"\n").concat(r.stack):l})),l=[];e.console.enabled&&l.push(new _.Console({humanReadableUnhandledException:!0,level:(null==e||null===(t=e.console)||void 0===t?void 0:t.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));e.file.enabled&&l.push(new _.File({filename:e.file.filename,level:(null==e||null===(o=e.file)||void 0===o?void 0:o.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(e.mail.enabled){var v=function(e,r){var t=function(t){S.Transport.call(this,t),t=t||{},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=t.humanReadableUnhandledException||!0,this.handleExceptions=t.handleExceptions||!0,this.json=t.json||!1,this.colorize=t.colorize||!1};return x.inherits(t,S.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n=this,i="";try{i=t.message.split("\n")[0]}catch(c){i=t.message.toString()}i=u(i);var a=e.name+": ["+t.level.toUpperCase()+"] "+i,l={from:this.from,to:this.to,subject:a,text:u(t.message)};r.send(l,(function(){n.emit("logged"),o(null,!0)}))},t}(e.mail,r);_.MailerLogger=v,l.push(new _.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return w({level:(null==e?void 0:e.level)||"silly",format:te(ae({stack:!0}),oe(),a),transports:l})},ue=(e,r)=>{var t=function(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=l.createTransport(e,r);function n(){return(n=X((function*(e){if(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=o.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(n){return{error:n,ok:!1}}}))).apply(this,arguments)}var i={send:function(e){return n.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),o.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:e,defaults:r,silent:t};return i}(r.mail.options,r.mail.defaults),o=le(r.log,t),n=K(K({},r.db.options),{},{log:o}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},u={config:K({},r),emailer:t,logger:o,db:i};function c(){return(c=X((function*(e,r){e.miolo=u,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=u},ce=[401];var se=i(import.meta.url),de=n.dirname(se),fe=n.resolve(de,"./miolo.ico"),pe={total:0};var me=i(import.meta.url),ve=n.dirname(me),he=L(n.resolve(ve,"./robots.txt"),"utf8");var ye=(e,r,t)=>{var o=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(t||{})}catch(n){}return function(e,r){var t=Math.random().toString(),o=null==e?void 0:e.secret;o||(o="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:t};return N.encode(n,o)}(t||{},o)};function i(){return i=X((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),o.debug("Guest token conceeded"));var a=function(e){var r,t=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(t)&&(t=86400);var o=new Date;return o.setSeconds(o.getSeconds()+t),{expires:o,httpOnly:!1}}(t);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)}))},ge=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=X((function*(r,n){var i;try{i=(e=>{var r,t=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(t)try{t=t.replace("Basic ","");try{t=Buffer.from(t,"base64").toString()}catch(i){t=atob(t)}var[o,n]=t.split(":");return{username:o,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="'+o.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield t(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)}o||(o="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(M(r,i))))},be=new F;var xe=(e,r,t)=>r(null,e.id),Se=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},_e=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},we=(e,r,t)=>{var{get_user_id:o,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=o||xe,d=n||Se,f=i||_e,p=a||"/login",m=l||"/logout",v=new P.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));!function(e,r){e.keys=[r.secret||"*secret*"];var t=K({store:be},r.options||{});e.use(U(t,e))}(e,t),A.serializeUser(((r,t)=>{process.nextTick((function(){s(r,t,e.context.miolo)}))})),A.deserializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),A.use(v),e.use(A.initialize()),e.use(A.session());var h=function(){var e=X((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,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,t){return e.apply(this,arguments)}}(),y=new J;y.post(p,((e,r)=>A.authenticate("local",function(){var r=X((function*(r,t,o,n){if(!1!==t)return e.session.user=t,e.session.authenticated=!0,e.body={user:t,authenticated:!0},null!=u&&e.redirect(u),yield e.login(t);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:o,error:r},e.response.status=401}));return function(e,t,o,n){return r.apply(this,arguments)}}())(e))),y.get(m,h),y.post(m,h),e.use(y.routes())},Ee=(e,r)=>{null!=r&&0!=r.length&&r.map((r=>{function t(){return(t=X((function*(e,t){yield r(e),yield t()}))).apply(this,arguments)}e.use((function(e,r){return t.apply(this,arguments)}))}))},ke=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},Oe=(e,r)=>{var t=e.context.miolo.logger;ke(r,"cors",(r=>{if("simple"==r)t.debug("Setting CORS the simple way"),e.use(function(){var e=X((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,t){return e.apply(this,arguments)}}());else{var o=(e=>"object"==typeof e?e:{})(r);t.debug("Setting CORS headers for ".concat(JSON.stringify(o))),e.use(V(o))}})),ke(r,"proxy",(r=>{var[o,n]=(e=>{var r,t,o,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(t=e)||void 0===t?void 0:t.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(o=e)||void 0===o?void 0:o.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);t.debug("Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(B(o,n))}))},Re=function(){var e=X((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),qe=function(){var e=X((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),Me={require:!1,action:"redirect",redirect_url:"/",error_code:401},Ce={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Te=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];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)||Re,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||qe,u=o(Me,(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:o(Ce,(null==d?void 0:d.useUserFields)||{}),auth:o(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&&t.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),t};function je(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?G.parse(r):{}}function Je(e,r,t,o){t.map((t=>{var n=t.prefix;t.routes.map((t=>{var i=e.getModel(t.name);if(i){for(var a=function(){var e=X((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=t.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(o.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(o.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(o.error("Crud path ".concat(t.url," specified auth but no action")),e.body={})),i)}));return function(r,t){return e.apply(this,arguments)}}(),l=function(){var e=X((function*(e,r,o){var n;if(yield a(e,r)){var i=!0;if(null!=t&&t.before&&(i=yield t.before(e)),i){var l=null==e||null===(n=e.session)||void 0===n||null===(n=n.user)||void 0===n?void 0:n.id,u={};!0===t.useUserFields.use&&(u=t.useUserFields.fieldNames);var c,s={uid:l,fieldNames:u},d=yield o(s);null!=t&&t.after&&(d=yield t.after(e,d)),c=d,d=null==t.bodyField?c:{[t.bodyField]:c},e.body=d}else e.body={}}else e.body={}}));return function(r,t,o){return e.apply(this,arguments)}}(),u=function(){var e=X((function*(e){yield l(e,"r",function(){var r=X((function*(r){var t=je(e.request.url),o={transaction:void 0};return yield i.read(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=X((function*(e){yield l(e,"r",function(){var r=X((function*(r){var t=je(e.request.url),o={transaction:void 0};return yield i.keyList(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=X((function*(e){yield l(e,"r",function(){var r=X((function*(r){var t=je(e.request.url),o={transaction:void 0};return yield i.find(t.id,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=X((function*(e){yield l(e,"r",function(){var r=X((function*(r){var t=je(e.request.url),o={transaction:void 0};return yield i.distinct(t.distinct_field,t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=X((function*(e){yield l(e,"w",function(){var r=X((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.created_by&&(o[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(o,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=function(){var e=X((function*(e){yield l(e,"w",function(){var r=X((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.last_update_by&&(o[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(o,{id:o.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=function(){var e=X((function*(e){yield l(e,"w",function(){var r=X((function*(r){var t=e.request.fields,o={transaction:void 0};return yield i.delete({id:t.id},o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=n?"/".concat(n,"/").concat(t.url):"/".concat(t.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(t.name," to ").concat(v));var h=t.mode.indexOf("r")>=0,y=t.mode.indexOf("w")>=0,g=t.mode.indexOf("u")>=0||y;h&&(r.get("".concat(v,"/find"),(e=>s(e))),r.get("".concat(v,"/read"),(e=>u(e))),r.get("".concat(v,"/distinct"),(e=>d(e))),r.get("".concat(v,"/key_list"),(e=>c(e)))),g&&(r.post("".concat(v,"/save"),(e=>f(e))),r.post("".concat(v,"/update"),(e=>p(e)))),y&&r.post("".concat(v,"/delete"),(e=>m(e)))}else o.error("[miolo-router] Could not get model for ".concat(t.name))}))}))}var Le=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];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)||Re,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||qe,l=o(Me,(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:o(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)}t.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),t};function Ne(e,r,t){var o=new z;try{var n=Te(t),i=Le(t),a=n.length>0,l=i.length>0;if(!a&&!l)throw"[miolo-router] Could not get any route from the passed <routes> param";a&&Je(r,o,n,r.log),l&&function(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n,i=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");t.info("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=X((function*(e){var o,n=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"POST"===r.method)||(n||("error"==i.action?(t.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(t.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(t.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=X((function*(e){try{var o;if("GET"==r.method&&(null===(o=e.request)||void 0===o||!o.fields)&&e.request.url.indexOf("?")>0){var n=je(e.request.url);n&&(e.request.fields=n)}}catch(u){t.error("Error while trying to qet query params for ".concat(e.request.url))}if(yield a(e)){var i=!0;if(null!=r&&r.before&&(i=yield r.before(e)),i){var l=yield r.callback(e);return null!=r&&r.after&&(l=yield r.after(e,l)),l}}}));return function(r){return e.apply(this,arguments)}}(),u=r.method.toLowerCase();e[u](i,(e=>l(e,r)))}))}))}(o,i,r.log)}catch(u){console.error(u),console.error("[miolo-router] Error initing the router. Probably config objects are not ok"),console.error("[miolo-router] connOrConfig:"),console.error(null==r?void 0:r.config),console.error("[miolo-router] routes:"),console.error(t)}e.use(o.routes())}var Ae=i(import.meta.url),Pe=n.dirname(Ae),Ue=L(n.resolve(Pe,"fallback_index.html"),"utf8");var Fe=i(import.meta.url),Ve=n.dirname(Fe),Be=L(n.resolve(Ve,"fallback_index.html"),"utf8");function ze(e){return e?e/1e6:0}function Ge(e){return e?e/1e6:0}function Ie(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(ze(H.freemem()),2),n=Math.round(ze(H.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")):t.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")),W.check("/",(function(e,r){var o=Math.round(Ge(r.used),2),n=Math.round(Ge(r.total),2),i=Math.round(Ge(r.free),2);i<1?t.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)")):t.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function De(e,r){var t=e.context.miolo,o=t.logger,n=[Ie(),...r||[]],i=[];n.map((e=>{var r=e.name,o=function(e,r){var t,o=e.logger,n=null!=r&&null!==(t=r.onTick)&&void 0!==t&&t.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new D((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{console.log("".concat(i,".onTick"));try{o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,t)}catch(n){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(console.log("".concat(i,".onComplete")),o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),o.error(t)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,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])||o.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),o.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(g("manually started!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),o.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function He(n,i){var a,l=new r,u=function(e){var r,t=o(re,e);return t.auth_type=function(e){var r,t,o;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.passport?"passport":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.custom?"custom":"guest"}(e),t.use_catcher=!(null==t||null===(r=t.http)||void 0===r||!r.catcher_url),t}(n);ue(l,u),(e=>{e.use(R({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:q.Z_SYNC_FLUSH},deflate:{flush:q.Z_SYNC_FLUSH},br:!1})),e.use(O(k({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(l),function(e){var r=e.context.miolo.logger;function t(){return(t=X((function*(e){if(e){var t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),ce.indexOf(t)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(t,": ").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=t,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 t.apply(this,arguments)}}(l),((e,r)=>{var{favicon:t,folders:o}=r;for(var[n,i]of(e.use(T(t||fe)),Object.entries(o)))e.use(M(n,C(i,{index:!1})))})(l,null===(a=u.http)||void 0===a?void 0:a.static),function(e){function r(){return(r=X((function*(e,r){var t,o=e.miolo.logger,n=e.headers["x-real-ip"]||"127.0.0.1",i=j.now();e.request.body=K(K({},e.request.fields),e.request.files),pe.total+=1,pe[n]=(pe[n]||0)+1,e.requestId=pe.total,e.request.ip=n;var a=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,l="".concat(s(n)," ").concat(d(e.request.method)," ").concat(d(a)," [").concat(v(pe[n]),"/").concat(v(e.requestId),"]"),u=null!=e.request.body?JSON.stringify(e.request.body):"";o.info("".concat(l," - START")),o.debug("".concat(l," - Body: ").concat(u)),yield r();var c=null==e||null===(t=e.session)||void 0===t?void 0:t.user,p="";null!=c&&(null!=c&&c.id?p=" - uid ".concat(null==c?void 0:c.id):null!=c&&c.token&&(p=" - token ".concat(null==c?void 0:c.token)));var y,g=e.response.status,b=g;200==g?y=h:g>200&&g<=299?(y=f,e.response.redirected&&e.response.url&&(b+=" -> ".concat(e.response.url))):y=m;var x="[".concat(y(b),"]"),S=parseFloat((j.now()-i)/1e3).toFixed(2),_=S<1?h:S<2?f:m,w=null!=e.session?JSON.stringify(e.session):"";o.debug("".concat(l," - Session: ").concat(w));var E=null!=e.body?JSON.stringify(e.body):"";o.debug("".concat(l," - Response: ").concat(E)),o.info("".concat(l," - DONE ").concat(x).concat(p," (time ").concat(_(S),")"))}))).apply(this,arguments)}e.use((function(e,t){return r.apply(this,arguments)}))}(l),function(e){function r(){return(r=X((function*(e){e.body=he}))).apply(this,arguments)}var t=new J;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(l),u.use_catcher&&function(e,r){function t(){return t=X((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(f("[JS Warning]")," on ").concat(y(o),": ").concat(t.msg,"\n")+"".concat(f("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(m("[JS Error]")," on ").concat(y(o),": ").concat(r.msg,"\n")+"".concat(m("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(m("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(m("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(m("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(m("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),t.apply(this,arguments)}var o=new J;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(l,u.http.catcher_url),"guest"==u.auth_type&&ye(l,u.auth.guest,null==u?void 0:u.session),"basic"==u.auth_type&&ge(l,u.auth.basic),"passport"==u.auth_type&&we(l,u.auth.passport,null==u?void 0:u.session),"custom"==u.auth_type&&((e,r)=>{var t=e.context.miolo.logger;try{var o=r(e);if("function"==typeof o)e.use(o);else if(Array.isArray(o)){var n=new J;o.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){t.error("Custom auth error: ".concat(i,"'"))}})(l,u.auth.custom);var c=null==u?void 0:u.middlewares;if(c&&Ee(l,c),Oe(l,u.http),null!=u&&u.routes){var p=l.context.miolo.db.getConnection();Ne(l,p,u.routes)}null!=(null==i?void 0:i.middleware)?l.use(i.middleware):null!=(null==i?void 0:i.ssr)?function(e,r,t,o){var n=(null==r?void 0:r.html)||Be;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=X((function*(e){var t={};try{t=yield r.ssr.loader(e)}catch(l){var o,n="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(o=e.request)||void 0===o?void 0:o.fields)||{})),i=null!=l&&l.stack?"".concat(l.toString(),"\n").concat(l.stack):l.toString(),a="".concat("Error produced by loader in render.ssr middleware","\n").concat(n,"\n").concat(i);e.miolo.logger.error(a)}return t}));return function(r){return e.apply(this,arguments)}}(),a=(e,r)=>{var t,o,n=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return{user:null==e||null===(o=e.session)||void 0===o?void 0:o.user,authenticated:n,ssr_data:r,extra:null==e?void 0:e.extra}},l=(e,i)=>{var a="",l={hostname:null==t?void 0:t.hostname,port:null==t?void 0:t.port,catcher_url:null==t?void 0:t.catcher_url,auth_type:o};try{a=I(r.ssr.renderer(e,i,l))}catch(u){e.miolo.logger.error("Missing renderer in render.ssr middleware"),e.miolo.logger.error(u),a="\n <div>\n MIOLO: Missing SSR renderer: ".concat(u.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(i,null,2)).replace("{children}",a)};function u(){return(u=X((function*(e){var r=yield i(e),t=a(e,r),o=l(e,t);e.miolo.logger.debug("render_ssr_middleware() rendered HTML (".concat(Buffer.byteLength(o,"utf8")," bytes total) ")),e.body=o}))).apply(this,arguments)}e.use((function(e){return u.apply(this,arguments)}))}(l,i,u.http,u.auth_type):null!=i&&i.html?function(e,r){var t=(null==r?void 0:r.html)||Ue;t.indexOf("{context}")<0&&e.context.miolo.logger.error(m("Provided HTML for rendering has no {context} template variable")),t.indexOf("{children}")<0&&e.context.miolo.logger.error(m("Provided HTML for rendering has no {children} template variable"));var o=e=>{var r,t,o=!0===(null==e||null===(r=e.session)||void 0===r?void 0:r.authenticated);return{user:null==e||null===(t=e.session)||void 0===t?void 0:t.user,authenticated:o,ssr_data:void 0,extra:null==e?void 0:e.extra}},n=e=>t.replace("{context}",JSON.stringify(e,null,2));function i(){return(i=X((function*(e){var r=o(e),t=n(r);e.miolo.logger.debug("render_html_middleware() rendered HTML (".concat(Buffer.byteLength(t,"utf8")," bytes total) ")),e.body=t}))).apply(this,arguments)}var a=new J;a.get("/",(function(e){return i.apply(this,arguments)})),e.use(a.routes())}(l,i):function(e,r){function t(){return(t=X((function*(e){e.miolo.logger.debug("render_404_middleware() Not FOUND ".concat(e.url," ")),e.body={},e.response.status=404,e.response.body="Resource Not Found"}))).apply(this,arguments)}var o=new J;o.get("/",(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(l);var g=function(){var r=X((function*(){var r=e.createServer(l.callback());yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(r,u.http.port,u.http.hostname),l.context.miolo.logger.info("miolo is listening on ".concat(u.http.hostname,":").concat(u.http.port)),l.server=r;var o=t({server:r});return l.stop_server=X((function*(){yield o.terminate(),l.context.miolo.logger.info("miolo has been shutdowned from ".concat(u.http.hostname,":").concat(u.http.port))})),De(l,null==u?void 0:u.cron),l}));return function(){return r.apply(this,arguments)}}();return l.run=g,l}export{He as miolo};
11
+ import e from"node:http";import r from"koa";import{createHttpTerminator as t}from"http-terminator";import o 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 p,red as m,cyan_light as v,green as h,blue as y,green_bold as g,yellow_bold as b}from"tinguir";import S,{promisify as _}from"node:util";import x,{transports as E,createLogger as w,format as k}from"winston";import O from"koa-better-body";import R from"koa-convert";import q from"koa-compress";import{constants as C}from"node:zlib";import M from"koa-mount";import T from"koa-static";import j from"koa-favicon";import{performance as J}from"node:perf_hooks";import L from"@koa/router";import{readFileSync as N}from"node:fs";import A from"jwt-simple";import P from"koa-passport";import U from"passport-local";import F from"koa-session";import V from"koa-redis";import B from"@koa/cors";import I from"koa-proxies";import z from"koa-router";import D from"qs";import{renderToString as G}from"react-dom/server";import{CronJob as H}from"cron";import W from"node:os";import Y from"diskspace";import K from"redis";function X(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,o)}return t}function Z(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?X(Object(t),!0).forEach((function(r){ee(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):X(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function Q(e,r,t,o,n,i,a){try{var l=e[i](a),u=l.value}catch(c){return void t(c)}l.done?r(u):Promise.resolve(u).then(o,n)}function $(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){Q(i,o,n,a,l,"next",e)}function l(e){Q(i,o,n,a,l,"throw",e)}a(void 0)}))}}function ee(e,r,t){return(r=function(e){var r=function(e,r){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var o=t.call(e,r||"default");if("object"!=typeof o)return o;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:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var re=i(import.meta.url),te=n.dirname(re),oe={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},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:void 0},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 ne(e){var{options:r,defaults:t,silent:o}=e,n=l.createTransport(r,t);function i(){return(i=$((function*(e){if(!0===o)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(t){return{error:t,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:t,silent:o};return a}var{combine:ie,timestamp:ae,_label:le,printf:ue,errors:ce}=k,se=(e,r)=>{var t,o,n={silly:c,debug:s,verbose:d,info:f,warn:p,error:m},i={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},a=ue((r=>{var t,o=n[r.level],a=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),l="[miolo] ".concat(o(a)," ").concat(o(i[r.level])," ").concat(r.message);return r.stack?"".concat(l,"\n").concat(r.stack):l})),l=[];e.console.enabled&&l.push(new E.Console({humanReadableUnhandledException:!0,level:(null==e||null===(t=e.console)||void 0===t?void 0:t.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));e.file.enabled&&l.push(new E.File({filename:e.file.filename,level:(null==e||null===(o=e.file)||void 0===o?void 0:o.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0}));if(e.mail.enabled){var v=function(e,r){var t=function(t){x.Transport.call(this,t),t=t||{},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=t.humanReadableUnhandledException||!0,this.handleExceptions=t.handleExceptions||!0,this.json=t.json||!1,this.colorize=t.colorize||!1};return S.inherits(t,x.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n=this,i="";try{i=t.message.split("\n")[0]}catch(c){i=t.message.toString()}i=u(i);var a=e.name+": ["+t.level.toUpperCase()+"] "+i,l={from:this.from,to:this.to,subject:a,text:u(t.message)};r.send(l,(function(){n.emit("logged"),o(null,!0)}))},t}(e.mail,r);E.MailerLogger=v,l.push(new E.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}return w({level:(null==e?void 0:e.level)||"silly",format:ie(ce({stack:!0}),ae(),a),transports:l})},de=(e,r)=>{var t=ne(r.mail),o=se(r.log,t),n=Z(Z({},r.db.options),{},{log:o}),i={getConnection:()=>a(r.db.config,n),getModel:e=>a(r.db.config,n).getModel(e)},l={config:Z({},r),emailer:t,logger:o,db:i};function u(){return(u=$((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},fe=[401];var pe=i(import.meta.url),me=n.dirname(pe),ve=n.resolve(me,"./miolo.ico"),he={total:0};var ye=i(import.meta.url),ge=n.dirname(ye),be=N(n.resolve(ge,"./robots.txt"),"utf8");var Se=(e,r,t)=>{var o=e.context.miolo.logger,n=()=>{try{var{make_guest_token:e}=r;if(null!=e)return e(t||{})}catch(n){}return function(e,r){var t=Math.random().toString(),o=null==e?void 0:e.secret;o||(o="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:t};return A.encode(n,o)}(t||{},o)};function i(){return i=$((function*(e,r){var i=e.cookies.get("token")||e.headers.token;void 0!==i&&0!=i.length||(i=yield n(),o.debug("Guest token conceeded"));var a=function(e){var r,t=null==e||null===(r=e.options)||void 0===r?void 0:r.maxAge;isNaN(t)&&(t=86400);var o=new Date;return o.setSeconds(o.getSeconds()+t),{expires:o,httpOnly:!1}}(t);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)}))},_e=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=$((function*(r,n){var i;try{i=(e=>{var r,t=null==e||null===(r=e.headers)||void 0===r?void 0:r.authorization;if(t)try{t=t.replace("Basic ","");try{t=Buffer.from(t,"base64").toString()}catch(i){t=atob(t)}var[o,n]=t.split(":");return{username:o,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="'+o.replace(/"/g,'\\"')+'"'};if(!i)return a();var l=yield t(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)}o||(o="Secure Area"),null==n||0==n.length?e.use(i):n.map((r=>e.use(M(r,i))))},xe=new V;var Ee=(e,r,t)=>r(null,e.id),we=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},ke=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},Oe=(e,r,t)=>{var{get_user_id:o,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=o||Ee,d=n||we,f=i||ke,p=a||"/login",m=l||"/logout",v=new U.Strategy(((r,t,o)=>{f(r,t,o,e.context.miolo)}));!function(e,r){e.keys=[r.secret||"*secret*"];var t=Z({store:xe},r.options||{});e.use(F(t,e))}(e,t),P.serializeUser(((r,t)=>{process.nextTick((function(){s(r,t,e.context.miolo)}))})),P.deserializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),P.use(v),e.use(P.initialize()),e.use(P.session());var h=function(){var e=$((function*(e,r){e.session.authenticated?(e.session.user=void 0,e.session.authenticated=!1,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,t){return e.apply(this,arguments)}}(),y=new L;y.post(p,((e,r)=>P.authenticate("local",function(){var r=$((function*(r,t,o,n){if(!1!==t)return e.session.user=t,e.session.authenticated=!0,e.body={user:t,authenticated:!0},null!=u&&e.redirect(u),yield e.login(t);e.session.user=void 0,e.session.authenticated=!1,e.body={user:void 0,authenticated:!1,info:o,error:r},e.response.status=401}));return function(e,t,o,n){return r.apply(this,arguments)}}())(e))),y.get(m,h),y.post(m,h),e.use(y.routes())},Re=(e,r)=>{null!=r&&0!=r.length&&r.map((r=>{function t(){return(t=$((function*(e,t){yield r(e),yield t()}))).apply(this,arguments)}e.use((function(e,r){return t.apply(this,arguments)}))}))},qe=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},Ce=(e,r)=>{var t=e.context.miolo.logger;qe(r,"cors",(r=>{if("simple"==r)t.debug("Setting CORS the simple way"),e.use(function(){var e=$((function*(e,r){e.set("Access-Control-Allow-Origin","*"),e.set("Access-Control-Expose-Headers","SourceMap,X-SourceMap"),yield r()}));return function(r,t){return e.apply(this,arguments)}}());else{var o=(e=>"object"==typeof e?e:{})(r);t.debug("Setting CORS headers for ".concat(JSON.stringify(o))),e.use(B(o))}})),qe(r,"proxy",(r=>{var[o,n]=(e=>{var r,t,o,n;return null==e&&(e={}),[(null===(r=e)||void 0===r?void 0:r.path)||"/",{target:(null===(t=e)||void 0===t?void 0:t.target)||"https://proxy.miolo.com",changeOrigin:null==(null===(o=e)||void 0===o?void 0:o.changeOrigin)||e.changeOrigin,logs:null==(null===(n=e)||void 0===n?void 0:n.logs)||e.logs}]})(r);t.debug("Setting Proxy for ".concat(o," to ").concat(n.target," ")),e.use(I(o,n))}))},Me=function(){var e=$((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),Te=function(){var e=$((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),je={require:!1,action:"redirect",redirect_url:"/",error_code:401},Je={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},Le=e=>{var r=(null==e?void 0:e.crud)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];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)||Me,l=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Te,u=o(je,(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:o(Je,(null==d?void 0:d.useUserFields)||{}),auth:o(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&&t.push({prefix:(null==r?void 0:r.prefix)||"",routes:c})}})),t};function Ne(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?D.parse(r):{}}function Ae(e,r,t,o){t.map((t=>{var n=t.prefix;t.routes.map((t=>{var i=e.getModel(t.name);if(i){for(var a=function(){var e=$((function*(e,r){var n,i=!0===(null==e||null===(n=e.session)||void 0===n?void 0:n.authenticated),a=t.auth;return!(!0===a.require||"read-only"===a.require&&"w"===r)||(i||("error"==a.action?(o.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(o.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(o.error("Crud path ".concat(t.url," specified auth but no action")),e.body={})),i)}));return function(r,t){return e.apply(this,arguments)}}(),l=function(){var e=$((function*(e,r,o){var n;if(yield a(e,r)){var i=!0;if(null!=t&&t.before&&(i=yield t.before(e)),i){var l=null==e||null===(n=e.session)||void 0===n||null===(n=n.user)||void 0===n?void 0:n.id,u={};!0===t.useUserFields.use&&(u=t.useUserFields.fieldNames);var c,s={uid:l,fieldNames:u},d=yield o(s);null!=t&&t.after&&(d=yield t.after(e,d)),c=d,d=null==t.bodyField?c:{[t.bodyField]:c},e.body=d}else e.body={}}else e.body={}}));return function(r,t,o){return e.apply(this,arguments)}}(),u=function(){var e=$((function*(e){yield l(e,"r",function(){var r=$((function*(r){var t=Ne(e.request.url),o={transaction:void 0};return yield i.read(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=$((function*(e){yield l(e,"r",function(){var r=$((function*(r){var t=Ne(e.request.url),o={transaction:void 0};return yield i.keyList(t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=$((function*(e){yield l(e,"r",function(){var r=$((function*(r){var t=Ne(e.request.url),o={transaction:void 0};return yield i.find(t.id,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=$((function*(e){yield l(e,"r",function(){var r=$((function*(r){var t=Ne(e.request.url),o={transaction:void 0};return yield i.distinct(t.distinct_field,t,o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=$((function*(e){yield l(e,"w",function(){var r=$((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.created_by&&(o[r.fieldNames.created_by]=r.uid);var n={transaction:void 0};return yield i.insert(o,n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),p=function(){var e=$((function*(e){yield l(e,"w",function(){var r=$((function*(r){var t,o=e.request.fields;null!=r&&null!==(t=r.fieldNames)&&void 0!==t&&t.last_update_by&&(o[r.fieldNames.last_update_by]=r.uid);var n={transaction:void 0};return yield i.update(o,{id:o.id},n)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),m=function(){var e=$((function*(e){yield l(e,"w",function(){var r=$((function*(r){var t=e.request.fields,o={transaction:void 0};return yield i.delete({id:t.id},o)}));return function(e){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=n?"/".concat(n,"/").concat(t.url):"/".concat(t.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(t.name," to ").concat(v));var h=t.mode.indexOf("r")>=0,y=t.mode.indexOf("w")>=0,g=t.mode.indexOf("u")>=0||y;h&&(r.get("".concat(v,"/find"),(e=>s(e))),r.get("".concat(v,"/read"),(e=>u(e))),r.get("".concat(v,"/distinct"),(e=>d(e))),r.get("".concat(v,"/key_list"),(e=>c(e)))),g&&(r.post("".concat(v,"/save"),(e=>f(e))),r.post("".concat(v,"/update"),(e=>p(e)))),y&&r.post("".concat(v,"/delete"),(e=>m(e)))}else o.error("[miolo-router] Could not get model for ".concat(t.name))}))}))}var Pe=e=>{var r=(null==e?void 0:e.queries)||[];if(!r)return[];if(!Array.isArray(r))return[];var t=[];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)||Me,a=(null==r?void 0:r.after)||(null==e?void 0:e.after)||Te,l=o(je,(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:o(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)}t.push({prefix:(null==r?void 0:r.prefix)||"",routes:u})}})),t};function Ue(e,r,t){var o=new z;try{var n=Le(t),i=Pe(t),a=n.length>0,l=i.length>0;if(!a&&!l)throw"[miolo-router] Could not get any route from the passed <routes> param";a&&Ae(r,o,n,r.log),l&&function(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n,i=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);i.indexOf("//")>=0;)i=i.replace(/\/\//g,"/");t.info("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=$((function*(e){var o,n=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated),i=r.auth;return!(!0===i.require||"read-only"===i.require&&"POST"===r.method)||(n||("error"==i.action?(t.error("Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(t.warn("Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(t.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=$((function*(e){try{var o;if("GET"==r.method&&(null===(o=e.request)||void 0===o||!o.fields)&&e.request.url.indexOf("?")>0){var n=Ne(e.request.url);n&&(e.request.fields=n)}}catch(u){t.error("Error while trying to qet query params for ".concat(e.request.url))}if(yield a(e)){var i=!0;if(null!=r&&r.before&&(i=yield r.before(e)),i){var l=yield r.callback(e);return null!=r&&r.after&&(l=yield r.after(e,l)),l}}}));return function(r){return e.apply(this,arguments)}}(),u=r.method.toLowerCase();e[u](i,(e=>l(e,r)))}))}))}(o,i,r.log)}catch(u){console.error(u),console.error("[miolo-router] Error initing the router. Probably config objects are not ok"),console.error("[miolo-router] connOrConfig:"),console.error(null==r?void 0:r.config),console.error("[miolo-router] routes:"),console.error(t)}e.use(o.routes())}var Fe=i(import.meta.url),Ve=n.dirname(Fe),Be=N(n.resolve(Ve,"fallback_index.html"),"utf8");var Ie=i(import.meta.url),ze=n.dirname(Ie),De=N(n.resolve(ze,"fallback_index.html"),"utf8");function Ge(e){return e?e/1e6:0}function He(e){return e?e/1e6:0}function We(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(Ge(W.freemem()),2),n=Math.round(Ge(W.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")):t.info("[SERVER][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(h(n)," MB (").concat(f(i)," %)")),Y.check("/",(function(e,r){var o=Math.round(He(r.used),2),n=Math.round(He(r.total),2),i=Math.round(He(r.free),2);i<1?t.error("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)")):t.info("[SERVER][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(h(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function Ye(e,r){var t=e.context.miolo,o=t.logger,n=[We(),...r||[]],i=[];n.map((e=>{var r=e.name,o=function(e,r){var t,o=e.logger,n=null!=r&&null!==(t=r.onTick)&&void 0!==t&&t.name&&"onTick"!=r.onTick.name?r.onTick.name:"custom",i=(null==r?void 0:r.name)||n;return new H((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{console.log("".concat(i,".onTick"));try{o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,t)}catch(n){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(console.log("".concat(i,".onComplete")),o.silly("[SERVER][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[SERVER][Custom Job ".concat(d(i),"] Error at onComplete()")),o.error(t)}}),!0===(null==r?void 0:r.start),(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,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])||o.error("[SERVER] Cannot stop job ".concat(d(e),": Not Found")),r},l=e=>{try{e.job.stop(),e.running=!1,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(b("manually stopped!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually stopping it")),o.error(r)}};e.cron={jobs:i,start:e=>{var r=a(e);r&&(e=>{try{e.job.stop(),e.running=!0,o.debug("[SERVER][Job ".concat(d(e.name),"] ").concat(g("manually started!")))}catch(r){o.error("[SERVER][Job ".concat(d(e.name),"] Error manually starting it")),o.error(r)}})(r)},stop:e=>{var r=a(e);r&&l(r)},stop_all:()=>{i.map((e=>{l(e)}))}}}function Ke(n,i){var a,l=new r,u=function(e){var r,t=o(oe,e);return t.auth_type=function(e){var r,t,o;return null!=e&&null!==(r=e.auth)&&void 0!==r&&r.basic?"basic":null!=e&&null!==(t=e.auth)&&void 0!==t&&t.passport?"passport":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.custom?"custom":"guest"}(e),t.use_catcher=!(null==t||null===(r=t.http)||void 0===r||!r.catcher_url),t}(n);de(l,u),Ce(l,u.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(R(O({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(l),function(e){var r=e.context.miolo.logger;function t(){return(t=$((function*(e){if(e){var t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),fe.indexOf(t)>=0?r.warn("".concat(this.method," ").concat(this.url," - ").concat(t,": ").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=t,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 t.apply(this,arguments)}}(l),((e,r)=>{var{favicon:t,folders:o}=r;for(var[n,i]of(e.use(j(t||ve)),Object.entries(o)))e.use(M(n,T(i,{index:!1})))})(l,null===(a=u.http)||void 0===a?void 0:a.static),function(e){function r(){return(r=$((function*(e,r){var t,o=e.miolo.logger,n=e.headers["x-real-ip"]||"127.0.0.1",i=J.now();e.request.body=Z(Z({},e.request.fields),e.request.files),he.total+=1,he[n]=(he[n]||0)+1,e.requestId=he.total,e.request.ip=n;var a=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,l="".concat(s(n)," ").concat(d(e.request.method)," ").concat(d(a)," [").concat(v(he[n]),"/").concat(v(e.requestId),"]"),u=null!=e.request.body?JSON.stringify(e.request.body):"";o.info("".concat(l," - START")),o.debug("".concat(l," - Body: ").concat(u)),yield r();var c=null==e||null===(t=e.session)||void 0===t?void 0:t.user,p="";null!=c&&(null!=c&&c.id?p=" - uid ".concat(null==c?void 0:c.id):null!=c&&c.token&&(p=" - token ".concat(null==c?void 0:c.token)));var y,g=e.response.status,b=g;200==g?y=h:g>200&&g<=299?(y=f,e.response.redirected&&e.response.url&&(b+=" -> ".concat(e.response.url))):y=m;var S="[".concat(y(b),"]"),_=parseFloat((J.now()-i)/1e3).toFixed(2),x=_<1?h:_<2?f:m,E=null!=e.session?JSON.stringify(e.session):"";o.debug("".concat(l," - Session: ").concat(E));var w=null!=e.body?JSON.stringify(e.body):"";o.debug("".concat(l," - Response: ").concat(w)),o.info("".concat(l," - DONE ").concat(S).concat(p," (time ").concat(x(_),")"))}))).apply(this,arguments)}e.use((function(e,t){return r.apply(this,arguments)}))}(l),function(e){function r(){return(r=$((function*(e){e.body=be}))).apply(this,arguments)}var t=new L;t.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(t.routes())}(l),u.use_catcher&&function(e,r){function t(){return t=$((function*(e){var{error:r,warning:t,path:o,agent:n}=e.request.body,i=e.miolo.logger;if(t){var a="".concat(f("[JS Warning]")," on ").concat(y(o),": ").concat(t.msg,"\n")+"".concat(f("[JS Warning]")," File => ").concat(t.file,"\n")+"".concat(f("[JS Warning]")," Line => ").concat(t.line,"\n")+"".concat(f("[JS Warning]")," Col => ").concat(t.col,"\n")+"".concat(f("[JS Warning]")," Error => ").concat(JSON.stringify(t.error),"\n")+"".concat(f("[JS Warning]")," Agent => ").concat(n);i.warn(a)}else{var l="".concat(m("[JS Error]")," on ").concat(y(o),": ").concat(r.msg,"\n")+"".concat(m("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(m("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(m("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(m("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(m("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),t.apply(this,arguments)}var o=new L;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(l,u.http.catcher_url),"guest"==u.auth_type&&Se(l,u.auth.guest,null==u?void 0:u.session),"basic"==u.auth_type&&_e(l,u.auth.basic),"passport"==u.auth_type&&Oe(l,u.auth.passport,null==u?void 0:u.session),"custom"==u.auth_type&&((e,r)=>{var t=e.context.miolo.logger;try{var o=r(e);if("function"==typeof o)e.use(o);else if(Array.isArray(o)){var n=new L;o.map((e=>{var r=e.method.toLowerCase();n[r](e.url,e.callback)})),e.use(n.routes())}}catch(i){t.error("Custom auth error: ".concat(i,"'"))}})(l,u.auth.custom);var c=null==u?void 0:u.middlewares;if(c&&Re(l,c),null!=u&&u.routes){var p=l.context.miolo.db.getConnection();Ue(l,p,u.routes)}null!=(null==i?void 0:i.middleware)?l.use(i.middleware):null!=(null==i?void 0:i.ssr)?function(e,r,t,o){var n=(null==r?void 0:r.html)||De;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=$((function*(e){var t={};try{t=yield r.ssr.loader(e)}catch(l){var o,n="URL: ".concat(e.request.url,"\nFields: ").concat(JSON.stringify((null===(o=e.request)||void 0===o?void 0:o.fields)||{})),i=null!=l&&l.stack?"".concat(l.toString(),"\n").concat(l.stack):l.toString(),a="".concat("Error produced by loader in render.ssr middleware","\n").concat(n,"\n").concat(i);e.miolo.logger.error(a)}return t}));return function(r){return e.apply(this,arguments)}}(),a=(e,r)=>{var t,o,n=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return{user:null==e||null===(o=e.session)||void 0===o?void 0:o.user,authenticated:n,ssr_data:r,extra:null==e?void 0:e.extra}},l=(e,i)=>{var a="",l={hostname:null==t?void 0:t.hostname,port:null==t?void 0:t.port,catcher_url:null==t?void 0:t.catcher_url,auth_type:o};try{a=G(r.ssr.renderer(e,i,l))}catch(u){e.miolo.logger.error("Missing renderer in render.ssr middleware"),e.miolo.logger.error(u),a="\n <div>\n MIOLO: Missing SSR renderer: ".concat(u.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(i,null,2)).replace("{children}",a)};function u(){return(u=$((function*(e){var r=yield i(e),t=a(e,r),o=l(e,t);e.miolo.logger.debug("render_ssr_middleware() rendered HTML (".concat(Buffer.byteLength(o,"utf8")," bytes total) ")),e.body=o}))).apply(this,arguments)}e.use((function(e){return u.apply(this,arguments)}))}(l,i,u.http,u.auth_type):null!=i&&i.html?function(e,r){var t=(null==r?void 0:r.html)||Be;t.indexOf("{context}")<0&&e.context.miolo.logger.error(m("Provided HTML for rendering has no {context} template variable")),t.indexOf("{children}")<0&&e.context.miolo.logger.error(m("Provided HTML for rendering has no {children} template variable"));var o=e=>{var r,t,o=!0===(null==e||null===(r=e.session)||void 0===r?void 0:r.authenticated);return{user:null==e||null===(t=e.session)||void 0===t?void 0:t.user,authenticated:o,ssr_data:void 0,extra:null==e?void 0:e.extra}},n=e=>t.replace("{context}",JSON.stringify(e,null,2));function i(){return(i=$((function*(e){var r=o(e),t=n(r);e.miolo.logger.debug("render_html_middleware() rendered HTML (".concat(Buffer.byteLength(t,"utf8")," bytes total) ")),e.body=t}))).apply(this,arguments)}var a=new L;a.get("/",(function(e){return i.apply(this,arguments)})),e.use(a.routes())}(l,i):function(e,r){function t(){return(t=$((function*(e){e.miolo.logger.debug("render_404_middleware() Not FOUND ".concat(e.url," ")),e.body={},e.response.status=404,e.response.body="Resource Not Found"}))).apply(this,arguments)}var o=new L;o.get("/",(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(l);var g=function(){var r=$((function*(){var r=e.createServer(l.callback());yield((e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))})))(r,u.http.port,u.http.hostname),l.context.miolo.logger.info("miolo is listening on ".concat(u.http.hostname,":").concat(u.http.port)),l.server=r;var o=t({server:r});return l.stop_server=$((function*(){yield o.terminate(),l.context.miolo.logger.info("miolo has been shutdowned from ".concat(u.http.hostname,":").concat(u.http.port))})),Ye(l,null==u?void 0:u.cron),l}));return function(){return r.apply(this,arguments)}}();return l.run=g,l}function Xe(e){var r=K.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 K.ReplyError?"".concat(s("REDIS")," ").concat(m("Error "+e.code)," Command: ").concat(e.command," ").concat(e.toString()):"".concat(s("REDIS")," ").concat(m("Error "+e.code)," ").concat(e.toString())}catch(t){r="".concat(s("REDIS")," ").concat(m("Error ")," ").concat(t)}console.error(r)})),t=_(r.get).bind(r),o=_(r.exists).bind(r),n=_(r.set).bind(r),i=_(r.del).bind(r);function a(){return(a=$((function*(e){return yield t(e)}))).apply(this,arguments)}function l(){return(l=$((function*(e){return 1==(yield o(e))}))).apply(this,arguments)}function u(){return u=$((function*(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:86400;return"OK"==(yield n(e,r,"EX",t))})),u.apply(this,arguments)}function c(){return(c=$((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{Ke as miolo,Xe as miolo_cacher,ne as miolo_emailer,se as miolo_logger};