miolo 0.10.2 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
3
3
  *
4
4
  * Copyright (c) Donato Lorenzo <donato@afialapis.com>
5
5
  *
@@ -2030,6 +2030,8 @@ var CUSTOM_BLACKLIST_IPS = ['52.212.247.108',
2030
2030
  // Asia Pacific Network Information Centre (APNIC)
2031
2031
  '110.166.71.39',
2032
2032
  // Asia Pacific Network Information Centre (APNIC)
2033
+ '39.107.54.8',
2034
+ // Asia Pacific Network Information Centre (APNIC)
2033
2035
  '205.210.31.240 ',
2034
2036
  // Palo Alto Networks, Inc (PAN-22)
2035
2037
  '134.122.52.203',
@@ -2114,14 +2116,18 @@ var init_static_middleware = function init_static_middleware(app, config) {
2114
2116
  };
2115
2117
 
2116
2118
  var _geoip_reader = undefined;
2117
- var _geoip_local_ips = ['127.0.0.1', '::1:'];
2118
- function _geoip_init(db, local_ips, logger) {
2119
+ var _geoip_def_local_ips = ['127.0.0.1', '::1:'];
2120
+ function _geoip_is_local(ip, local_ips) {
2121
+ if (local_ips === void 0) {
2122
+ local_ips = [];
2123
+ }
2124
+ var all_local_ips = [].concat(_geoip_def_local_ips, local_ips || []);
2125
+ return all_local_ips.indexOf(ip) >= 0;
2126
+ }
2127
+ function _geoip_init(db, logger) {
2119
2128
  if (db === void 0) {
2120
2129
  db = '/var/lib/GeoIP/GeoLite2-City.mmdb';
2121
2130
  }
2122
- if (local_ips === void 0) {
2123
- local_ips = ['127.0.0.1'];
2124
- }
2125
2131
  if (logger === void 0) {
2126
2132
  logger = console;
2127
2133
  }
@@ -2129,7 +2135,6 @@ function _geoip_init(db, local_ips, logger) {
2129
2135
  if (_geoip_reader != undefined) {
2130
2136
  return _geoip_reader;
2131
2137
  }
2132
- _geoip_local_ips = [].concat(_geoip_local_ips, local_ips || []);
2133
2138
  var dbBuffer = fs.readFileSync(db);
2134
2139
  _geoip_reader = geoip2Node.Reader.openBuffer(dbBuffer);
2135
2140
  return _geoip_reader;
@@ -2143,7 +2148,7 @@ var geoip_localize_ip = function geoip_localize_ip(ip, config, logger) {
2143
2148
  if (logger === void 0) {
2144
2149
  logger = console;
2145
2150
  }
2146
- if (_geoip_local_ips.indexOf(ip) >= 0) {
2151
+ if (_geoip_is_local(ip, config == null ? void 0 : config.local_ips)) {
2147
2152
  return {
2148
2153
  local: true,
2149
2154
  country: '',
@@ -2152,7 +2157,7 @@ var geoip_localize_ip = function geoip_localize_ip(ip, config, logger) {
2152
2157
  }
2153
2158
  try {
2154
2159
  var _resp$city;
2155
- var reader = _geoip_init(config == null ? void 0 : config.db, config == null ? void 0 : config.local_ipds, logger);
2160
+ var reader = _geoip_init(config == null ? void 0 : config.db, logger);
2156
2161
  var resp = reader.city(ip);
2157
2162
  return {
2158
2163
  country: resp.country.isoCode,
@@ -3213,13 +3218,13 @@ function attachCrudRoutes(router, crudConfigs, logger) {
3213
3218
  }
3214
3219
  if (!authenticated) {
3215
3220
  if (auth.action == 'error') {
3216
- ctx.miolo.logger.error("[miolo-router] Unauthorized access. Throwing error " + auth.error_code);
3221
+ ctx.miolo.logger.error("[router] Unauthorized access. Throwing error " + auth.error_code);
3217
3222
  ctx["throw"](auth.error_code, null, {});
3218
3223
  } else if (auth.action == 'redirect') {
3219
- ctx.miolo.logger.warn("[miolo-router] Unauthorized access. Redirecting to " + auth.redirect_url);
3224
+ ctx.miolo.logger.warn("[router] Unauthorized access. Redirecting to " + auth.redirect_url);
3220
3225
  ctx.redirect(auth.redirect_url);
3221
3226
  } else {
3222
- ctx.miolo.logger.error("[miolo-router] Crud path " + route.url + " specified auth but no action");
3227
+ ctx.miolo.logger.error("[router] Crud path " + route.url + " specified auth but no action");
3223
3228
  ctx.body = {};
3224
3229
  }
3225
3230
  }
@@ -3250,8 +3255,8 @@ function attachCrudRoutes(router, crudConfigs, logger) {
3250
3255
  _context2.next = 6;
3251
3256
  break;
3252
3257
  }
3253
- ctx.miolo.logger.error("[miolo-router] Could not get model for " + route.name);
3254
- throw new Error("[miolo-router] Could not get model for " + route.name);
3258
+ ctx.miolo.logger.error("[router] Could not get model for " + route.name);
3259
+ throw new Error("[router] Could not get model for " + route.name);
3255
3260
  case 6:
3256
3261
  result = {};
3257
3262
  _context2.prev = 7;
@@ -3310,7 +3315,7 @@ function attachCrudRoutes(router, crudConfigs, logger) {
3310
3315
  case 35:
3311
3316
  _context2.prev = 35;
3312
3317
  _context2.t0 = _context2["catch"](7);
3313
- ctx.miolo.logger.error("[miolo-router] Unexpected error on CRUD " + route.name + "-" + op);
3318
+ ctx.miolo.logger.error("[router] Unexpected error on CRUD " + route.name + "-" + op);
3314
3319
  ctx.miolo.logger.error(_context2.t0);
3315
3320
  case 39:
3316
3321
  result = _pack_body_field(result);
@@ -3631,7 +3636,7 @@ function attachCrudRoutes(router, crudConfigs, logger) {
3631
3636
  while (url.indexOf('//') >= 0) {
3632
3637
  url = url.replace(/\/\//g, "/");
3633
3638
  }
3634
- logger.info("[miolo-router] Routing table " + route.name + " to " + url);
3639
+ logger.info("[router] Routing table " + route.name + " to " + url);
3635
3640
  var allowRead = route.mode.indexOf('r') >= 0;
3636
3641
  var allowDelete = route.mode.indexOf('w') >= 0;
3637
3642
  var allowUpsave = route.mode.indexOf('u') >= 0 || allowDelete;
@@ -3753,7 +3758,7 @@ function attachQueriesRoutes(router, queriesConfigs, logger) {
3753
3758
  }
3754
3759
  var routeAuth = route.auth;
3755
3760
  var checkAuth = routeAuth.require === true || routeAuth.require === 'read-only' && route.method === 'POST';
3756
- logger.info("[miolo-router] Routing " + (((_route$callback = route.callback) == null ? void 0 : _route$callback.name) || 'callback') + " to " + route.method + " " + url + (checkAuth ? ' (auth)' : ''));
3761
+ logger.info("[router] Routing " + (((_route$callback = route.callback) == null ? void 0 : _route$callback.name) || 'callback') + " to " + route.method + " " + url + (checkAuth ? ' (auth)' : ''));
3757
3762
  var _route_auth_callback = /*#__PURE__*/function () {
3758
3763
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(ctx) {
3759
3764
  var _ctx$session;
@@ -3793,7 +3798,7 @@ function attachQueriesRoutes(router, queriesConfigs, logger) {
3793
3798
  }();
3794
3799
  var _route_callback = /*#__PURE__*/function () {
3795
3800
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(ctx) {
3796
- var result, _ctx$request, fields, authenticated, goon;
3801
+ var result, _ctx$request, fields, authenticated, goon, _route$callback2;
3797
3802
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
3798
3803
  while (1) switch (_context2.prev = _context2.next) {
3799
3804
  case 0:
@@ -3809,7 +3814,7 @@ function attachQueriesRoutes(router, queriesConfigs, logger) {
3809
3814
  }
3810
3815
  }
3811
3816
  } catch (e) {
3812
- ctx.miolo.logger.error("[miolo-router] Error while trying to qet query params for " + ctx.request.url);
3817
+ ctx.miolo.logger.error("[router] Error while trying to qet query params for " + ctx.request.url);
3813
3818
  }
3814
3819
  _context2.next = 5;
3815
3820
  return _route_auth_callback(ctx);
@@ -3855,7 +3860,7 @@ function attachQueriesRoutes(router, queriesConfigs, logger) {
3855
3860
  case 24:
3856
3861
  _context2.prev = 24;
3857
3862
  _context2.t0 = _context2["catch"](1);
3858
- ctx.miolo.logger.error("[miolo-router] Unexpected error on Query " + route.name);
3863
+ ctx.miolo.logger.error("[router] Unexpected error on Query " + ((_route$callback2 = route.callback) == null ? void 0 : _route$callback2.name) + " at " + url);
3859
3864
  ctx.miolo.logger.error(_context2.t0);
3860
3865
  case 28:
3861
3866
  return _context2.abrupt("return", result);
@@ -3891,7 +3896,7 @@ function init_router(app, routes) {
3891
3896
  var crudConfigsOk = crudConfigs.length > 0;
3892
3897
  var queriesConfigsOk = queriesConfigs.length > 0;
3893
3898
  if (!crudConfigsOk && !queriesConfigsOk) {
3894
- throw "[miolo-router] Could not get any route from the passed <routes> param";
3899
+ throw "[router] Could not get any route from the passed <routes> param";
3895
3900
  }
3896
3901
 
3897
3902
  // attach CRUD routes
@@ -3904,8 +3909,8 @@ function init_router(app, routes) {
3904
3909
  attachQueriesRoutes(router, queriesConfigs, logger);
3905
3910
  }
3906
3911
  } catch (e) {
3907
- logger.error('[miolo-router] Error initing the router.');
3908
- logger.error('[miolo-router] routes:');
3912
+ logger.error('[router] Error initing the router.');
3913
+ logger.error('[router] routes:');
3909
3914
  logger.error(routes);
3910
3915
  logger.error(e);
3911
3916
  }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * miolo v0.10.2
2
+ * miolo v0.10.3
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"koa";import r from"deepmerge";import o from"node:path";import{fileURLToPath as t}from"node:url";import n from"nodemailer";import i,{readFileSync as a}from"node:fs";import{uncolor as l,red as c,gray as u,magenta as s,cyan as d,yellow as f,red_light as v,green as p,cyan_light as m,blue as h,green_bold as g,yellow_bold as y}from"tinguir";import b from"node:util";import _,{transports as w,createLogger as x,format as S}from"winston";import{intre_now as k}from"intre";import{dropConnections as O,getConnection as E}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import{cacheiro as j}from"cacheiro";export{cacheiro as miolo_cacher}from"cacheiro";import q from"koa-better-body";import C from"koa-convert";import P from"koa-compress";import{constants as R}from"node:zlib";import I from"koa-ratelimit";import L from"node:https";import M from"koa-mount";import F from"koa-static";import J from"koa-favicon";import{performance as N}from"node:perf_hooks";import{Reader as T}from"@maxmind/geoip2-node";import A from"@koa/router";import U from"jwt-simple";import z from"koa-passport";import B from"passport-local";import G from"koa-session";import W from"@koa/cors";import D from"koa-proxies";import H from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as K}from"cron";import V from"node:os";import Z from"diskspace";import Q from"node:http";import{createHttpTerminator as X}from"http-terminator";function $(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 ee(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?$(Object(o),!0).forEach((function(r){ne(e,r,o[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):$(Object(o)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))}))}return e}function re(e){var r=function(e,r){if("object"!=typeof e||!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:r+""}function oe(e,r,o,t,n,i,a){try{var l=e[i](a),c=l.value}catch(u){return void o(u)}l.done?r(c):Promise.resolve(c).then(t,n)}function te(e){return function(){var r=this,o=arguments;return new Promise((function(t,n){var i=e.apply(r,o);function a(e){oe(i,t,n,a,l,"next",e)}function l(e){oe(i,t,n,a,l,"throw",e)}a(void 0)}))}}function ne(e,r,o){return(r=re(r))in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var ie=t(import.meta.url),ae=o.dirname(ie),le=864e6,ce={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:o.resolve(ae,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,ratelimit:{max:1e3,duration:6e4,errorMessage:"Rate Limit reached",whitelist_ips:[],blacklist_ips:[],ipsum_folder:"/var/ipsum"},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:le,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:{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/afialapis/%MIOLO%.log",zippedArchive:!0,maxsize:20971520,maxFiles:20},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:[],cache:{default:{type:"combined",redis:{host:"127.0.0.1",port:6379},version:1,clean:!1},calustra:{namespace:"miolo-calustra",ttl:864e5},session:{namespace:"miolo-session",ttl:le},custom:{}}};function ue(e){var{options:r,defaults:o,silent:t}=e,i=n.createTransport(r,o);function a(){return(a=te((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=i.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(o){return{error:o,ok:!1}}}))).apply(this,arguments)}var l={send:function(e){return a.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),i.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 l}var{combine:se,timestamp:de,_label:fe,printf:ve,errors:pe}=S,me=function(e,r){var t,n,a,p,m=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",h={silly:u,debug:s,verbose:d,info:f,warn:v,error:c},g={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},y=r=>{var o,t=h[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(o=e.format)||void 0===o?void 0:o.locale)||"en"),i="[".concat(m,"] ").concat(t(n)," ").concat(t(g[r.level])," ").concat(r.message);return r.stack?"".concat(i,"\n").concat(r.stack):i},S=[];!0===(null==e||null===(t=e.console)||void 0===t?void 0:t.enabled)&&S.push(new w.Console({humanReadableUnhandledException:!0,level:(null==e||null===(p=e.console)||void 0===p?void 0:p.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(n=e.file)||void 0===n?void 0:n.enabled)){var O,E,j=new w.File({filename:null!=e&&null!==(O=e.file)&&void 0!==O&&O.filename?e.file.filename.replace("%MIOLO%",m):"/var/log/afialapis/miolo.log",level:(null==e||null===(E=e.file)||void 0===E?void 0:E.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0,maxRetries:10});!function(e){process.on("SIGHUP",(function(){var r=o.join(e.dirname,e._getFile(!1));return function(){console.log("[miolo][file-logger] SIGHUP received. Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroy());var o=i.createWriteStream(r,e.options);o.setMaxListeners(1/0),e._size=0,e._stream=o,e.opening=!1,e.emit("open",r),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(t){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(t.toString()))}}()}))}(j),S.push(j);var q=r=>{var t,n,a=o.join(j.dirname,j.filename),l=y({level:"info",message:"[logger][file-rotate] ".concat(r,"\n"),timestamp:k()});try{i.accessSync(a,i.constants.F_OK),i.appendFileSync(a,l)}catch(c){i.writeFileSync(a,l,{encoding:"utf-8"})}!0===(null==e||null===(t=e.console)||void 0===t?void 0:t.enabled)&&(j.levels[(null==e||null===(n=e.console)||void 0===n?void 0:n.level)||(null==e?void 0:e.level)||"error"]>=j.levels.info&&console.log(l))};j.on("finish",(function(e){q("Log done")})),j.on("error",(function(e){q(c("Error: ".concat(e)))}))}if(!0===(null==e||null===(a=e.mail)||void 0===a?void 0:a.enabled)){var C=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 b.inherits(o,_.Transport),o.prototype.name="MailerLogger",o.prototype.log=function(o,t){var n=this,i="",a="";try{try{i=o.message.split("\n")[0]}catch(s){i=o.message.toString()}i=l(i)}catch(d){i="Could not create a title for the error (".concat(d.toString(),")")}try{try{a=l(o.message)}catch(d){a=o.message.toString()}}catch(d){a="Could not create a body for the error (".concat(d.toString(),")")}var c="".concat(null==e?void 0:e.name," [").concat(o.level.toUpperCase(),"] ").concat(i),u={from:this.from,to:this.to,subject:c,text:a};r.send(u,(function(){n.emit("logged"),t(null,!0)}))},o}(e.mail,r);w.MailerLogger=C,S.push(new w.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}var P=x({level:(null==e?void 0:e.level)||"silly",format:se(pe({stack:!0}),de(),ve(y)),transports:S});try{P.info("[logger] Inited for ".concat(P.transports.map((e=>"".concat(e.name," (").concat(e.level,")").concat(e.silent?c(" SILENT!"):""))).join(", ")))}catch(R){}return P};class he{parse_value_str(e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong str value passed: ".concat(e);return r}return e.toString()}parse_field_str(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected str value not passed for ".concat(r);return t}return this.parse_value_str(e[r],o,t)}parse_value_int(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,t=parseInt(e);if(null==t||isNaN(t)){if(r)throw"Wrong int value passed: ".concat(e);return o}return t}parse_field_int(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected int value not passed for ".concat(r);return t}return this.parse_value_int(e[r],o,t)}parse_value_float(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,t=parseFloat(e);if(null==t||isNaN(t)){if(r)throw"Wrong float value passed: ".concat(e);return o}return e}parse_field_float(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected float value not passed for ".concat(r);return t}return this.parse_value_float(e[r],o,t)}parse_value_bool(e){if(null!=e&&null!=e)return!0===e||"true"===e||"True"===e||1===e||"1"===e||!1!==e&&"false"!==e&&"False"!==e&&0!==e&&"0"!==e&&(arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0);if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong bool value passed for ".concat(name)}parse_field_bool(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected bool value not passed for ".concat(r);return t}return this.parse_value_bool(e[r],o,t)}parse_value_obj(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(r)throw"Wrong obj value passed: ".concat(e);return o}if(0==Object.keys(e).length){if(r)throw"Empty obj value passed: ".concat(e);return o}if("object"!=typeof e)throw"Wrong obj value passed: ".concat(e);return e}parse_field_obj(e,r){var o=arguments.length>2&&void 0!==arguments[2]&&arguments[2],t=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(o)throw"Expected obj value not passed for ".concat(r);return t}return this.parse_value_obj(e[r],o,t)}}var ge=()=>new he;function ye(e,r,o){return{type:(null==r?void 0:r.type)||(null==e?void 0:e.type),redis:(null==r?void 0:r.redis)||(null==e?void 0:e.redis),namespace:(null==r?void 0:r.namespace)||(null==e?void 0:e.namespace),version:(null==r?void 0:r.version)||(null==e?void 0:e.version),clean:!0===(null==r?void 0:r.clean)||!0===(null==e?void 0:e.clean),ttl:(null==r?void 0:r.ttl)||(null==e?void 0:e.ttl),log:o}}function be(e,r){return ye(e.cache.default,e.cache.calustra,r)}var _e=void 0;function we(e,r){var o=function(){var o=te((function*(){if(null==_e){_e={};var o=function(e,r){var o=e.cache.default,t=e.cache.custom||{},n={};for(var[i,a]of Object.entries(t)){var l=ye(o,a,r);l.namespace=l.namespace||"miolo-".concat(i),n[i]=l}return n}(e,r);for(var[t,n]of Object.entries(o)){var i=yield j(n);_e[t]=i}}return _e}));return function(){return o.apply(this,arguments)}}(),t=function(){var e=te((function*(e){return(yield o())[e]}));return function(r){return e.apply(this,arguments)}}(),n=function(){var e=te((function*(){var e=yield o();return Object.keys(e)}));return function(){return e.apply(this,arguments)}}(),i=function(){var e=te((function*(e,r){var n=yield o();r&&(yield t(e)).unsetAll();delete n[e]}));return function(r,o){return e.apply(this,arguments)}}(),a=function(){var e=te((function*(e){if(e){var r=yield o();for(var[t,n]of Object.entries(r))yield n.unsetAll()}_e={}}));return function(r){return e.apply(this,arguments)}}();return{get_cache:t,get_cache_names:n,drop_cache:i,drop_caches:a}}var xe=(e,r)=>{var o=ue(r.mail),t=me(r.log,o,null==r?void 0:r.name),n=ge(),i=function(e,r){var o,t,n=function(){var o=te((function*(o){var t=ee(ee(ee({},e.db.options),o||{}),{},{log:r,cache:be(e,r)}),n=yield E(e.db.config,t);return n.get_model=n.getModel,n}));return function(e){return o.apply(this,arguments)}}(),i=function(){var o=te((function*(o,t){var n=ee(ee(ee({},e.db.options),t||{}),{},{log:r});return(yield E(e.db.config,n)).get_model(o)}));return function(e,r){return o.apply(this,arguments)}}(),a={init_connection:(t=te((function*(){return yield n({reset:!0})})),function(){return t.apply(this,arguments)}),fly_connection:(o=te((function*(){return yield n({cache:!1})})),function(){return o.apply(this,arguments)}),get_connection:n,get_model:i,drop_connections:O};return a}(r,t),a=we(r,t),l={config:ee({},r),emailer:o,logger:t,parser:n,db:i,cache:a};function c(){return(c=te((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=l},Se=[401,403];var ke="/var/ipsum",Oe="ipsum.txt",Ee="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",je=1;function qe(e,r){var o=r?r.error:console.error;if(!e)return[];try{var t=[];return e.split("\n").filter((e=>e.indexOf("#")<0)).map((e=>{var[r,o]=e.split("\t");parseInt(o)>=je&&t.push(r)})),t}catch(n){return o("[cron][".concat(d("IPsum"),"] Error getting IPs from content")),[]}}function Ce(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,n=t?t.error:console.error,a=t?t.debug:console.log;if(i.existsSync(e))try{a("[cron][".concat(d("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee,o=arguments.length>2?arguments[2]:void 0,t=o?o.error:console.error;L.get(r,(r=>{var o=[];r.on("data",(e=>{o.push(e)})).on("end",(()=>{var r=Buffer.concat(o).toString();e(r)}))})).on("error",(r=>{t("[cron][".concat(d("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((n=>{var l=o.join(e,Oe);i.writeFileSync(l,n,{encoding:"utf8",flag:"w"});var c=n.split("\n").length,u=qe(n,t),s=u.length;a("[cron][".concat(d("IPsum"),"] File downloaded. ").concat(c," ips on the list (").concat(s," appearing in ").concat(je," or more lists)")),r&&r(u)}))}catch(l){n("[cron][".concat(d("IPsum"),"] Error ").concat(l," updating the file"))}else n("[cron][".concat(d("IPsum"),"] Folder ").concat(e," does not exist"))}function Pe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke,r=arguments.length>1?arguments[1]:void 0,t=arguments.length>2?arguments[2]:void 0,n=t?t.debug:console.log,a=t?t.warn:console.log,l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke,r=arguments.length>1?arguments[1]:void 0,t=r?r.error:console.error;if(!i.existsSync(e))return r&&t("[cron][".concat(d("IPsum"),"] Folder ").concat(e," does not exist")),[];var n=o.join(e,Oe);return i.existsSync(n)?qe(i.readFileSync(n,{encoding:"utf8"}),r):(r&&t("[cron][".concat(d("IPsum"),"] File ").concat(n," does not exist")),[])}(e,t);return l.length>0?(r&&r(l),n("[cron][".concat(d("IPsum"),"] File contains ").concat(l.length," ips")),l):(a("[cron][".concat(d("IPsum"),"] File is empty. Launching update...")),Ce(e,r,t),[])}var Re=["52.212.247.108","54.218.32.58","170.106.82.193","110.166.71.39","205.210.31.240 ","134.122.52.203","165.232.105.25","66.249.73.200","35.206.153.204","199.244.88.227","198.12.222.107","212.128.118.10"];var Ie=t(import.meta.url),Le=o.dirname(Ie),Me=o.resolve(Le,"./miolo.ico"),Fe=o.resolve(Le,"../../../.."),Je=void 0,Ne=["127.0.0.1","::1:"];var Te=function(e,r){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(Ne.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!=Je)return Je;Ne=[...Ne,...r||[]];var t=i.readFileSync(e);return Je=T.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),a=n.city(e);return{country:a.country.isoCode,city:null===(t=a.city)||void 0===t||null===(t=t.names)||void 0===t?void 0:t.en}}catch(l){o.error("[geoip] Error localizing IP ".concat(e,":")),o.error(l)}return{country:"",city:""}},Ae={total:0};var Ue=e=>{var r=[e.headers["x-real-ip"],e.headers["x-orig-ip"],e.ip,"127.0.0.1"];for(var o of r)if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(o))return o};var ze=t(import.meta.url),Be=o.dirname(ze),Ge=a(o.resolve(Be,"./robots.txt"),"utf8");var We=(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 U.encode(n,t)}(o||{},t)};function i(){return i=te((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)}))},De=(e,r)=>{var{auth_user:o,realm:t,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=te((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(c){}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))))};class He{constructor(e,r){this.options=e,this.logger=r,this._cache=void 0}init_cache(){var e=this;return te((function*(){return null==e._cache&&(e.logger.silly("[session-store] Initing store"),e._cache=yield j(e.options)),e._cache}))()}get(e,r,o){var t=this;return te((function*(){var r=yield t.init_cache(),o=yield r.getItem(e);try{var n=JSON.parse(o);return t.logger.silly("[session-store] Get session for ".concat(e,": ").concat(JSON.stringify(n))),n}catch(i){return void t.logger.silly("[session-store] No session for ".concat(e))}}))()}set(e,r,o,t){var n=this;return te((function*(){n.logger.silly("[session-store] Set session for ".concat(e));var o=yield n.init_cache(),t=void 0;try{t=JSON.stringify(r)}catch(i){}yield o.setItem(e,t)}))()}destroy(e,r){var o=this;return te((function*(){o.logger.silly("[session-store] Destroy session for ".concat(e));var r=yield o.init_cache();yield r.unsetItem(e)}))()}}function Ye(e,r){var o=function(e,r){return ye(e.cache.default,e.cache.session,r)}({cache:e},r);return new He(o,r)}var Ke=(e,r,o)=>r(null,e.id),Ve=(e,r,o)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},Ze=(e,r,o,t)=>{o(Error("You need to define auth.passport.local_auth_user"),null)},Qe=(e,r,o,t)=>{var{get_user_id:n,find_user_by_id:i,local_auth_user:a,url_login:l,url_logout:c,url_login_redirect:u,url_logout_redirect:s}=r,d=n||Ke,f=i||Ve,v=a||Ze,p=l||"/login",m=c||"/logout",h=new B.Strategy(((r,o,t)=>{v(r,o,t,e.context.miolo)}));function g(){return(g=te((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(o){}yield r()}))).apply(this,arguments)}!function(e,r,o){var t=Ye(o,e.context.miolo.logger);e.keys=[r.secret||"*secret*"];var n=ee({store:t},r.options||{});e.use(G(n,e))}(e,o,t),z.serializeUser(((r,o)=>{process.nextTick((function(){d(r,o,e.context.miolo)}))})),z.deserializeUser(((r,o)=>{process.nextTick((function(){f(r,o,e.context.miolo)}))})),z.use(h),e.use(z.initialize()),e.use(z.session()),e.use((function(e,r){return g.apply(this,arguments)}));var y=function(){var e=te((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!=s&&e.redirect(s)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,o){return e.apply(this,arguments)}}(),b=new A;b.post(p,((e,r)=>z.authenticate("local",function(){var r=te((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))),b.get(m,y),b.post(m,y),e.use(b.routes())},Xe=(e,r,o)=>{try{var t=e[r];if(null!=t&&0!=t)return o(t)}catch(n){}},$e=(e,r)=>{var o=e.context.miolo.logger;Xe(r,"cors",(r=>{if("simple"==r)o.debug("Setting CORS the simple way"),e.use(function(){var e=te((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(W(t))}})),Xe(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(D(t,n))}))},er=function(){var e=te((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),rr=function(){var e=te((function*(e,r){return r}));return function(r,o){return e.apply(this,arguments)}}(),or={require:!1,action:"redirect",redirect_url:"/",error_code:401},tr={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},nr=e=>{var o=(null==e?void 0:e.crud)||[];if(!o)return[];if(!Array.isArray(o))return[];var t=[];return o.map((o=>{var n=null==o?void 0:o.routes;if(n&&Array.isArray(n)){var i=(null==o?void 0:o.bodyField)||(null==e?void 0:e.bodyField),a=(null==o?void 0:o.before)||(null==e?void 0:e.before)||er,l=(null==o?void 0:o.after)||(null==e?void 0:e.after)||rr,c=r(or,(null==e?void 0:e.auth)||{},(null==o?void 0:o.auth)||{}),u=[];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:r(tr,(null==d?void 0:d.useUserFields)||{}),auth:r(c,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};u.push(f)}}u.length>0&&t.push({prefix:(null==o?void 0:o.prefix)||"",routes:u})}})),t};function ir(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?H.parse(r):{}}function ar(e,r){function o(e){return t.apply(this,arguments)}function t(){return(t=te((function*(r){r.miolo.logger.info("[router] ".concat(e.name,"()"));var o=r.request.fields;try{r.miolo.logger.debug("[router] ".concat(e.name,"() Calling with params ").concat(JSON.stringify(o)))}catch(n){}var t=yield e(r.miolo,o);try{r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result ").concat(JSON.stringify(t)))}catch(n){}r.body=t}))).apply(this,arguments)}return Object.defineProperty(o,"name",{value:e.name,writable:!1}),o}function lr(e,r,o){r.map((r=>{var t=r.prefix;r.routes.map((r=>{for(var n=function(){var e=te((function*(e,o){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&&"w"===o)||(n||("error"==i.action?(e.miolo.logger.error("[miolo-router] Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(e.miolo.logger.warn("[miolo-router] Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(e.miolo.logger.error("[miolo-router] Crud path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r,o){return e.apply(this,arguments)}}(),i=function(){var e=te((function*(e,o,t){var i=yield e.miolo.db.get_model(r.name);if(!i)throw e.miolo.logger.error("[miolo-router] Could not get model for ".concat(r.name)),new Error("[miolo-router] Could not get model for ".concat(r.name));var a,l={};try{var c;if(!(yield n(e,o)))return void(e.body={});var u=!0;if(null!=r&&r.before&&(u=yield r.before(e)),!u)return void(e.body={});var s=null==e||null===(c=e.session)||void 0===c||null===(c=c.user)||void 0===c?void 0:c.id,d={};!0===r.useUserFields.use&&(d=r.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield t(i,f),null!=r&&r.after&&(l=yield r.after(e,l))}catch(v){e.miolo.logger.error("[miolo-router] Unexpected error on CRUD ".concat(r.name,"-").concat(o)),e.miolo.logger.error(v)}a=l,l=null==r.bodyField?a:{[r.bodyField]:a},e.body=l}));return function(r,o,t){return e.apply(this,arguments)}}(),a=function(){var e=te((function*(e){yield i(e,"r",function(){var r=te((function*(r,o){var t=ir(e.request.url),n={transaction:void 0};return yield r.read(t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=te((function*(e){yield i(e,"r",function(){var r=te((function*(r,o){var t=ir(e.request.url),n={transaction:void 0};return yield r.keyList(t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=te((function*(e){yield i(e,"r",function(){var r=te((function*(r,o){var t=ir(e.request.url),n={transaction:void 0};return yield r.find(t.id,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=te((function*(e){yield i(e,"r",function(){var r=te((function*(r,o){var t=ir(e.request.url),n={transaction:void 0};return yield r.distinct(t.distinct_field,t,n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=te((function*(e){yield i(e,"w",function(){var r=te((function*(r,o){var t,n=e.request.fields;null!=o&&null!==(t=o.fieldNames)&&void 0!==t&&t.created_by&&(n[o.fieldNames.created_by]=o.uid);var i={transaction:void 0};return yield r.insert(n,i)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=te((function*(e){yield i(e,"w",function(){var r=te((function*(r,o){var t,n=e.request.fields;null!=o&&null!==(t=o.fieldNames)&&void 0!==t&&t.last_update_by&&(n[o.fieldNames.last_update_by]=o.uid);var i={transaction:void 0};return yield r.update(n,{id:n.id},i)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=te((function*(e){yield i(e,"w",function(){var r=te((function*(r,o){var t=e.request.fields,n={transaction:void 0};return yield r.delete({id:t.id},n)}));return function(e,o){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=t?"/".concat(t,"/").concat(r.url):"/".concat(r.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");o.info("[miolo-router] Routing table ".concat(r.name," to ").concat(v));var p=r.mode.indexOf("r")>=0,m=r.mode.indexOf("w")>=0,h=r.mode.indexOf("u")>=0||m;p&&(e.get("".concat(v,"/find"),(e=>c(e))),e.get("".concat(v,"/read"),(e=>a(e))),e.get("".concat(v,"/distinct"),(e=>u(e))),e.get("".concat(v,"/key_list"),(e=>l(e)))),h&&(e.post("".concat(v,"/save"),(e=>s(e))),e.post("".concat(v,"/update"),(e=>d(e)))),m&&e.post("".concat(v,"/delete"),(e=>f(e)))}))}))}var cr=e=>{var o=(null==e?void 0:e.queries)||[];if(!o)return[];if(!Array.isArray(o))return[];var t=[];return o.map((o=>{var n=null==o?void 0:o.routes;if(n&&Array.isArray(n)){var i=(null==o?void 0:o.before)||(null==e?void 0:e.before)||er,a=(null==o?void 0:o.after)||(null==e?void 0:e.after)||rr,l=r(or,(null==o?void 0:o.auth)||{},(null==e?void 0:e.auth)||{}),c=[];for(var u of n)if(u.url){var s=void 0;if(u.callback||u.callback_fn){s=u.callback||ar(u.callback_fn);var d={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:s,auth:r(l,(null==u?void 0:u.auth)||{}),before:(null==u?void 0:u.before)||i,after:(null==u?void 0:u.after)||a};c.push(d)}}t.push({prefix:(null==o?void 0:o.prefix)||"",routes:c})}})),t};function ur(e,r){var o=e.context.miolo.logger,t=new A;try{var n=nr(r),i=cr(r),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&&lr(t,n,o),l&&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,"/");var a=r.auth,l=!0===a.require||"read-only"===a.require&&"POST"===r.method;o.info("[miolo-router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i).concat(l?" (auth)":""));var c=function(){var e=te((function*(e){var o,t=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return!l||(t||("error"==a.action?(e.miolo.logger.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(e.miolo.logger.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(e.miolo.logger.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),t)}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=te((function*(e){var o={};try{try{var t;if("GET"==r.method&&(null===(t=e.request)||void 0===t||!t.fields)&&e.request.url.indexOf("?")>0){var n=ir(e.request.url);n&&(e.request.fields=n)}}catch(a){e.miolo.logger.error("[miolo-router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield c(e)))return;var i=!0;if(null!=r&&r.before&&(i=yield r.before(e)),!i)return;o=yield r.callback(e),null!=r&&r.after&&(o=yield r.after(e,o))}catch(l){e.miolo.logger.error("[miolo-router] Unexpected error on Query ".concat(r.name)),e.miolo.logger.error(l)}return o}));return function(r){return e.apply(this,arguments)}}(),s=r.method.toLowerCase();e[s](i,(e=>u(e,r)))}))}))}(t,i,o)}catch(c){o.error("[miolo-router] Error initing the router."),o.error("[miolo-router] routes:"),o.error(r),o.error(c)}e.use(t.routes())}var sr=t(import.meta.url),dr=o.dirname(sr),fr=a(o.resolve(dr,"fallback_index.html"),"utf8");function vr(e){return e?e/1e6:0}function pr(e){return e?e/1e6:0}function mr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var o,t,n,i;o=e.logger,t=Math.round(vr(V.freemem()),2),n=Math.round(vr(V.totalmem()),2),(i=Math.round(100*t/n,2))>80?o.error("[cron][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")):o.info("[cron][".concat(d("SysCheck"),"] RAM ").concat(f(t)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")),Z.check("/",(function(e,r){var t=Math.round(pr(r.used),2),n=Math.round(pr(r.total),2),i=Math.round(pr(r.free),2);i<1?o.error("[cron][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)")):o.info("[cron][".concat(d("SysCheck"),"] DISK ").concat(f(t)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function hr(e,r){var o=e.context.miolo,t=o.logger,n=[mr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Ce(e.config.http.ratelimit.ipsum_folder||ke,(r=>{e.logger.info("[cron][".concat(d("IPsum"),"] File downloaded. ").concat(p(r.length)," ips will be ").concat(f("blacklisted"),"!"))}),e.logger)},start:!0},...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 K((null==r?void 0:r.cronTime)||"*/5 * * * *",(o=>{try{t.silly("[cron][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,o)}catch(n){t.error("[cron][Custom Job ".concat(d(i),"] Error at onTick()")),t.error(n)}}),(()=>{if(t.silly("[cron][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(o){t.error("[cron][Custom Job ".concat(d(i),"] Error at onComplete()")),t.error(o)}}),!1,(null==r?void 0:r.timezone)||"Europe/Madrid")}(o,e);i.push({name:r,job:t,running:!1})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||t.error("[cron] Job ".concat(d(e)," Not Found")),r},l=e=>{try{return e.job.start(),e.running=!0,t.debug("[cron][Job ".concat(d(e.name),"] ").concat(g("started!"))),1}catch(r){return t.error("[cron][Job ".concat(d(e.name),"] Error starting it")),t.error(r),0}},c=e=>{try{return e.job.stop(),e.running=!1,t.debug("[cron][Job ".concat(d(e.name),"] ").concat(y("stopped!"))),1}catch(r){return t.error("[cron][Job ".concat(d(e.name),"] Error stopping it")),t.error(r),0}};return e.cron={jobs:i,start_one:e=>{var r=a(e);return r?[l(r),r.name]:[0,""]},start:()=>{try{var e=[],r=[];i.map((o=>{1==l(o)?e.push(o.name):r.push(o.name)})),e.length>0&&t.info("[cron] Started ".concat(e.length," jobs: ").concat(e)),r.length>0&&t.warn("[cron] Could not start ".concat(r.length," jobs: ").concat(r))}catch(o){t.error("[cron] start() error: ".concat(o))}},stop_one:e=>{var r=a(e);return r?[c(r),r.name]:[0,""]},stop:()=>{try{var e=[],r=[];i.map((o=>{1==c(o)?e.push(o.name):r.push(o.name)})),e.length>0&&t.info("[cron] Stopped ".concat(e.length," jobs: ").concat(e)),r.length>0&&t.warn("[cron] Could not stop ".concat(r.length," jobs: ").concat(r))}catch(o){t.error("[cron] stop() error: ".concat(o))}}},e}var gr=(e,r,o)=>new Promise(((t,n)=>{e.listen(r,o,(e=>{e?n(e):t()}))}));function yr(o,t){var n,i,a,l=new e,u=function(e){var o,t=r(ce,e);return t.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),t.use_catcher=!(null==t||null===(o=t.http)||void 0===o||!o.catcher_url),t}(o);xe(l,u),$e(l,u.http),(e=>{e.use(P({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:R.Z_SYNC_FLUSH},deflate:{flush:R.Z_SYNC_FLUSH},br:!1})),e.use(C(q({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(l),function(e){var r=e.context.miolo.logger;function o(){return(o=te((function*(e){if(e){var o=this.headers["x-real-ip"]||this.headers["x-orig-ip"]||this.ip||"127.0.0.1",t=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof t&&(t=500):(t=406,e.message="Unsupported type"),Se.indexOf(t)>=0?r.warn("[".concat(o,"] ").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 o.apply(this,arguments)}}(l),function(e,r){var o=e.context.miolo,t=Pe(null==r?void 0:r.ipsum_folder,void 0,o.logger),n={driver:"memory",db:new Map,id:e=>e.request.ip,headers:{remaining:"Rate-Limit-Remaining",reset:"Rate-Limit-Reset",total:"Rate-Limit-Total"},disableHeader:!1,max:(null==r?void 0:r.max)||1e3,duration:(null==r?void 0:r.duration)||6e4,errorMessage:(null==r?void 0:r.errorMessage)||"Rate Limit reached",whitelist:(null==r?void 0:r.whitelist)||(e=>{var o=(null==r?void 0:r.whitelist_ips)||[];return!!o&&o.indexOf(e.request.ip)>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var o=e.request.ip,n=[...t,...Re,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(o)>=0;return n&&e.miolo.logger.info("Rejecting ".concat(f("blacklisted")," ").concat(s(o))),n})};e.use(I(n))}(l,null===(n=u.http)||void 0===n?void 0:n.ratelimit),((e,r)=>{var{favicon:o,folders:t}=r,n=o||Me;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(Fe,""))),e.use(J(n)),Object.entries(t)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(Fe,""))),e.use(M(i,F(a,{index:!1})))})(l,null===(i=u.http)||void 0===i?void 0:i.static),function(e,r){var o=function(){var e=te((function*(e,r){return{}}));return function(r,o){return e.apply(this,arguments)}}(),t=function(){var e=te((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=te((function*(e,r){var o,t,i,a,l,u,v=e.miolo.logger,h=Ue(e),g=N.now();e.request.body=ee(ee({},e.request.fields),e.request.files),Ae.total+=1,Ae[h]=(Ae[h]||0)+1,e.requestId=Ae.total,e.request.ip=h;var y=!0===(null==n||null===(o=n.geoip)||void 0===o?void 0:o.enabled),b={};y&&(b=Te(h,n.geoip,v)),e.request.geoip=b;var _=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,w=y?!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,")"):"":"",x="".concat(s(h)).concat(w," ").concat(d(e.request.method)," ").concat(d(_)," [").concat(m(Ae[h]),"/").concat(m(e.requestId),"]"),S=null!=e.request.body?JSON.stringify(e.request.body):"";v.info("".concat(x," - START")),v.debug("".concat(x," - Body: ").concat(S));var k=yield n.onStart(e,{started:g,description:"pending"});yield r();var O=null==e||null===(u=e.session)||void 0===u?void 0:u.user,E="";null!=O&&(null!=O&&O.id?E=" - uid ".concat(null==O?void 0:O.id):null!=O&&O.token&&(E=" - token ".concat(null==O?void 0:O.token)));var j,q=e.response.status,C=q;200==q?j=p:q>200&&q<=299?(j=f,e.response.redirected&&e.response.url&&(C+=" -> ".concat(e.response.url))):j=c;var P="[".concat(j(C),"]"),R=parseFloat((N.now()-g)/1e3).toFixed(2),I=R<n.lazy?p:R<n.slow?f:c,L=R<n.lazy?"Ok":R<n.slow?"lazy":"slow",M=null!=e.session?JSON.stringify(e.session):"";v.debug("".concat(x," - Session: ").concat(M));var F=null!=e.body?JSON.stringify(e.body):"";v.debug("".concat(x," - Response: ").concat(F)),yield n.onDone(e,k,{started:g,elapsed:R,description:L}),v.info("".concat(x," - DONE ").concat(P).concat(E," (").concat(I(L),": ").concat(I(R),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(l,null==u||null===(a=u.http)||void 0===a?void 0:a.request),function(e){function r(){return(r=te((function*(e){e.body=Ge}))).apply(this,arguments)}var o=new A;o.get("/robots.txt",(function(e){return r.apply(this,arguments)})),e.use(o.routes())}(l),u.use_catcher&&function(e,r){function o(){return o=te((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(h(t),": ").concat(JSON.stringify(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(c("[JS Error]")," on ").concat(h(t),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(c("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(c("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(c("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(c("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(c("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),o.apply(this,arguments)}var t=new A;t.post(r,(function(e){return o.apply(this,arguments)})),e.use(t.routes())}(l,u.http.catcher_url),"guest"==u.auth_type&&We(l,u.auth.guest,null==u?void 0:u.session),"basic"==u.auth_type&&De(l,u.auth.basic),"credentials"==u.auth_type&&Qe(l,u.auth.credentials,null==u?void 0:u.session,null==u?void 0:u.cache),"custom"==u.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 A;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,"'"))}})(l,u.auth.custom);var v=null==u?void 0:u.middlewares;return v&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(l,v),null!=u&&u.routes&&ur(l,u.routes),null!=(null==t?void 0:t.middleware)?l.use(t.middleware):function(e,r,o,t){var n=(null==r?void 0:r.html)||fr;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=te((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(c){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!=c&&c.stack?"".concat(c.toString(),"\n").concat(c.stack):c.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=Y(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):\n".concat(a.toString())),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 c(){return(c=te((function*(e){var r,n,c={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},u=yield i(e),s=a(e,c,u),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 c.apply(this,arguments)}))}(l,t,u.http,null==u?void 0:u.auth),hr(l,null==u?void 0:u.cron),function(e,r){var o,t=e.context.miolo.logger,n=function(){var o=te((function*(){try{var o,n,i;if(null!=(null===(o=e.http)||void 0===o?void 0:o.server))return void t.warn("[http][start] Server already running on ".concat(null==e||null===(n=e.http)||void 0===n?void 0:n.hostname,":").concat(null==e||null===(i=e.http)||void 0===i?void 0:i.port));var a=Q.createServer(e.callback()),l=X({server:a}),c=function(){var o=te((function*(){try{yield l.terminate(),delete e.http.server,t.info("[http][stop] miolo has been shutdowned from ".concat(r.hostname,":").concat(r.port))}catch(o){t.error("[http][stop] error: ".concat(o))}}));return function(){return o.apply(this,arguments)}}();e.http.server=a,e.http.stop=c,yield gr(a,r.port,r.hostname),t.info("[http][start] miolo is listening on ".concat(r.hostname,":").concat(r.port))}catch(u){t.error("[http][start] error: ".concat(u))}}));return function(){return o.apply(this,arguments)}}();e.http={server:void 0,start:n,stop:(o=te((function*(){t.warn("[http] stop() stop() function still not attached. Is server running?")})),function(){return o.apply(this,arguments)}),hostname:r.hostname,port:r.port}}(l,null==u?void 0:u.http),l.start=te((function*(){yield l.context.miolo.db.init_connection(),yield l.http.start(),l.cron.start()})),l.stop=te((function*(){l.context.miolo.db.drop_connections(),yield l.http.stop(),l.cron.stop()})),l.restart=te((function*(){yield l.stop(),yield l.start()})),l}export{yr as miolo,ue as miolo_emailer,me as miolo_logger,ge as miolo_parser};
11
+ import e from"koa";import r from"deepmerge";import t from"node:path";import{fileURLToPath as o}from"node:url";import n from"nodemailer";import i,{readFileSync as a}from"node:fs";import{uncolor as l,red as c,gray as u,magenta as s,cyan as d,yellow as f,red_light as v,green as p,cyan_light as m,blue as h,green_bold as g,yellow_bold as y}from"tinguir";import b from"node:util";import _,{transports as w,createLogger as x,format as S}from"winston";import{intre_now as k}from"intre";import{dropConnections as O,getConnection as E}from"calustra";export{getConnection as miolo_db_connection}from"calustra";import{cacheiro as j}from"cacheiro";export{cacheiro as miolo_cacher}from"cacheiro";import q from"koa-better-body";import C from"koa-convert";import P from"koa-compress";import{constants as R}from"node:zlib";import I from"koa-ratelimit";import L from"node:https";import M from"koa-mount";import F from"koa-static";import J from"koa-favicon";import{performance as N}from"node:perf_hooks";import{Reader as T}from"@maxmind/geoip2-node";import A from"@koa/router";import U from"jwt-simple";import z from"koa-passport";import B from"passport-local";import G from"koa-session";import W from"@koa/cors";import D from"koa-proxies";import H from"qs";import{renderToString as Y}from"react-dom/server";import{CronJob as K}from"cron";import V from"node:os";import Z from"diskspace";import Q from"node:http";import{createHttpTerminator as X}from"http-terminator";function $(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 ee(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?$(Object(t),!0).forEach((function(r){ne(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):$(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function re(e){var r=function(e,r){if("object"!=typeof e||!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:r+""}function te(e,r,t,o,n,i,a){try{var l=e[i](a),c=l.value}catch(u){return void t(u)}l.done?r(c):Promise.resolve(c).then(o,n)}function oe(e){return function(){var r=this,t=arguments;return new Promise((function(o,n){var i=e.apply(r,t);function a(e){te(i,o,n,a,l,"next",e)}function l(e){te(i,o,n,a,l,"throw",e)}a(void 0)}))}}function ne(e,r,t){return(r=re(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var ie=o(import.meta.url),ae=t.dirname(ie),le=864e6,ce={name:"miolo",http:{port:8001,hostname:"localhost",catcher_url:"/sys/jserror",static:{favicon:t.resolve(ae,"../static/img/miolo.ico"),folders:{}},cors:!1,proxy:!1,ratelimit:{max:1e3,duration:6e4,errorMessage:"Rate Limit reached",whitelist_ips:[],blacklist_ips:[],ipsum_folder:"/var/ipsum"},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:le,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:{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/afialapis/%MIOLO%.log",zippedArchive:!0,maxsize:20971520,maxFiles:20},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:[],cache:{default:{type:"combined",redis:{host:"127.0.0.1",port:6379},version:1,clean:!1},calustra:{namespace:"miolo-calustra",ttl:864e5},session:{namespace:"miolo-session",ttl:le},custom:{}}};function ue(e){var{options:r,defaults:t,silent:o}=e,i=n.createTransport(r,t);function a(){return(a=oe((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=i.sendMail(e);return r.ok=!(null==r||!r.messageId),r}catch(t){return{error:t,ok:!1}}}))).apply(this,arguments)}var l={send:function(e){return a.apply(this,arguments)},verify:function(){console.info("[miolo][Verify][MAILER] Verifying..."),i.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 l}var{combine:se,timestamp:de,_label:fe,printf:ve,errors:pe}=S,me=function(e,r){var o,n,a,p,m=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"miolo",h={silly:u,debug:s,verbose:d,info:f,warn:v,error:c},g={silly:"sly",debug:"dbg",verbose:"vbs",info:"inf",warn:"wrn",error:"err"},y=r=>{var t,o=h[r.level],n=new Date(r.timestamp).toLocaleString((null==e||null===(t=e.format)||void 0===t?void 0:t.locale)||"en"),i="[".concat(m,"] ").concat(o(n)," ").concat(o(g[r.level])," ").concat(r.message);return r.stack?"".concat(i,"\n").concat(r.stack):i},S=[];!0===(null==e||null===(o=e.console)||void 0===o?void 0:o.enabled)&&S.push(new w.Console({humanReadableUnhandledException:!0,level:(null==e||null===(p=e.console)||void 0===p?void 0:p.level)||(null==e?void 0:e.level)||"silly",handleExceptions:!0}));if(!0===(null==e||null===(n=e.file)||void 0===n?void 0:n.enabled)){var O,E,j=new w.File({filename:null!=e&&null!==(O=e.file)&&void 0!==O&&O.filename?e.file.filename.replace("%MIOLO%",m):"/var/log/afialapis/miolo.log",level:(null==e||null===(E=e.file)||void 0===E?void 0:E.level)||(null==e?void 0:e.level)||"info",humanReadableUnhandledException:!0,handleExceptions:!0,maxRetries:10});!function(e){process.on("SIGHUP",(function(){var r=t.join(e.dirname,e._getFile(!1));return function(){console.log("[miolo][file-logger] SIGHUP received. Reopening ".concat(r,"..."));try{e._stream&&(e._stream.end(),e._stream.destroy());var t=i.createWriteStream(r,e.options);t.setMaxListeners(1/0),e._size=0,e._stream=t,e.opening=!1,e.emit("open",r),console.log("[miolo][file-logger] Reopened ".concat(r," successfully"))}catch(o){console.error("[miolo][file-logger] Error reopening ".concat(r,": ").concat(o.toString()))}}()}))}(j),S.push(j);var q=r=>{var o,n,a=t.join(j.dirname,j.filename),l=y({level:"info",message:"[logger][file-rotate] ".concat(r,"\n"),timestamp:k()});try{i.accessSync(a,i.constants.F_OK),i.appendFileSync(a,l)}catch(c){i.writeFileSync(a,l,{encoding:"utf-8"})}!0===(null==e||null===(o=e.console)||void 0===o?void 0:o.enabled)&&(j.levels[(null==e||null===(n=e.console)||void 0===n?void 0:n.level)||(null==e?void 0:e.level)||"error"]>=j.levels.info&&console.log(l))};j.on("finish",(function(e){q("Log done")})),j.on("error",(function(e){q(c("Error: ".concat(e)))}))}if(!0===(null==e||null===(a=e.mail)||void 0===a?void 0:a.enabled)){var C=function(e,r){var t=function(t){_.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 b.inherits(t,_.Transport),t.prototype.name="MailerLogger",t.prototype.log=function(t,o){var n=this,i="",a="";try{try{i=t.message.split("\n")[0]}catch(s){i=t.message.toString()}i=l(i)}catch(d){i="Could not create a title for the error (".concat(d.toString(),")")}try{try{a=l(t.message)}catch(d){a=t.message.toString()}}catch(d){a="Could not create a body for the error (".concat(d.toString(),")")}var c="".concat(null==e?void 0:e.name," [").concat(t.level.toUpperCase(),"] ").concat(i),u={from:this.from,to:this.to,subject:c,text:a};r.send(u,(function(){n.emit("logged"),o(null,!0)}))},t}(e.mail,r);w.MailerLogger=C,S.push(new w.MailerLogger({humanReadableUnhandledException:!0,handleExceptions:!0}))}var P=x({level:(null==e?void 0:e.level)||"silly",format:se(pe({stack:!0}),de(),ve(y)),transports:S});try{P.info("[logger] Inited for ".concat(P.transports.map((e=>"".concat(e.name," (").concat(e.level,")").concat(e.silent?c(" SILENT!"):""))).join(", ")))}catch(R){}return P};class he{parse_value_str(e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong str value passed: ".concat(e);return r}return e.toString()}parse_field_str(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected str value not passed for ".concat(r);return o}return this.parse_value_str(e[r],t,o)}parse_value_int(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=parseInt(e);if(null==o||isNaN(o)){if(r)throw"Wrong int value passed: ".concat(e);return t}return o}parse_field_int(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected int value not passed for ".concat(r);return o}return this.parse_value_int(e[r],t,o)}parse_value_float(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,o=parseFloat(e);if(null==o||isNaN(o)){if(r)throw"Wrong float value passed: ".concat(e);return t}return e}parse_field_float(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected float value not passed for ".concat(r);return o}return this.parse_value_float(e[r],t,o)}parse_value_bool(e){if(null!=e&&null!=e)return!0===e||"true"===e||"True"===e||1===e||"1"===e||!1!==e&&"false"!==e&&"False"!==e&&0!==e&&"0"!==e&&(arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0);if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])throw"Wrong bool value passed for ".concat(name)}parse_field_bool(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected bool value not passed for ".concat(r);return o}return this.parse_value_bool(e[r],t,o)}parse_value_obj(e){var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0;if(null==e||null==e){if(r)throw"Wrong obj value passed: ".concat(e);return t}if(0==Object.keys(e).length){if(r)throw"Empty obj value passed: ".concat(e);return t}if("object"!=typeof e)throw"Wrong obj value passed: ".concat(e);return e}parse_field_obj(e,r){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:void 0;if(!(r in e)){if(t)throw"Expected obj value not passed for ".concat(r);return o}return this.parse_value_obj(e[r],t,o)}}var ge=()=>new he;function ye(e,r,t){return{type:(null==r?void 0:r.type)||(null==e?void 0:e.type),redis:(null==r?void 0:r.redis)||(null==e?void 0:e.redis),namespace:(null==r?void 0:r.namespace)||(null==e?void 0:e.namespace),version:(null==r?void 0:r.version)||(null==e?void 0:e.version),clean:!0===(null==r?void 0:r.clean)||!0===(null==e?void 0:e.clean),ttl:(null==r?void 0:r.ttl)||(null==e?void 0:e.ttl),log:t}}function be(e,r){return ye(e.cache.default,e.cache.calustra,r)}var _e=void 0;function we(e,r){var t=function(){var t=oe((function*(){if(null==_e){_e={};var t=function(e,r){var t=e.cache.default,o=e.cache.custom||{},n={};for(var[i,a]of Object.entries(o)){var l=ye(t,a,r);l.namespace=l.namespace||"miolo-".concat(i),n[i]=l}return n}(e,r);for(var[o,n]of Object.entries(t)){var i=yield j(n);_e[o]=i}}return _e}));return function(){return t.apply(this,arguments)}}(),o=function(){var e=oe((function*(e){return(yield t())[e]}));return function(r){return e.apply(this,arguments)}}(),n=function(){var e=oe((function*(){var e=yield t();return Object.keys(e)}));return function(){return e.apply(this,arguments)}}(),i=function(){var e=oe((function*(e,r){var n=yield t();r&&(yield o(e)).unsetAll();delete n[e]}));return function(r,t){return e.apply(this,arguments)}}(),a=function(){var e=oe((function*(e){if(e){var r=yield t();for(var[o,n]of Object.entries(r))yield n.unsetAll()}_e={}}));return function(r){return e.apply(this,arguments)}}();return{get_cache:o,get_cache_names:n,drop_cache:i,drop_caches:a}}var xe=(e,r)=>{var t=ue(r.mail),o=me(r.log,t,null==r?void 0:r.name),n=ge(),i=function(e,r){var t,o,n=function(){var t=oe((function*(t){var o=ee(ee(ee({},e.db.options),t||{}),{},{log:r,cache:be(e,r)}),n=yield E(e.db.config,o);return n.get_model=n.getModel,n}));return function(e){return t.apply(this,arguments)}}(),i=function(){var t=oe((function*(t,o){var n=ee(ee(ee({},e.db.options),o||{}),{},{log:r});return(yield E(e.db.config,n)).get_model(t)}));return function(e,r){return t.apply(this,arguments)}}(),a={init_connection:(o=oe((function*(){return yield n({reset:!0})})),function(){return o.apply(this,arguments)}),fly_connection:(t=oe((function*(){return yield n({cache:!1})})),function(){return t.apply(this,arguments)}),get_connection:n,get_model:i,drop_connections:O};return a}(r,o),a=we(r,o),l={config:ee({},r),emailer:t,logger:o,parser:n,db:i,cache:a};function c(){return(c=oe((function*(e,r){e.miolo=l,yield r()}))).apply(this,arguments)}e.use((function(e,r){return c.apply(this,arguments)})),e.context.miolo=l},Se=[401,403];var ke="/var/ipsum",Oe="ipsum.txt",Ee="https://raw.githubusercontent.com/stamparm/ipsum/master/ipsum.txt",je=1;function qe(e,r){var t=r?r.error:console.error;if(!e)return[];try{var o=[];return e.split("\n").filter((e=>e.indexOf("#")<0)).map((e=>{var[r,t]=e.split("\t");parseInt(t)>=je&&o.push(r)})),o}catch(n){return t("[cron][".concat(d("IPsum"),"] Error getting IPs from content")),[]}}function Ce(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,n=o?o.error:console.error,a=o?o.debug:console.log;if(i.existsSync(e))try{a("[cron][".concat(d("IPsum"),"] Updating file...")),function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Ee,t=arguments.length>2?arguments[2]:void 0,o=t?t.error:console.error;L.get(r,(r=>{var t=[];r.on("data",(e=>{t.push(e)})).on("end",(()=>{var r=Buffer.concat(t).toString();e(r)}))})).on("error",(r=>{o("[cron][".concat(d("IPsum"),"] Error downloading remote file (").concat(r.toString(),")")),e("")}))}((n=>{var l=t.join(e,Oe);i.writeFileSync(l,n,{encoding:"utf8",flag:"w"});var c=n.split("\n").length,u=qe(n,o),s=u.length;a("[cron][".concat(d("IPsum"),"] File downloaded. ").concat(c," ips on the list (").concat(s," appearing in ").concat(je," or more lists)")),r&&r(u)}))}catch(l){n("[cron][".concat(d("IPsum"),"] Error ").concat(l," updating the file"))}else n("[cron][".concat(d("IPsum"),"] Folder ").concat(e," does not exist"))}function Pe(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke,r=arguments.length>1?arguments[1]:void 0,o=arguments.length>2?arguments[2]:void 0,n=o?o.debug:console.log,a=o?o.warn:console.log,l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ke,r=arguments.length>1?arguments[1]:void 0,o=r?r.error:console.error;if(!i.existsSync(e))return r&&o("[cron][".concat(d("IPsum"),"] Folder ").concat(e," does not exist")),[];var n=t.join(e,Oe);return i.existsSync(n)?qe(i.readFileSync(n,{encoding:"utf8"}),r):(r&&o("[cron][".concat(d("IPsum"),"] File ").concat(n," does not exist")),[])}(e,o);return l.length>0?(r&&r(l),n("[cron][".concat(d("IPsum"),"] File contains ").concat(l.length," ips")),l):(a("[cron][".concat(d("IPsum"),"] File is empty. Launching update...")),Ce(e,r,o),[])}var Re=["52.212.247.108","54.218.32.58","170.106.82.193","110.166.71.39","39.107.54.8","205.210.31.240 ","134.122.52.203","165.232.105.25","66.249.73.200","35.206.153.204","199.244.88.227","198.12.222.107","212.128.118.10"];var Ie=o(import.meta.url),Le=t.dirname(Ie),Me=t.resolve(Le,"./miolo.ico"),Fe=t.resolve(Le,"../../../.."),Je=void 0,Ne=["127.0.0.1","::1:"];var Te=function(e,r){var t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:console;if(function(e){return[...Ne,...(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[])||[]].indexOf(e)>=0}(e,null==r?void 0:r.local_ips))return{local:!0,country:"",city:""};try{var o,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]:console;try{if(null!=Je)return Je;var t=i.readFileSync(e);return Je=T.openBuffer(t)}catch(o){return r.error("[geoip] Error initing:"),void r.error(o)}}(null==r?void 0:r.db,t),a=n.city(e);return{country:a.country.isoCode,city:null===(o=a.city)||void 0===o||null===(o=o.names)||void 0===o?void 0:o.en}}catch(l){t.error("[geoip] Error localizing IP ".concat(e,":")),t.error(l)}return{country:"",city:""}},Ae={total:0};var Ue=e=>{var r=[e.headers["x-real-ip"],e.headers["x-orig-ip"],e.ip,"127.0.0.1"];for(var t of r)if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(t))return t};var ze=o(import.meta.url),Be=t.dirname(ze),Ge=a(t.resolve(Be,"./robots.txt"),"utf8");var We=(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 U.encode(n,o)}(t||{},o)};function i(){return i=oe((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)}))},De=(e,r)=>{var{auth_user:t,realm:o,paths:n}=r;function i(e,r){return a.apply(this,arguments)}function a(){return(a=oe((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(c){}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))))};class He{constructor(e,r){this.options=e,this.logger=r,this._cache=void 0}init_cache(){var e=this;return oe((function*(){return null==e._cache&&(e.logger.silly("[session-store] Initing store"),e._cache=yield j(e.options)),e._cache}))()}get(e,r,t){var o=this;return oe((function*(){var r=yield o.init_cache(),t=yield r.getItem(e);try{var n=JSON.parse(t);return o.logger.silly("[session-store] Get session for ".concat(e,": ").concat(JSON.stringify(n))),n}catch(i){return void o.logger.silly("[session-store] No session for ".concat(e))}}))()}set(e,r,t,o){var n=this;return oe((function*(){n.logger.silly("[session-store] Set session for ".concat(e));var t=yield n.init_cache(),o=void 0;try{o=JSON.stringify(r)}catch(i){}yield t.setItem(e,o)}))()}destroy(e,r){var t=this;return oe((function*(){t.logger.silly("[session-store] Destroy session for ".concat(e));var r=yield t.init_cache();yield r.unsetItem(e)}))()}}function Ye(e,r){var t=function(e,r){return ye(e.cache.default,e.cache.session,r)}({cache:e},r);return new He(t,r)}var Ke=(e,r,t)=>r(null,e.id),Ve=(e,r,t)=>{r(Error("You need to define auth.passport.find_user_by_id"),null)},Ze=(e,r,t,o)=>{t(Error("You need to define auth.passport.local_auth_user"),null)},Qe=(e,r,t,o)=>{var{get_user_id:n,find_user_by_id:i,local_auth_user:a,url_login:l,url_logout:c,url_login_redirect:u,url_logout_redirect:s}=r,d=n||Ke,f=i||Ve,v=a||Ze,p=l||"/login",m=c||"/logout",h=new B.Strategy(((r,t,o)=>{v(r,t,o,e.context.miolo)}));function g(){return(g=oe((function*(e,r){try{e.session.authenticated&&(e.session.user=e.state.user)}catch(t){}yield r()}))).apply(this,arguments)}!function(e,r,t){var o=Ye(t,e.context.miolo.logger);e.keys=[r.secret||"*secret*"];var n=ee({store:o},r.options||{});e.use(G(n,e))}(e,t,o),z.serializeUser(((r,t)=>{process.nextTick((function(){d(r,t,e.context.miolo)}))})),z.deserializeUser(((r,t)=>{process.nextTick((function(){f(r,t,e.context.miolo)}))})),z.use(h),e.use(z.initialize()),e.use(z.session()),e.use((function(e,r){return g.apply(this,arguments)}));var y=function(){var e=oe((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!=s&&e.redirect(s)):(e.body={user:void 0,authenticated:!1},e.response.status=401)}));return function(r,t){return e.apply(this,arguments)}}(),b=new A;b.post(p,((e,r)=>z.authenticate("local",function(){var r=oe((function*(r,t,o,n){if(!1!==t)return e.session.user=e.state.user,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))),b.get(m,y),b.post(m,y),e.use(b.routes())},Xe=(e,r,t)=>{try{var o=e[r];if(null!=o&&0!=o)return t(o)}catch(n){}},$e=(e,r)=>{var t=e.context.miolo.logger;Xe(r,"cors",(r=>{if("simple"==r)t.debug("Setting CORS the simple way"),e.use(function(){var e=oe((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(W(o))}})),Xe(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(D(o,n))}))},er=function(){var e=oe((function*(e){return!0}));return function(r){return e.apply(this,arguments)}}(),rr=function(){var e=oe((function*(e,r){return r}));return function(r,t){return e.apply(this,arguments)}}(),tr={require:!1,action:"redirect",redirect_url:"/",error_code:401},or={use:!1,fieldNames:{created_by:"created_by",last_update_by:"last_update_by"}},nr=e=>{var t=(null==e?void 0:e.crud)||[];if(!t)return[];if(!Array.isArray(t))return[];var o=[];return t.map((t=>{var n=null==t?void 0:t.routes;if(n&&Array.isArray(n)){var i=(null==t?void 0:t.bodyField)||(null==e?void 0:e.bodyField),a=(null==t?void 0:t.before)||(null==e?void 0:e.before)||er,l=(null==t?void 0:t.after)||(null==e?void 0:e.after)||rr,c=r(tr,(null==e?void 0:e.auth)||{},(null==t?void 0:t.auth)||{}),u=[];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:r(or,(null==d?void 0:d.useUserFields)||{}),auth:r(c,(null==d?void 0:d.auth)||{}),before:(null==d?void 0:d.before)||a,after:(null==d?void 0:d.after)||l};u.push(f)}}u.length>0&&o.push({prefix:(null==t?void 0:t.prefix)||"",routes:u})}})),o};function ir(e){var r=e.indexOf("?")>=0?e.substr(e.indexOf("?")+1):"";return r?H.parse(r):{}}function ar(e,r){function t(e){return o.apply(this,arguments)}function o(){return(o=oe((function*(r){r.miolo.logger.info("[router] ".concat(e.name,"()"));var t=r.request.fields;try{r.miolo.logger.debug("[router] ".concat(e.name,"() Calling with params ").concat(JSON.stringify(t)))}catch(n){}var o=yield e(r.miolo,t);try{r.miolo.logger.debug("[router] ".concat(e.name,"() Called with result ").concat(JSON.stringify(o)))}catch(n){}r.body=o}))).apply(this,arguments)}return Object.defineProperty(t,"name",{value:e.name,writable:!1}),t}function lr(e,r,t){r.map((r=>{var o=r.prefix;r.routes.map((r=>{for(var n=function(){var e=oe((function*(e,t){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&&"w"===t)||(n||("error"==i.action?(e.miolo.logger.error("[router] Unauthorized access. Throwing error ".concat(i.error_code)),e.throw(i.error_code,null,{})):"redirect"==i.action?(e.miolo.logger.warn("[router] Unauthorized access. Redirecting to ".concat(i.redirect_url)),e.redirect(i.redirect_url)):(e.miolo.logger.error("[router] Crud path ".concat(r.url," specified auth but no action")),e.body={})),n)}));return function(r,t){return e.apply(this,arguments)}}(),i=function(){var e=oe((function*(e,t,o){var i=yield e.miolo.db.get_model(r.name);if(!i)throw e.miolo.logger.error("[router] Could not get model for ".concat(r.name)),new Error("[router] Could not get model for ".concat(r.name));var a,l={};try{var c;if(!(yield n(e,t)))return void(e.body={});var u=!0;if(null!=r&&r.before&&(u=yield r.before(e)),!u)return void(e.body={});var s=null==e||null===(c=e.session)||void 0===c||null===(c=c.user)||void 0===c?void 0:c.id,d={};!0===r.useUserFields.use&&(d=r.useUserFields.fieldNames);var f={uid:s,fieldNames:d};l=yield o(i,f),null!=r&&r.after&&(l=yield r.after(e,l))}catch(v){e.miolo.logger.error("[router] Unexpected error on CRUD ".concat(r.name,"-").concat(t)),e.miolo.logger.error(v)}a=l,l=null==r.bodyField?a:{[r.bodyField]:a},e.body=l}));return function(r,t,o){return e.apply(this,arguments)}}(),a=function(){var e=oe((function*(e){yield i(e,"r",function(){var r=oe((function*(r,t){var o=ir(e.request.url),n={transaction:void 0};return yield r.read(o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),l=function(){var e=oe((function*(e){yield i(e,"r",function(){var r=oe((function*(r,t){var o=ir(e.request.url),n={transaction:void 0};return yield r.keyList(o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),c=function(){var e=oe((function*(e){yield i(e,"r",function(){var r=oe((function*(r,t){var o=ir(e.request.url),n={transaction:void 0};return yield r.find(o.id,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=oe((function*(e){yield i(e,"r",function(){var r=oe((function*(r,t){var o=ir(e.request.url),n={transaction:void 0};return yield r.distinct(o.distinct_field,o,n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),s=function(){var e=oe((function*(e){yield i(e,"w",function(){var r=oe((function*(r,t){var o,n=e.request.fields;null!=t&&null!==(o=t.fieldNames)&&void 0!==o&&o.created_by&&(n[t.fieldNames.created_by]=t.uid);var i={transaction:void 0};return yield r.insert(n,i)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),d=function(){var e=oe((function*(e){yield i(e,"w",function(){var r=oe((function*(r,t){var o,n=e.request.fields;null!=t&&null!==(o=t.fieldNames)&&void 0!==o&&o.last_update_by&&(n[t.fieldNames.last_update_by]=t.uid);var i={transaction:void 0};return yield r.update(n,{id:n.id},i)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),f=function(){var e=oe((function*(e){yield i(e,"w",function(){var r=oe((function*(r,t){var o=e.request.fields,n={transaction:void 0};return yield r.delete({id:o.id},n)}));return function(e,t){return r.apply(this,arguments)}}())}));return function(r){return e.apply(this,arguments)}}(),v=o?"/".concat(o,"/").concat(r.url):"/".concat(r.url);v.indexOf("//")>=0;)v=v.replace(/\/\//g,"/");t.info("[router] Routing table ".concat(r.name," to ").concat(v));var p=r.mode.indexOf("r")>=0,m=r.mode.indexOf("w")>=0,h=r.mode.indexOf("u")>=0||m;p&&(e.get("".concat(v,"/find"),(e=>c(e))),e.get("".concat(v,"/read"),(e=>a(e))),e.get("".concat(v,"/distinct"),(e=>u(e))),e.get("".concat(v,"/key_list"),(e=>l(e)))),h&&(e.post("".concat(v,"/save"),(e=>s(e))),e.post("".concat(v,"/update"),(e=>d(e)))),m&&e.post("".concat(v,"/delete"),(e=>f(e)))}))}))}var cr=e=>{var t=(null==e?void 0:e.queries)||[];if(!t)return[];if(!Array.isArray(t))return[];var o=[];return t.map((t=>{var n=null==t?void 0:t.routes;if(n&&Array.isArray(n)){var i=(null==t?void 0:t.before)||(null==e?void 0:e.before)||er,a=(null==t?void 0:t.after)||(null==e?void 0:e.after)||rr,l=r(tr,(null==t?void 0:t.auth)||{},(null==e?void 0:e.auth)||{}),c=[];for(var u of n)if(u.url){var s=void 0;if(u.callback||u.callback_fn){s=u.callback||ar(u.callback_fn);var d={url:u.url,method:(null==u?void 0:u.method)||"GET",callback:s,auth:r(l,(null==u?void 0:u.auth)||{}),before:(null==u?void 0:u.before)||i,after:(null==u?void 0:u.after)||a};c.push(d)}}o.push({prefix:(null==t?void 0:t.prefix)||"",routes:c})}})),o};function ur(e,r){var t=e.context.miolo.logger,o=new A;try{var n=nr(r),i=cr(r),a=n.length>0,l=i.length>0;if(!a&&!l)throw"[router] Could not get any route from the passed <routes> param";a&&lr(o,n,t),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,"/");var a=r.auth,l=!0===a.require||"read-only"===a.require&&"POST"===r.method;t.info("[router] Routing ".concat((null===(n=r.callback)||void 0===n?void 0:n.name)||"callback"," to ").concat(r.method," ").concat(i).concat(l?" (auth)":""));var c=function(){var e=oe((function*(e){var t,o=!0===(null==e||null===(t=e.session)||void 0===t?void 0:t.authenticated);return!l||(o||("error"==a.action?(e.miolo.logger.error("Unauthorized access. Throwing error ".concat(a.error_code)),e.throw(a.error_code,null,{})):"redirect"==a.action?(e.miolo.logger.warn("Unauthorized access. Redirecting to ".concat(a.redirect_url)),e.redirect(a.redirect_url)):(e.miolo.logger.error("Route path ".concat(r.url," specified auth but no action")),e.body={})),o)}));return function(r){return e.apply(this,arguments)}}(),u=function(){var e=oe((function*(e){var t={};try{try{var o;if("GET"==r.method&&(null===(o=e.request)||void 0===o||!o.fields)&&e.request.url.indexOf("?")>0){var n=ir(e.request.url);n&&(e.request.fields=n)}}catch(u){e.miolo.logger.error("[router] Error while trying to qet query params for ".concat(e.request.url))}if(!(yield c(e)))return;var a=!0;if(null!=r&&r.before&&(a=yield r.before(e)),!a)return;t=yield r.callback(e),null!=r&&r.after&&(t=yield r.after(e,t))}catch(s){var l;e.miolo.logger.error("[router] Unexpected error on Query ".concat(null===(l=r.callback)||void 0===l?void 0:l.name," at ").concat(i)),e.miolo.logger.error(s)}return t}));return function(r){return e.apply(this,arguments)}}(),s=r.method.toLowerCase();e[s](i,(e=>u(e,r)))}))}))}(o,i,t)}catch(c){t.error("[router] Error initing the router."),t.error("[router] routes:"),t.error(r),t.error(c)}e.use(o.routes())}var sr=o(import.meta.url),dr=t.dirname(sr),fr=a(t.resolve(dr,"fallback_index.html"),"utf8");function vr(e){return e?e/1e6:0}function pr(e){return e?e/1e6:0}function mr(){return{name:"SysCheck",cronTime:"0,15,30,45 * * * *",onTick:(e,r)=>{var t,o,n,i;t=e.logger,o=Math.round(vr(V.freemem()),2),n=Math.round(vr(V.totalmem()),2),(i=Math.round(100*o/n,2))>80?t.error("[cron][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")):t.info("[cron][".concat(d("SysCheck"),"] RAM ").concat(f(o)," MB used of ").concat(p(n)," MB (").concat(f(i)," %)")),Z.check("/",(function(e,r){var o=Math.round(pr(r.used),2),n=Math.round(pr(r.total),2),i=Math.round(pr(r.free),2);i<1?t.error("[cron][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)")):t.info("[cron][".concat(d("SysCheck"),"] DISK ").concat(f(o)," GB used of ").concat(p(n)," GB (").concat(f(i)," GB free)"))}))},start:!0}}function hr(e,r){var t=e.context.miolo,o=t.logger,n=[mr(),{name:"IPsum",cronTime:"0 0 * * *",onTick:(e,r)=>{Ce(e.config.http.ratelimit.ipsum_folder||ke,(r=>{e.logger.info("[cron][".concat(d("IPsum"),"] File downloaded. ").concat(p(r.length)," ips will be ").concat(f("blacklisted"),"!"))}),e.logger)},start:!0},...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 K((null==r?void 0:r.cronTime)||"*/5 * * * *",(t=>{try{o.silly("[cron][Custom Job ".concat(d(i),"] ").concat(g("ticks!"))),r.onTick(e,t)}catch(n){o.error("[cron][Custom Job ".concat(d(i),"] Error at onTick()")),o.error(n)}}),(()=>{if(o.silly("[cron][Custom Job ".concat(d(i),"] ").concat(g("completed!"))),null!=r&&r.onComplete)try{r.onComplete(e)}catch(t){o.error("[cron][Custom Job ".concat(d(i),"] Error at onComplete()")),o.error(t)}}),!1,(null==r?void 0:r.timezone)||"Europe/Madrid")}(t,e);i.push({name:r,job:o,running:!1})}));var a=e=>{var r;return(r="number"==typeof e?i[e]:i.filter((r=>r.name==e))[0])||o.error("[cron] Job ".concat(d(e)," Not Found")),r},l=e=>{try{return e.job.start(),e.running=!0,o.debug("[cron][Job ".concat(d(e.name),"] ").concat(g("started!"))),1}catch(r){return o.error("[cron][Job ".concat(d(e.name),"] Error starting it")),o.error(r),0}},c=e=>{try{return e.job.stop(),e.running=!1,o.debug("[cron][Job ".concat(d(e.name),"] ").concat(y("stopped!"))),1}catch(r){return o.error("[cron][Job ".concat(d(e.name),"] Error stopping it")),o.error(r),0}};return e.cron={jobs:i,start_one:e=>{var r=a(e);return r?[l(r),r.name]:[0,""]},start:()=>{try{var e=[],r=[];i.map((t=>{1==l(t)?e.push(t.name):r.push(t.name)})),e.length>0&&o.info("[cron] Started ".concat(e.length," jobs: ").concat(e)),r.length>0&&o.warn("[cron] Could not start ".concat(r.length," jobs: ").concat(r))}catch(t){o.error("[cron] start() error: ".concat(t))}},stop_one:e=>{var r=a(e);return r?[c(r),r.name]:[0,""]},stop:()=>{try{var e=[],r=[];i.map((t=>{1==c(t)?e.push(t.name):r.push(t.name)})),e.length>0&&o.info("[cron] Stopped ".concat(e.length," jobs: ").concat(e)),r.length>0&&o.warn("[cron] Could not stop ".concat(r.length," jobs: ").concat(r))}catch(t){o.error("[cron] stop() error: ".concat(t))}}},e}var gr=(e,r,t)=>new Promise(((o,n)=>{e.listen(r,t,(e=>{e?n(e):o()}))}));function yr(t,o){var n,i,a,l=new e,u=function(e){var t,o=r(ce,e);return o.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.credentials?"credentials":null!=e&&null!==(o=e.auth)&&void 0!==o&&o.custom?"custom":"guest"}(e),o.use_catcher=!(null==o||null===(t=o.http)||void 0===t||!t.catcher_url),o}(t);xe(l,u),$e(l,u.http),(e=>{e.use(P({filter:function(e){return"application/json"==e||"text/html"==e},gzip:{flush:R.Z_SYNC_FLUSH},deflate:{flush:R.Z_SYNC_FLUSH},br:!1})),e.use(C(q({formLimit:"100mb",jsonLimit:"100mb",bufferLimit:"100mb"})))})(l),function(e){var r=e.context.miolo.logger;function t(){return(t=oe((function*(e){if(e){var t=this.headers["x-real-ip"]||this.headers["x-orig-ip"]||this.ip||"127.0.0.1",o=e.status||400;if(this.accepts(["text","json","html"])?"number"!=typeof o&&(o=500):(o=406,e.message="Unsupported type"),Se.indexOf(o)>=0?r.warn("[".concat(t,"] ").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 t.apply(this,arguments)}}(l),function(e,r){var t=e.context.miolo,o=Pe(null==r?void 0:r.ipsum_folder,void 0,t.logger),n={driver:"memory",db:new Map,id:e=>e.request.ip,headers:{remaining:"Rate-Limit-Remaining",reset:"Rate-Limit-Reset",total:"Rate-Limit-Total"},disableHeader:!1,max:(null==r?void 0:r.max)||1e3,duration:(null==r?void 0:r.duration)||6e4,errorMessage:(null==r?void 0:r.errorMessage)||"Rate Limit reached",whitelist:(null==r?void 0:r.whitelist)||(e=>{var t=(null==r?void 0:r.whitelist_ips)||[];return!!t&&t.indexOf(e.request.ip)>=0}),blacklist:(null==r?void 0:r.blacklist)||(e=>{var t=e.request.ip,n=[...o,...Re,...(null==r?void 0:r.blacklist_ips)||[]].indexOf(t)>=0;return n&&e.miolo.logger.info("Rejecting ".concat(f("blacklisted")," ").concat(s(t))),n})};e.use(I(n))}(l,null===(n=u.http)||void 0===n?void 0:n.ratelimit),((e,r)=>{var{favicon:t,folders:o}=r,n=t||Me;for(var[i,a]of(e.context.miolo.logger.debug("[static] Serving favicon from ".concat(n.replace(Fe,""))),e.use(J(n)),Object.entries(o)))e.context.miolo.logger.debug("[static] Mounting static folder ".concat(i," => ").concat(a.replace(Fe,""))),e.use(M(i,F(a,{index:!1})))})(l,null===(i=u.http)||void 0===i?void 0:i.static),function(e,r){var t=function(){var e=oe((function*(e,r){return{}}));return function(r,t){return e.apply(this,arguments)}}(),o=function(){var e=oe((function*(e,r,t){}));return function(r,t,o){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)||t,onDone:(null==r?void 0:r.onDone)||o,geoip:(null==r?void 0:r.geoip)||{enabled:!1}};function i(){return(i=oe((function*(e,r){var t,o,i,a,l,u,v=e.miolo.logger,h=Ue(e),g=N.now();e.request.body=ee(ee({},e.request.fields),e.request.files),Ae.total+=1,Ae[h]=(Ae[h]||0)+1,e.requestId=Ae.total,e.request.ip=h;var y=!0===(null==n||null===(t=n.geoip)||void 0===t?void 0:t.enabled),b={};y&&(b=Te(h,n.geoip,v)),e.request.geoip=b;var _=e.request.url.indexOf("?")>=0?e.request.url.substr(0,e.request.url.indexOf("?")):e.request.url,w=y?!0===(null===(o=b)||void 0===o?void 0:o.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,")"):"":"",x="".concat(s(h)).concat(w," ").concat(d(e.request.method)," ").concat(d(_)," [").concat(m(Ae[h]),"/").concat(m(e.requestId),"]"),S=null!=e.request.body?JSON.stringify(e.request.body):"";v.info("".concat(x," - START")),v.debug("".concat(x," - Body: ").concat(S));var k=yield n.onStart(e,{started:g,description:"pending"});yield r();var O=null==e||null===(u=e.session)||void 0===u?void 0:u.user,E="";null!=O&&(null!=O&&O.id?E=" - uid ".concat(null==O?void 0:O.id):null!=O&&O.token&&(E=" - token ".concat(null==O?void 0:O.token)));var j,q=e.response.status,C=q;200==q?j=p:q>200&&q<=299?(j=f,e.response.redirected&&e.response.url&&(C+=" -> ".concat(e.response.url))):j=c;var P="[".concat(j(C),"]"),R=parseFloat((N.now()-g)/1e3).toFixed(2),I=R<n.lazy?p:R<n.slow?f:c,L=R<n.lazy?"Ok":R<n.slow?"lazy":"slow",M=null!=e.session?JSON.stringify(e.session):"";v.debug("".concat(x," - Session: ").concat(M));var F=null!=e.body?JSON.stringify(e.body):"";v.debug("".concat(x," - Response: ").concat(F)),yield n.onDone(e,k,{started:g,elapsed:R,description:L}),v.info("".concat(x," - DONE ").concat(P).concat(E," (").concat(I(L),": ").concat(I(R),")"))}))).apply(this,arguments)}e.use((function(e,r){return i.apply(this,arguments)}))}(l,null==u||null===(a=u.http)||void 0===a?void 0:a.request),function(e){function r(){return(r=oe((function*(e){e.body=Ge}))).apply(this,arguments)}var t=new A;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=oe((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(h(o),": ").concat(JSON.stringify(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(c("[JS Error]")," on ").concat(h(o),": ").concat(JSON.stringify(r.msg),"\n")+"".concat(c("[JS Error]")," File => ").concat(r.file,"\n")+"".concat(c("[JS Error]")," Line => ").concat(r.line,"\n")+"".concat(c("[JS Error]")," Col => ").concat(r.col,"\n")+"".concat(c("[JS Error]")," Error => ").concat(JSON.stringify(r.error),"\n")+"".concat(c("[JS Error]")," Agent => ").concat(n);i.error(l)}e.body={result:1}})),t.apply(this,arguments)}var o=new A;o.post(r,(function(e){return t.apply(this,arguments)})),e.use(o.routes())}(l,u.http.catcher_url),"guest"==u.auth_type&&We(l,u.auth.guest,null==u?void 0:u.session),"basic"==u.auth_type&&De(l,u.auth.basic),"credentials"==u.auth_type&&Qe(l,u.auth.credentials,null==u?void 0:u.session,null==u?void 0:u.cache),"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 A;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 v=null==u?void 0:u.middlewares;return v&&((e,r)=>{null!=r&&0!=r.length&&r.map((r=>{e.use(r)}))})(l,v),null!=u&&u.routes&&ur(l,u.routes),null!=(null==o?void 0:o.middleware)?l.use(o.middleware):function(e,r,t,o){var n=(null==r?void 0:r.html)||fr;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=oe((function*(e){var t={};try{var o;null!=r&&null!==(o=r.ssr)&&void 0!==o&&o.loader&&(t=yield r.ssr.loader(e))}catch(c){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!=c&&c.stack?"".concat(c.toString(),"\n").concat(c.stack):c.toString(),l="".concat("Error produced by loader in render.ssr middleware","\n").concat(i,"\n").concat(a);e.miolo.logger.error(l)}return t}));return function(r){return e.apply(this,arguments)}}(),a=(e,r,t)=>{var o,n,i=!0===(null==e||null===(o=e.session)||void 0===o?void 0:o.authenticated);return{config:r,user:null==e||null===(n=e.session)||void 0===n?void 0:n.user,authenticated:i,ssr_data:t,extra:null==e?void 0:e.extra}},l=(e,t)=>{var o="";try{var i;null!=r&&null!==(i=r.ssr)&&void 0!==i&&i.renderer?o=Y(r.ssr.renderer(e,t)):e.miolo.logger.warn("Missing renderer in render.ssr middleware")}catch(a){e.miolo.logger.error("Error in renderer (render.ssr middleware):\n".concat(a.toString())),o="\n <div>\n MIOLO: Error SSR renderer: ".concat(a.toString(),"\n </div> \n ")}return n.replace("{context}",JSON.stringify(t,null,2)).replace("{children}",o)};function c(){return(c=oe((function*(e){var r,n,c={hostname:null==t?void 0:t.hostname,port:null==t?void 0:t.port,catcher_url:null==t?void 0:t.catcher_url,login_url:null==o||null===(r=o.credentials)||void 0===r?void 0:r.url_login,logout_url:null==o||null===(n=o.credentials)||void 0===n?void 0:n.url_logout},u=yield i(e),s=a(e,c,u),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 c.apply(this,arguments)}))}(l,o,u.http,null==u?void 0:u.auth),hr(l,null==u?void 0:u.cron),function(e,r){var t,o=e.context.miolo.logger,n=function(){var t=oe((function*(){try{var t,n,i;if(null!=(null===(t=e.http)||void 0===t?void 0:t.server))return void o.warn("[http][start] Server already running on ".concat(null==e||null===(n=e.http)||void 0===n?void 0:n.hostname,":").concat(null==e||null===(i=e.http)||void 0===i?void 0:i.port));var a=Q.createServer(e.callback()),l=X({server:a}),c=function(){var t=oe((function*(){try{yield l.terminate(),delete e.http.server,o.info("[http][stop] miolo has been shutdowned from ".concat(r.hostname,":").concat(r.port))}catch(t){o.error("[http][stop] error: ".concat(t))}}));return function(){return t.apply(this,arguments)}}();e.http.server=a,e.http.stop=c,yield gr(a,r.port,r.hostname),o.info("[http][start] miolo is listening on ".concat(r.hostname,":").concat(r.port))}catch(u){o.error("[http][start] error: ".concat(u))}}));return function(){return t.apply(this,arguments)}}();e.http={server:void 0,start:n,stop:(t=oe((function*(){o.warn("[http] stop() stop() function still not attached. Is server running?")})),function(){return t.apply(this,arguments)}),hostname:r.hostname,port:r.port}}(l,null==u?void 0:u.http),l.start=oe((function*(){yield l.context.miolo.db.init_connection(),yield l.http.start(),l.cron.start()})),l.stop=oe((function*(){l.context.miolo.db.drop_connections(),yield l.http.stop(),l.cron.stop()})),l.restart=oe((function*(){yield l.stop(),yield l.start()})),l}export{yr as miolo,ue as miolo_emailer,me as miolo_logger,ge as miolo_parser};