From 9f0dddc5addbe907d51119f49e1a67f2d77199c8 Mon Sep 17 00:00:00 2001 From: Jonatan Nilsson Date: Tue, 8 Sep 2020 08:12:26 +0000 Subject: [PATCH] Big cleanup --- dev/api/core/coremonitor.mjs | 20 --- dev/api/core/ioroutes.mjs | 120 ---------------- dev/api/core/loghelper.mjs | 188 ------------------------ dev/api/routerio.mjs | 51 ------- dev/api/server.mjs | 82 ----------- dev/api/util.mjs | 16 --- dev/app/client.js | 8 -- dev/app/defaults.js | 34 ----- dev/app/header.js | 44 ------ dev/app/index.js | 31 ---- dev/app/log/log.js | 56 -------- dev/app/module.js | 38 ----- dev/app/socket.js | 4 - dev/app/status/status.js | 119 --------------- dev/app/updater/updater.js | 172 ---------------------- dev/index.mjs | 5 - dev/package.json | 20 --- dev/public/index.html | 14 -- dev/public/main.css | 270 ----------------------------------- 19 files changed, 1292 deletions(-) delete mode 100644 dev/api/core/coremonitor.mjs delete mode 100644 dev/api/core/ioroutes.mjs delete mode 100644 dev/api/core/loghelper.mjs delete mode 100644 dev/api/routerio.mjs delete mode 100644 dev/api/server.mjs delete mode 100644 dev/api/util.mjs delete mode 100644 dev/app/client.js delete mode 100644 dev/app/defaults.js delete mode 100644 dev/app/header.js delete mode 100644 dev/app/index.js delete mode 100644 dev/app/log/log.js delete mode 100644 dev/app/module.js delete mode 100644 dev/app/socket.js delete mode 100644 dev/app/status/status.js delete mode 100644 dev/app/updater/updater.js delete mode 100644 dev/index.mjs delete mode 100644 dev/package.json delete mode 100644 dev/public/index.html delete mode 100644 dev/public/main.css diff --git a/dev/api/core/coremonitor.mjs b/dev/api/core/coremonitor.mjs deleted file mode 100644 index 86f5c88..0000000 --- a/dev/api/core/coremonitor.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { formatLog } from './loghelper.mjs' -import { safeWrap } from '../util.mjs' - -export default function coremonitor(io, config, db, log, core) { - log.on('newlog', safeWrap(log, 'coremonitor.on.newlog', function(data) { - io.to('logger').emit('newlog', formatLog(data)) - })) - core.on('dbupdated', safeWrap(log, 'coremonitor.on.dbupdated', function() { - io.to('core').emit('core.db', db.get('core').value()) - })) - core.on('statusupdated', safeWrap(log, 'coremonitor.on.statusupdated', function() { - io.to('core').emit('core.status', core.status()) - })) - core.on('applog', safeWrap(log, 'coremonitor.on.applog', function(app) { - io.to('core.app').emit('core.program.log', { - name: 'app', - logs: app.logs, - }) - })) -} \ No newline at end of file diff --git a/dev/api/core/ioroutes.mjs b/dev/api/core/ioroutes.mjs deleted file mode 100644 index 339742d..0000000 --- a/dev/api/core/ioroutes.mjs +++ /dev/null @@ -1,120 +0,0 @@ -import { formatLog } from './loghelper.mjs' - -/* - * Event: 'core.config' - * - * Get config - */ -export async function config(ctx, data, cb) { - cb(ctx.config) -} - -/* - * Event: 'core.restart' - * - * Restart server - */ -export async function restart(ctx, data, cb) { - ctx.core.restart() -} - -/* - * Event: 'core.getlastlogs' - * - * Returns last few log messages from log - */ -export async function getlastlogs(ctx, data, cb) { - cb(ctx.logroot.ringbuffer.records.map(formatLog)) -} - -/* - * Event: 'core.listenlogs' - * - * Start listening to new log lines - */ -export async function listenlogs(ctx) { - ctx.socket.join('logger') -} - -/* - * Event: 'core.unlistenlogs' - * - * Stop listening to new log lines - */ -export async function unlistenlogs(ctx) { - ctx.socket.leave('logger') -} - -/* - * Event: 'core.update' - * - * Update specific software - */ -export async function update(ctx, data, cb) { - if (data.name === 'app') { - await ctx.core.updateProgram('app') - } else if (data.name === 'manage') { - await ctx.core.updateProgram('manage') - } else { - ctx.log.warn('Invalid update command for app ' + data.name) - ctx.log.event.warn('Invalid update command for app ' + data.name) - } -} - -/* - * Event: 'core.start' - * - * Start specific software - */ -export async function start(ctx, data, cb) { - if (data.name === 'app') { - await ctx.core.startProgram('app') - } else if (data.name === 'manage') { - await ctx.core.startProgram('manage') - } else { - ctx.log.warn('Invalid start command for app ' + data.name) - ctx.log.event.warn('Invalid start command for app ' + data.name) - } -} - -/* - * Event: 'core.listencore' - * - * Start listening to new log lines - */ -export async function listencore(ctx) { - ctx.socket.join('core') - ctx.socket.emit('core.db', ctx.db.get('core').value()) - ctx.socket.emit('core.status', ctx.core.status()) -} - -/* - * Event: 'core.unlistencore' - * - * Stop listening to new log lines - */ -export async function unlistencore(ctx) { - ctx.socket.leave('core') -} - -/* - * Event: 'core.listentoapp' - * - * Start listening to changes in core app - */ -export async function listentoapp(ctx) { - ctx.socket.join('core.app') - ctx.socket.emit('core.program.log', { - name: 'app', - logs: ctx.core.getProgramLogs('app') - }) -} - -/* - * Event: 'core.unlistentoapp' - * - * Stop listening to new log lines - */ -export async function unlistentoapp(ctx) { - ctx.socket.leave('core.app') -} diff --git a/dev/api/core/loghelper.mjs b/dev/api/core/loghelper.mjs deleted file mode 100644 index 59e878f..0000000 --- a/dev/api/core/loghelper.mjs +++ /dev/null @@ -1,188 +0,0 @@ -import _ from 'lodash' -import { format } from 'util' - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -// Suggested colors (some are unreadable in common cases): -// - Good: cyan, yellow (limited use), bold, green, magenta, red -// - Bad: blue (not visible on cmd.exe), grey (same color as background on -// Solarized Dark theme from , see -// issue #160) -var colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Levels -var TRACE = 10; -var DEBUG = 20; -var INFO = 30; -var WARN = 40; -var ERROR = 50; -var FATAL = 60; - -var levelFromName = { - 'trace': TRACE, - 'debug': DEBUG, - 'info': INFO, - 'warn': WARN, - 'error': ERROR, - 'fatal': FATAL -}; - -var upperPaddedNameFromLevel = {}; -Object.keys(levelFromName).forEach(function (name) { - var lvl = levelFromName[name]; - upperPaddedNameFromLevel[lvl] = ( - name.length === 4 ? ' ' : '') + name.toUpperCase(); -}); - -function stylize(str, color) { - if (!str) - return ''; - var codes = colors[color]; - if (codes) { - return '\\033[' + codes[0] + 'm' + str + - '\\033[' + codes[1] + 'm'; - } else { - return str; - } -} - -function indent(s) { - return ' ' + s.split(/\r?\n/).join('\n '); -} - -export function formatLog(data) { - let rec = _.cloneDeep(data) - - delete rec.v; - - // Time. - var time = '[' + rec.time.toISOString().replace('T', ' ').replace('Z', '') + ']' - time = stylize(time, 'none') - - delete rec.time; - - var nameStr = rec.name; - delete rec.name; - - if (rec.component) { - nameStr += '/' + rec.component; - } - delete rec.component; - - nameStr += '/' + rec.pid; - delete rec.pid; - - var level = (upperPaddedNameFromLevel[rec.level] || 'LVL' + rec.level); - var colorFromLevel = { - 10: 'white', // TRACE - 20: 'yellow', // DEBUG - 30: 'cyan', // INFO - 40: 'magenta', // WARN - 50: 'red', // ERROR - 60: 'inverse', // FATAL - }; - level = stylize(level, colorFromLevel[rec.level]); - delete rec.level; - - var src = ''; - if (rec.src && rec.src.file) { - var s = rec.src; - if (s.func) { - src = format(' (%s:%d in %s)', s.file, s.line, s.func); - } else { - src = format(' (%s:%d)', s.file, s.line); - } - src = stylize(src, 'green'); - } - delete rec.src; - - var hostname = rec.hostname; - delete rec.hostname; - - var extras = []; - var details = []; - - if (rec.req_id) { - extras.push('req_id=' + rec.req_id); - } - delete rec.req_id; - - var onelineMsg; - if (rec.msg.indexOf('\n') !== -1) { - onelineMsg = ''; - details.push(indent(stylize(rec.msg, 'cyan'))); - } else { - onelineMsg = ' ' + stylize(rec.msg, 'cyan'); - } - delete rec.msg; - - if (rec.err && rec.err.stack) { - var err = rec.err - if (typeof (err.stack) !== 'string') { - details.push(indent(err.stack.toString())); - } else { - details.push(indent(err.stack)); - } - delete err.message; - delete err.name; - delete err.stack; - // E.g. for extra 'foo' field on 'err', add 'err.foo' at - // top-level. This *does* have the potential to stomp on a - // literal 'err.foo' key. - Object.keys(err).forEach(function (k) { - rec['err.' + k] = err[k]; - }) - delete rec.err; - } - - var leftover = Object.keys(rec); - for (var i = 0; i < leftover.length; i++) { - var key = leftover[i]; - var value = rec[key]; - var stringified = false; - if (typeof (value) !== 'string') { - value = JSON.stringify(value, null, 2); - if (typeof (value) !== 'string') { - value = 'null' - } - stringified = true; - } - if (value.indexOf('\n') !== -1 || value.length > 50) { - details.push(indent(key + ': ' + value)); - } else if (!stringified && (value.indexOf(' ') != -1 || - value.length === 0)) - { - extras.push(key + '=' + JSON.stringify(value)); - } else { - extras.push(key + '=' + value); - } - } - - extras = stylize( - (extras.length ? ' (' + extras.join(', ') + ')' : ''), 'none'); - details = stylize( - (details.length ? details.join('\n --\n') + '\n' : ''), 'none'); - - return format('%s %s: %s on %s%s:%s%s\n%s', - time, - level, - nameStr, - hostname || '', - src, - onelineMsg, - extras, - details) -} \ No newline at end of file diff --git a/dev/api/routerio.mjs b/dev/api/routerio.mjs deleted file mode 100644 index 8a2c3cd..0000000 --- a/dev/api/routerio.mjs +++ /dev/null @@ -1,51 +0,0 @@ -import * as core from './core/ioroutes.mjs' - -function register(ctx, name, method) { - if (typeof(method) === 'object') { - Object.keys(method).forEach(key => { - register(ctx, [name, key].join('.'), method[key]) - }) - return - } - - ctx.socket.on(name, async function(data, cb) { - ctx.log.debug('SocketIO: ' + name) - - try { - await method(ctx, data, cb) - } - catch (error) { - ctx.log.error(error, `Error processing ${name}`) - } - }) -} - - -function onConnection(server, config, db, log, coreService, data) { - const io = server - const socket = data - - const child = log.child({ - id: socket.id, - }) - - child.info('Got new socket connection') - - let ctx = { - config, - io, - socket, - log: child, - db, - core: coreService, - logroot: log, - } - - ctx.socket.on('disconnect', function() { - child.info('Closed connection') - }) - - register(ctx, 'core', core) -} - -export default onConnection diff --git a/dev/api/server.mjs b/dev/api/server.mjs deleted file mode 100644 index adaa063..0000000 --- a/dev/api/server.mjs +++ /dev/null @@ -1,82 +0,0 @@ -import http from 'http' -import path from 'path' -import { fileURLToPath } from 'url' -import socket from 'socket.io-serveronly' -import nStatic from 'node-static' -import coremonitor from './core/coremonitor.mjs' - -import onConnection from './routerio.mjs' - -export function run(config, db, log, core) { - const __dirname = path.dirname(fileURLToPath(import.meta.url)) - const staticRoot = path.join(__dirname,'../public') - - const fileServer = new nStatic.Server(staticRoot) - const server = http.createServer(function (req, res) { - const child = log.child({}) - - const d1 = new Date().getTime() - - let finishedRequest = false - var done = function () { - if (finishedRequest) return - finishedRequest = true - if (req.url === '/main.css.map') return - var requestTime = new Date().getTime() - d1 - - let level = 'debug' - if (res.statusCode >= 400) { - level = 'warn' - } - if (res.statusCode >= 500) { - level = 'error' - } - - let status = '' - if (res.statusCode >= 400) { - status = res.statusCode + ' ' - } - - child[level]({ - duration: requestTime, - status: res.statusCode, - }, `<-- ${status}${req.method} ${req.url}`) - } - - res.addListener('finish', done); - res.addListener('close', done); - - req.addListener('end', function () { - if (req.url === '/') { - res.writeHead(302, { Location: '/index.html' }) - return res.end() - } - - fileServer.serve(req, res, function (err) { - if (err) { - if (err.status !== 404) { - log.error(err, req.url); - } - - res.writeHead(err.status, err.headers); - res.end(err.message); - } - }); - }).resume() - }) - - const io = new socket(server) - io.on('connection', onConnection.bind(this, io, config, db, log, core)) - - coremonitor(io, config, db, log, core) - - server.listen(config.managePort, '0.0.0.0', function(err) { - if (err) { - log.fatal(err) - log.event.error('Error starting server: ' + err.message) - return process.exit(2) - } - log.event.info(`Server is listening on ${config.managePort} serving files on ${staticRoot}`) - log.info(`Server is listening on ${config.managePort} serving files on ${staticRoot}`) - }) -} \ No newline at end of file diff --git a/dev/api/util.mjs b/dev/api/util.mjs deleted file mode 100644 index aff5296..0000000 --- a/dev/api/util.mjs +++ /dev/null @@ -1,16 +0,0 @@ -export function safeWrap(log, name, fn) { - return function(data, cb) { - try { - let out = fn(data, cb) - if (out && out.then) { - out.then(function() {}, function(err) { - log.error(err, 'Unknown error in ' + name) - log.event.error('Unknown error occured in ' + name + ': ' + err.message) - }) - } - } catch (err) { - log.error(err, 'Unknown error in ' + name) - log.event.error('Unknown error occured in ' + name + ': ' + err.message) - } - } -} \ No newline at end of file diff --git a/dev/app/client.js b/dev/app/client.js deleted file mode 100644 index 29b6a1f..0000000 --- a/dev/app/client.js +++ /dev/null @@ -1,8 +0,0 @@ -/*! - * Socket.IO v2.3.0 - * (c) 2014-2019 Guillermo Rauch - * Released under the MIT License. - */ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){function r(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var n,r=o(t),i=r.source,u=r.id,p=r.path,h=c[u]&&p in c[u].nsps,f=e.forceNew||e["force new connection"]||!1===e.multiplex||h;return f?(a("ignoring socket cache for %s",i),n=s(i,e)):(c[u]||(a("new io instance for %s",i),c[u]=s(i,e)),n=c[u]),r.query&&!e.query&&(e.query=r.query),n.socket(r.path,e)}var o=n(1),i=n(7),s=n(15),a=n(3)("socket.io-client");t.exports=e=r;var c=e.managers={};e.protocol=i.protocol,e.connect=r,e.Manager=n(15),e.Socket=n(39)},function(t,e,n){function r(t,e){var n=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(i("protocol-less url %s",t),t="undefined"!=typeof e?e.protocol+"//"+t:"https://"+t),i("parse %s",t),n=o(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";var r=n.host.indexOf(":")!==-1,s=r?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port,n.href=n.protocol+"://"+s+(e&&e.port===n.port?"":":"+n.port),n}var o=n(2),i=n(3)("socket.io-client:url");t.exports=r},function(t,e){var n=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");o!=-1&&i!=-1&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s=n.exec(t||""),a={},c=14;c--;)a[r[c]]=s[c]||"";return o!=-1&&i!=-1&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a}},function(t,e,n){(function(r){"use strict";function o(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+t.exports.humanize(this.diff),this.useColors){var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var r=0,o=0;e[0].replace(/%[a-zA-Z%]/g,function(t){"%%"!==t&&(r++,"%c"===t&&(o=r))}),e.splice(o,0,n)}}function s(){var t;return"object"===("undefined"==typeof console?"undefined":p(console))&&console.log&&(t=console).log.apply(t,arguments)}function a(t){try{t?e.storage.setItem("debug",t):e.storage.removeItem("debug")}catch(n){}}function c(){var t=void 0;try{t=e.storage.getItem("debug")}catch(n){}return!t&&"undefined"!=typeof r&&"env"in r&&(t=r.env.DEBUG),t}function u(){try{return localStorage}catch(t){}}var p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.log=s,e.formatArgs=i,e.save=a,e.load=c,e.useColors=o,e.storage=u(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.exports=n(5)(e);var h=t.exports.formatters;h.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}).call(e,n(4))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(t){if(p===setTimeout)return setTimeout(t,0);if((p===n||!p)&&setTimeout)return p=setTimeout,setTimeout(t,0);try{return p(t,0)}catch(e){try{return p.call(null,t,0)}catch(e){return p.call(this,t,0)}}}function i(t){if(h===clearTimeout)return clearTimeout(t);if((h===r||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(t);try{return h(t)}catch(e){try{return h.call(null,t)}catch(e){return h.call(this,t)}}}function s(){y&&l&&(y=!1,l.length?d=l.concat(d):m=-1,d.length&&a())}function a(){if(!y){var t=o(s);y=!0;for(var e=d.length;e;){for(l=d,d=[];++m1)for(var n=1;n100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*h;case"weeks":case"week":case"w":return n*p;case"days":case"day":case"d":return n*u;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function r(t){var e=Math.abs(t);return e>=u?Math.round(t/u)+"d":e>=c?Math.round(t/c)+"h":e>=a?Math.round(t/a)+"m":e>=s?Math.round(t/s)+"s":t+"ms"}function o(t){var e=Math.abs(t);return e>=u?i(t,e,u,"day"):e>=c?i(t,e,c,"hour"):e>=a?i(t,e,a,"minute"):e>=s?i(t,e,s,"second"):t+" ms"}function i(t,e,n,r){var o=e>=1.5*n;return Math.round(t/n)+" "+r+(o?"s":"")}var s=1e3,a=60*s,c=60*a,u=24*c,p=7*u,h=365.25*u;t.exports=function(t,e){e=e||{};var i=typeof t;if("string"===i&&t.length>0)return n(t);if("number"===i&&isFinite(t))return e["long"]?o(t):r(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,n){function r(){}function o(t){var n=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(n+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(n+=t.nsp+","),null!=t.id&&(n+=t.id),null!=t.data){var r=i(t.data);if(r===!1)return g;n+=r}return f("encoded %j as %s",t,n),n}function i(t){try{return JSON.stringify(t)}catch(e){return!1}}function s(t,e){function n(t){var n=d.deconstructPacket(t),r=o(n.packet),i=n.buffers;i.unshift(r),e(i)}d.removeBlobs(t,n)}function a(){this.reconstructor=null}function c(t){var n=0,r={type:Number(t.charAt(0))};if(null==e.types[r.type])return h("unknown packet type "+r.type);if(e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type){for(var o="";"-"!==t.charAt(++n)&&(o+=t.charAt(n),n!=t.length););if(o!=Number(o)||"-"!==t.charAt(n))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(n+1))for(r.nsp="";++n;){var i=t.charAt(n);if(","===i)break;if(r.nsp+=i,n===t.length)break}else r.nsp="/";var s=t.charAt(n+1);if(""!==s&&Number(s)==s){for(r.id="";++n;){var i=t.charAt(n);if(null==i||Number(i)!=i){--n;break}if(r.id+=t.charAt(n),n===t.length)break}r.id=Number(r.id)}if(t.charAt(++n)){var a=u(t.substr(n)),c=a!==!1&&(r.type===e.ERROR||y(a));if(!c)return h("invalid payload");r.data=a}return f("decoded %s as %j",t,r),r}function u(t){try{return JSON.parse(t)}catch(e){return!1}}function p(t){this.reconPack=t,this.buffers=[]}function h(t){return{type:e.ERROR,data:"parser error: "+t}}var f=n(8)("socket.io-parser"),l=n(11),d=n(12),y=n(13),m=n(14);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=r,e.Decoder=a;var g=e.ERROR+'"encode error"';r.prototype.encode=function(t,n){if(f("encoding packet %j",t),e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)s(t,n);else{var r=o(t);n([r])}},l(a.prototype),a.prototype.add=function(t){var n;if("string"==typeof t)n=c(t),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new p(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!m(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,this.emit("decoded",n))}},a.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},p.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=d.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},p.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,n){(function(r){"use strict";function o(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(t){var n=this.useColors;if(t[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+t[0]+(n?"%c ":" ")+"+"+e.humanize(this.diff),n){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))}),t.splice(i,0,r)}}function s(){return"object"===("undefined"==typeof console?"undefined":p(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(n){}}function c(){var t;try{t=e.storage.debug}catch(n){}return!t&&"undefined"!=typeof r&&"env"in r&&(t=r.env.DEBUG),t}function u(){try{return window.localStorage}catch(t){}}var p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e=t.exports=n(9),e.log=s,e.formatArgs=i,e.save=a,e.load=c,e.useColors=o,e.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},e.enable(c())}).call(e,n(4))},function(t,e,n){"use strict";function r(t){var n,r=0;for(n in t)r=(r<<5)-r+t.charCodeAt(n),r|=0;return e.colors[Math.abs(r)%e.colors.length]}function o(t){function n(){if(n.enabled){var t=n,r=+new Date,i=r-(o||r);t.diff=i,t.prev=o,t.curr=r,o=r;for(var s=new Array(arguments.length),a=0;a100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*p;case"days":case"day":case"d":return n*u;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function r(t){return t>=u?Math.round(t/u)+"d":t>=c?Math.round(t/c)+"h":t>=a?Math.round(t/a)+"m":t>=s?Math.round(t/s)+"s":t+"ms"}function o(t){return i(t,u,"day")||i(t,c,"hour")||i(t,a,"minute")||i(t,s,"second")||t+" ms"}function i(t,e,n){if(!(t0)return n(t);if("number"===i&&isNaN(t)===!1)return e["long"]?o(t):r(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,n){function r(t){if(t)return o(t)}function o(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r,o=0;o0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},r.prototype.cleanup=function(){p("cleanup");for(var t=this.subs.length,e=0;e=this._reconnectionAttempts)p("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();p("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var n=setTimeout(function(){t.skipReconnect||(p("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open(function(e){e?(p("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(p("reconnect success"),t.onreconnect())}))},e);this.subs.push({destroy:function(){clearTimeout(n)}})}},r.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,n){t.exports=n(17),t.exports.parser=n(24)},function(t,e,n){function r(t,e){return this instanceof r?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=p(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=p(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=h.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new r(t,e)}function o(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}var i=n(18),s=n(11),a=n(3)("engine.io-client:socket"),c=n(38),u=n(24),p=n(2),h=n(32);t.exports=r,r.priorWebsocketSuccess=!1,s(r.prototype),r.protocol=u.protocol,r.Socket=r,r.Transport=n(23),r.transports=n(18),r.parser=n(24),r.prototype.createTransport=function(t){a('creating transport "%s"',t);var e=o(this.query);e.EIO=u.protocol,e.transport=t;var n=this.transportOptions[t]||{};this.id&&(e.sid=this.id);var r=new i[t]({query:e,socket:this,agent:n.agent||this.agent,hostname:n.hostname||this.hostname,port:n.port||this.port,secure:n.secure||this.secure,path:n.path||this.path,forceJSONP:n.forceJSONP||this.forceJSONP,jsonp:n.jsonp||this.jsonp,forceBase64:n.forceBase64||this.forceBase64,enablesXDR:n.enablesXDR||this.enablesXDR,withCredentials:n.withCredentials||this.withCredentials,timestampRequests:n.timestampRequests||this.timestampRequests,timestampParam:n.timestampParam||this.timestampParam,policyPort:n.policyPort||this.policyPort,pfx:n.pfx||this.pfx,key:n.key||this.key,passphrase:n.passphrase||this.passphrase,cert:n.cert||this.cert,ca:n.ca||this.ca,ciphers:n.ciphers||this.ciphers,rejectUnauthorized:n.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:n.perMessageDeflate||this.perMessageDeflate,extraHeaders:n.extraHeaders||this.extraHeaders,forceNode:n.forceNode||this.forceNode,localAddress:n.localAddress||this.localAddress,requestTimeout:n.requestTimeout||this.requestTimeout,protocols:n.protocols||void 0,isReactNative:this.isReactNative});return r},r.prototype.open=function(){var t;if(this.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else{ -if(0===this.transports.length){var e=this;return void setTimeout(function(){e.emit("error","No transports available")},0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(n){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},r.prototype.setTransport=function(t){a("setting transport %s",t.name);var e=this;this.transport&&(a("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",function(){e.onDrain()}).on("packet",function(t){e.onPacket(t)}).on("error",function(t){e.onError(t)}).on("close",function(){e.onClose("transport close")})},r.prototype.probe=function(t){function e(){if(f.onlyBinaryUpgrades){var e=!this.supportsBinary&&f.transport.supportsBinary;h=h||e}h||(a('probe transport "%s" opened',t),p.send([{type:"ping",data:"probe"}]),p.once("packet",function(e){if(!h)if("pong"===e.type&&"probe"===e.data){if(a('probe transport "%s" pong',t),f.upgrading=!0,f.emit("upgrading",p),!p)return;r.priorWebsocketSuccess="websocket"===p.name,a('pausing current transport "%s"',f.transport.name),f.transport.pause(function(){h||"closed"!==f.readyState&&(a("changing transport and sending upgrade packet"),u(),f.setTransport(p),p.send([{type:"upgrade"}]),f.emit("upgrade",p),p=null,f.upgrading=!1,f.flush())})}else{a('probe transport "%s" failed',t);var n=new Error("probe error");n.transport=p.name,f.emit("upgradeError",n)}}))}function n(){h||(h=!0,u(),p.close(),p=null)}function o(e){var r=new Error("probe error: "+e);r.transport=p.name,n(),a('probe transport "%s" failed because of error: %s',t,e),f.emit("upgradeError",r)}function i(){o("transport closed")}function s(){o("socket closed")}function c(t){p&&t.name!==p.name&&(a('"%s" works - aborting "%s"',t.name,p.name),n())}function u(){p.removeListener("open",e),p.removeListener("error",o),p.removeListener("close",i),f.removeListener("close",s),f.removeListener("upgrading",c)}a('probing transport "%s"',t);var p=this.createTransport(t,{probe:1}),h=!1,f=this;r.priorWebsocketSuccess=!1,p.once("open",e),p.once("error",o),p.once("close",i),this.once("close",s),this.once("upgrading",c),p.open()},r.prototype.onOpen=function(){if(a("socket open"),this.readyState="open",r.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){a("starting upgrade probes");for(var t=0,e=this.upgrades.length;t1?{type:b[o],data:t.substring(1)}:{type:b[o]}:C}var i=new Uint8Array(t),o=i[0],s=f(t,1);return w&&"blob"===n&&(s=new w([s])),{type:b[o],data:s}},e.decodeBase64Packet=function(t,e){var n=b[t.charAt(0)];if(!u)return{type:n,data:{base64:!0,data:t.substr(1)}};var r=u.decode(t.substr(1));return"blob"===e&&w&&(r=new w([r])),{type:n,data:r}},e.encodePayload=function(t,n,r){function o(t){return t.length+":"+t}function i(t,r){e.encodePacket(t,!!s&&n,!1,function(t){r(null,o(t))})}"function"==typeof n&&(r=n,n=null);var s=h(t);return n&&s?w&&!g?e.encodePayloadAsBlob(t,r):e.encodePayloadAsArrayBuffer(t,r):t.length?void c(t,i,function(t,e){return r(e.join(""))}):r("0:")},e.decodePayload=function(t,n,r){if("string"!=typeof t)return e.decodePayloadAsBinary(t,n,r);"function"==typeof n&&(r=n,n=null);var o;if(""===t)return r(C,0,1);for(var i,s,a="",c=0,u=t.length;c0;){for(var s=new Uint8Array(o),a=0===s[0],c="",u=1;255!==s[u];u++){if(c.length>310)return r(C,0,1);c+=s[u]}o=f(o,2+c.length),c=parseInt(c);var p=f(o,0,c);if(a)try{p=String.fromCharCode.apply(null,new Uint8Array(p))}catch(h){var l=new Uint8Array(p);p="";for(var u=0;ur&&(n=r),e>=r||e>=n||0===r)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(n-e),s=e,a=0;s=55296&&e<=56319&&o65535&&(e-=65536,o+=d(e>>>10&1023|55296),e=56320|1023&e),o+=d(e);return o}function o(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function i(t,e){return d(t>>e&63|128)}function s(t,e){if(0==(4294967168&t))return d(t);var n="";return 0==(4294965248&t)?n=d(t>>6&31|192):0==(4294901760&t)?(o(t,e)||(t=65533),n=d(t>>12&15|224),n+=i(t,6)):0==(4292870144&t)&&(n=d(t>>18&7|240),n+=i(t,12),n+=i(t,6)),n+=d(63&t|128)}function a(t,e){e=e||{};for(var r,o=!1!==e.strict,i=n(t),a=i.length,c=-1,u="";++c=f)throw Error("Invalid byte index");var t=255&h[l];if(l++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function u(t){var e,n,r,i,s;if(l>f)throw Error("Invalid byte index");if(l==f)return!1;if(e=255&h[l],l++,0==(128&e))return e;if(192==(224&e)){if(n=c(),s=(31&e)<<6|n,s>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&e)){if(n=c(),r=c(),s=(15&e)<<12|n<<6|r,s>=2048)return o(s,t)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(n=c(),r=c(),i=c(),s=(7&e)<<18|n<<12|r<<6|i,s>=65536&&s<=1114111))return s;throw Error("Invalid UTF-8 detected")}function p(t,e){e=e||{};var o=!1!==e.strict;h=n(t),f=h.length,l=0;for(var i,s=[];(i=u(o))!==!1;)s.push(i);return r(s)}/*! https://mths.be/utf8js v2.1.2 by @mathias */ -var h,f,l,d=String.fromCharCode;t.exports={version:"2.1.2",encode:a,decode:p}},function(t,e){!function(){"use strict";for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(256),r=0;r>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3===2?i=i.substring(0,i.length-1)+"=":o%3===1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(t){var e,r,o,i,s,a=.75*t.length,c=t.length,u=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);var p=new ArrayBuffer(a),h=new Uint8Array(p);for(e=0;e>4,h[u++]=(15&o)<<4|i>>2,h[u++]=(3&i)<<6|63&s;return p}}()},function(t,e){function n(t){return t.map(function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var n=new Uint8Array(t.byteLength);n.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=n.buffer}return e}return t})}function r(t,e){e=e||{};var r=new i;return n(t).forEach(function(t){r.append(t)}),e.type?r.getBlob(e.type):r.getBlob()}function o(t,e){return new Blob(n(t),e||{})}var i="undefined"!=typeof i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{var t=new Blob(["hi"]);return 2===t.size}catch(e){return!1}}(),a=s&&function(){try{var t=new Blob([new Uint8Array([1,2])]);return 2===t.size}catch(e){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(r.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=function(){return s?a?Blob:o:c?r:void 0}()},function(t,e){e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),r=0,o=n.length;r0);return e}function r(t){var e=0;for(p=0;p';i=document.createElement(e)}catch(t){i=document.createElement("iframe"),i.name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),r(),t=t.replace(p,"\\\n"),this.area.value=t.replace(u,"\\n");try{this.form.submit()}catch(h){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&n()}:this.iframe.onload=n}}).call(e,function(){return this}())},function(t,e,n){function r(t){var e=t&&t.forceBase64;e&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(l=i),s.call(this,t)}var o,i,s=n(23),a=n(24),c=n(32),u=n(33),p=n(34),h=n(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=n(37)}catch(f){}var l=o||i;t.exports=r,u(r,s),r.prototype.name="websocket",r.prototype.supportsBinary=!0,r.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,n={agent:this.agent,perMessageDeflate:this.perMessageDeflate};n.pfx=this.pfx,n.key=this.key,n.passphrase=this.passphrase,n.cert=this.cert,n.ca=this.ca,n.ciphers=this.ciphers,n.rejectUnauthorized=this.rejectUnauthorized,this.extraHeaders&&(n.headers=this.extraHeaders),this.localAddress&&(n.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new l(t,e):new l(t):new l(t,e,n)}catch(r){return this.emit("error",r)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},r.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},r.prototype.write=function(t){function e(){n.emit("flush"),setTimeout(function(){n.writable=!0,n.emit("drain")},0)}var n=this;this.writable=!1;for(var r=t.length,o=0,i=r;o0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(t){this.ms=t},n.prototype.setMax=function(t){this.max=t},n.prototype.setJitter=function(t){this.jitter=t}}])}); diff --git a/dev/app/defaults.js b/dev/app/defaults.js deleted file mode 100644 index 01f6560..0000000 --- a/dev/app/defaults.js +++ /dev/null @@ -1,34 +0,0 @@ - -// taken from isobject npm library -function isObject(val) { - return val != null && typeof val === 'object' && Array.isArray(val) === false -} - -module.exports = function defaults(options, def) { - let out = { } - - if (options) { - Object.keys(options || {}).forEach(key => { - out[key] = options[key] - - if (Array.isArray(out[key])) { - out[key] = out[key].map(item => { - if (isObject(item)) return defaults(item) - return item - }) - } else if (out[key] && typeof out[key] === 'object') { - out[key] = defaults(options[key], def && def[key]) - } - }) - } - - if (def) { - Object.keys(def).forEach(function(key) { - if (typeof out[key] === 'undefined') { - out[key] = def[key] - } - }) - } - - return out -} diff --git a/dev/app/header.js b/dev/app/header.js deleted file mode 100644 index a5001b2..0000000 --- a/dev/app/header.js +++ /dev/null @@ -1,44 +0,0 @@ -const m = require('mithril') -const socket = require('./socket') - -const Header = { - oninit: function() { - this.connected = socket.connected - - socket.on('connect', () => { - this.connected = true - m.redraw() - }) - socket.on('disconnect', () => { - this.connected = false - m.redraw() - }) - }, - view: function() { - let path = m.route.get() || '' - - return [ - m('div.seperator'), - m(m.route.Link, { - href: '/', - class: path === '/' || path === '' ? 'active' : '', - }, 'Status'), - m('div.seperator'), - m(m.route.Link, { - href: '/log', - class: path === '/log' ? 'active' : '', - }, 'Log'), - m('div.seperator'), - m(m.route.Link, { - href: '/updater', - class: path.startsWith('/updater') ? 'active' : '', - }, 'Updater'), - m('div.seperator'), - !this.connected && m('div.disconnected', ` - Lost connection with server, Attempting to reconnect - `) || null, - ] - } -} - -module.exports = Header diff --git a/dev/app/index.js b/dev/app/index.js deleted file mode 100644 index f63e6c5..0000000 --- a/dev/app/index.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * @license - * stream-manager - * Copyright 2015 Jonatan Nilsson - * - * Available under WTFPL License (http://www.wtfpl.net/txt/copying/) -*/ - -'use strict' - -//Add debug components to window. Allows us to play with controls -//in the console. -window.components = {} - -require('./socket') - -const m = require('mithril') -const Header = require('./header') - -const Status = require('./status/status') -const Log = require('./log/log') -const Updater = require('./updater/updater') - -m.mount(document.getElementById('header'), Header) - -m.route(document.getElementById('content'), '/', { - '/': Status, - '/log': Log, - '/updater': Updater, - '/updater/:id': Updater, -}) diff --git a/dev/app/log/log.js b/dev/app/log/log.js deleted file mode 100644 index bf9c903..0000000 --- a/dev/app/log/log.js +++ /dev/null @@ -1,56 +0,0 @@ -const m = require('mithril') -const socket = require('../socket') -const Module = require('../module') - -const Log = Module({ - init: function() { - this.connected = socket.connected - this.loglines = [] - - this.on('newlog', data => { - this.loglines.push(this.formatLine(data)) - m.redraw() - }) - - this._socketOn(() => this.loadData()) - }, - - remove: function() { - socket.emit('core.unlistenlogs', {}) - }, - - loadData: function() { - this.loglines = [] - socket.emit('core.listenlogs', {}) - socket.emit('core.getlastlogs', {}, (res) => { - this.loglines = res.map(this.formatLine) - m.redraw() - }) - }, - - formatLine: function(line) { - return m.trust(line.replace(/\\033\[37m/g, '') - .replace(/\\033\[33m/g, '') - .replace(/\\033\[36m/g, '') - .replace(/\\033\[35m/g, '') - .replace(/\\033\[31m/g, '') - .replace(/\\033\[7m/g, '') - .replace(/\\033\[32m/g, '') - .replace(/\\033\[27m/g, '') - .replace(/\\033\[39m/g, '')) - }, - - view: function() { - return [ - m('h1.header', 'Log'), - m('div#logger', [ - this.loglines.map((line, i) => { - return m('div', { key: i }, line) - }), - m('div.padder'), - ]), - ] - } -}) - -module.exports = Log diff --git a/dev/app/module.js b/dev/app/module.js deleted file mode 100644 index 5f4b6f9..0000000 --- a/dev/app/module.js +++ /dev/null @@ -1,38 +0,0 @@ -const defaults = require('./defaults') -const socket = require('./socket') - -module.exports = function Module(module) { - return defaults(module, { - init: function() {}, - - oninit: function(vnode) { - this._listeners = [] - this.init(vnode) - }, - - _listeners: null, - - _socketOn: function(cb) { - socket.on('connect', () => cb()) - - if (socket.connected) { - cb() - } - }, - - on: function(name, cb) { - this._listeners.push([name, cb]) - socket.on(name, cb) - }, - - remove: function() {}, - - onremove: function() { - this.remove() - if (!this._listeners) return - for (let i = 0; i < this._listeners.length; i++) { - socket.removeListener(this._listeners[0], this._listeners[1]) - } - }, - }) -} diff --git a/dev/app/socket.js b/dev/app/socket.js deleted file mode 100644 index 93a376b..0000000 --- a/dev/app/socket.js +++ /dev/null @@ -1,4 +0,0 @@ -var io = require('./client') -var socket = io() - -module.exports = socket diff --git a/dev/app/status/status.js b/dev/app/status/status.js deleted file mode 100644 index 8278bdd..0000000 --- a/dev/app/status/status.js +++ /dev/null @@ -1,119 +0,0 @@ -const m = require('mithril') -const socket = require('../socket') -const Module = require('../module') - -const Status = Module({ - init: function() { - this._name = '...loading...' - this._management = { - port: null, - repository: null, - active: null, - latestInstalled: null, - lastActive: null, - latestVersion: null, - running: null, - } - this._app = { - port: null, - repository: null, - active: null, - latestInstalled: null, - lastActive: null, - latestVersion: null, - running: null, - } - - this._socketOn(() => this.loadData()) - }, - - loadData: function() { - socket.emit('core.config', {}, (res) => { - this._name = res.name + ' - ' + res.serviceName - this._app.port = res.port - this._app.repository = res.appRepository - this._management.port = res.managePort - this._management.repository = res.manageRepository - m.redraw() - }) - - this.on('core.db', (res) => { - this._management.active = res.manageActive - this._management.latestInstalled = res.manageLatestInstalled - this._management.lastActive = res.manageLastActive - this._management.latestVersion = res.manageLatestVersion - this._app.active = res.appActive - this._app.latestInstalled = res.appLatestInstalled - this._app.lastActive = res.appLastActive - this._app.latestVersion = res.appLatestVersion - - m.redraw() - }) - - this.on('core.status', (res) => { - this._management.running = res.manage - this._app.running = res.app - - m.redraw() - }) - - socket.emit('core.listencore', {}) - }, - - remove: function() { - socket.emit('core.unlistencore', {}) - }, - - restartClicked: function() { - socket.emit('core.restart', {}) - }, - - view: function() { - let loopOver = [ - ['Management service', '_management'], - ['Application service', '_app'], - ] - return m('div#status', [ - m('h1.header', this._name), - m('div.split', [ - loopOver.map((group) => { - return m('div.item', [ - m('h4', group[0]), - m('p', this[group[1]].port - ? `Port: ${this[group[1]].port}` - : ''), - m('p', this[group[1]].repository - ? `${this[group[1]].repository}` - : '< no repository >'), - m('p', this[group[1]].active - ? `Running version: ${this[group[1]].active}` - : '< no running version >'), - m('p', this[group[1]].latestInstalled - ? `Latest installed: ${this[group[1]].latestInstalled}` - : '< no version installed >'), - m('p', this[group[1]].lastActive - ? `Last stable version: ${this[group[1]].lastActive}` - : '< no last stable version >'), - m('p', this[group[1]].latestVersion - ? `Latest version: ${this[group[1]].latestVersion}` - : '< no version found >'), - this[group[1]].running !== null - ? m('p', - { class: group[1].running ? 'running' : 'notrunning' }, - group[1].running ? 'Running' : 'Not Running' - ) - : null, - m('button', { - - }, 'Update/Start') - ]) - }), - ]), - m('button', { - onclick: () => this.restartClicked(), - }, 'Restart service') - ]) - } -}) - -module.exports = Status diff --git a/dev/app/updater/updater.js b/dev/app/updater/updater.js deleted file mode 100644 index accb804..0000000 --- a/dev/app/updater/updater.js +++ /dev/null @@ -1,172 +0,0 @@ -const m = require('mithril') -const socket = require('../socket') -const Module = require('../module') - -const Updater = Module({ - init: function(vnode) { - this.activeApp = vnode.attrs.id || null - this.appRepository = null - this.manageRepository = null - this.db = null - this.app = {} - this.status = {} - this.logUpdated = false - this._socketOn(() => this.socketOpen()) - this._active = null - - if (this.activeApp && this.activeApp !== 'app'&& this.activeApp !== 'manage') { - return m.route('/updater') - } - }, - - onupdate: function(vnode) { - if (this.activeApp === vnode.attrs.id) return - - this.activeApp = vnode.attrs.id || null - if (this.activeApp && this.activeApp !== 'app'&& this.activeApp !== 'manage') { - return m.route.set('/updater') - } - if (this.activeApp && (this.appRepository || this.manageRepository)) { - this.loadAppData() - } - m.redraw() - }, - - socketOpen: function() { - socket.emit('core.config', {}, (res) => { - this.appRepository = res.appRepository - this.manageRepository = res.manageRepository - if (this.activeApp) { - this.loadAppData() - } - m.redraw() - }) - - socket.on('core.status', (res) => { - this.status = res - m.redraw() - }) - - this.on('core.db', (res) => { - this.db = res - this.updateActiveDb() - m.redraw() - }) - - this.on('core.program.log', (res) => { - this.app.logs = res.logs - this.logUpdated = true - m.redraw() - }) - - - socket.emit('core.listencore', {}) - }, - - updateActiveDb() { - if (this.db && this.activeApp) { - this.app = { - repository: this[this.activeApp + 'Repository'], - active: this.db[this.activeApp + 'Active'], - lastActive: this.db[this.activeApp + 'LastActive'], - latestInstalled: this.db[this.activeApp + 'LatestInstalled'], - latestVersion: this.db[this.activeApp + 'LatestVersion'], - logs: '', - } - } else { - this.app = {} - } - }, - - loadAppData() { - this.updateActiveDb() - if (this.activeApp === 'app') { - socket.emit('core.listentoapp', {}) - } - /* request to listen to app updates */ - }, - - remove: function() { - socket.emit('core.unlistencore', {}) - socket.emit('core.unlistentoapp', {}) - }, - - startUpdate: function() { - socket.emit('core.update', { - name: this.activeApp, - }) - }, - - startSoftware: function() { - socket.emit('core.start', { - name: this.activeApp, - }) - }, - - view: function() { - return m('div#update', [ - m('div.actions', [ - m('h1.header', 'Updater'), - m('div.filler'), - m(m.route.Link, { - hidden: !this.appRepository, - class: 'button' + (this.activeApp === 'app' ? ' active' : ''), - href: '/updater/app', - }, 'Update App'), - m(m.route.Link, { - hidden: this.manageRepository, - class: 'button' + (this.activeApp === 'manage' ? ' active' : ''), - href: '/updater/manage', - }, 'Update Manager'), - ]), - this.activeApp && this.app ? [ - m('h4', this.app.repository - ? `${this.app.repository}` - : '< no repository >'), - m('div.info', [ - m('p', this.app.active - ? `Running version: ${this.app.active}` - : '< no running version >'), - m('p', this.app.latestInstalled - ? `Latest installed: ${this.app.latestInstalled}` - : '< no version installed >'), - m('p', this.app.lastActive - ? `Last stable version: ${this.app.lastActive}` - : '< no last stable version >'), - m('p', this.app.latestVersion - ? `Latest version: ${this.app.latestVersion}` - : '< no version found >'), - ]), - m('div.console', { - onupdate: (vnode) => { - if (this.logUpdated) { - vnode.dom.scrollTop = vnode.dom.scrollHeight - this.logUpdated = false - } - } - }, - m('pre', this.app.logs && this.app.logs || '') - ), - this.db - ? m('div.actions', { - hidden: this.status[this.activeApp + 'Updating'], - }, [ - m('button', { - onclick: () => this.startUpdate(), - }, 'Update & Install'), - m('button', { - hidden: this.status[this.activeApp] || !(this.db[this.activeApp + 'LastActive'] || this.db[this.activeApp + 'LatestInstalled']), - onclick: () => this.startSoftware(), - }, 'Start'), - m('button', { - hidden: !this.db[this.activeApp + 'LastActive'] - || this.db[this.activeApp + 'LastActive'] === this.db[this.activeApp + 'Active'] - }, 'Use Last Version'), - ]) - : null, - ] : null - ]) - } -}) - -module.exports = Updater diff --git a/dev/index.mjs b/dev/index.mjs deleted file mode 100644 index 9e27ec0..0000000 --- a/dev/index.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export function start(config, db, log, core) { - return import('./api/server.mjs').then(function(module) { - return module.run(config, db, log, core) - }) -} \ No newline at end of file diff --git a/dev/package.json b/dev/package.json deleted file mode 100644 index 45e40c7..0000000 --- a/dev/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "app", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "js:build:main": "asbundle app/index.js public/main.js", - "dev": "nodemon --watch app --exec \"npm run js:build:main\"", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC", - "dependencies": { - "asbundle": "^2.6.1", - "mithril": "^2.0.4", - "node-static": "^0.7.11", - "nodemon": "^2.0.4", - "socket.io-serveronly": "^2.3.0" - } -} diff --git a/dev/public/index.html b/dev/public/index.html deleted file mode 100644 index e48aefa..0000000 --- a/dev/public/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - Service Core - - - - -
- - - diff --git a/dev/public/main.css b/dev/public/main.css deleted file mode 100644 index 8a12380..0000000 --- a/dev/public/main.css +++ /dev/null @@ -1,270 +0,0 @@ -html { - box-sizing: border-box; - font-size: 16px; - height: 100%; -} - -*, *:before, *:after { - box-sizing: inherit; -} - -body, h1, h2, h3, h4, h5, h6, p { - margin: 0; - padding: 0; - font-weight: normal; -} - -body { - background: #3d3d3d; - color: #f1f1f1; - display: flex; - font-size: 16px; - min-height: 100vh; - flex-direction: column; - font-family: Helvetica, sans-serif, Arial; -} - -a, a:visited { - color: #eee; - text-decoration: underline; -} - -/* Container */ -.container { - display: flex; - align-items: stretch; - flex-direction: column; - flex-grow: 2; -} - -.disconnected { - position: fixed; - top: 0; - left: 0; - right: 0; - bottom: 0; - background: rgba(0,0,0,0.8); - color: #fff; - font-size: 1em; - display: flex; - justify-content: center; - align-items: center; -} - -[hidden] { display: none !important; } - -main { - display: flex; - flex-direction: column; - align-items: stretch; - flex-grow: 2; - width: 100%; -} - -main h1 { - text-align: center; - font-size: 1.6rem; - line-height: 3.6rem; -} - -form.login { - align-self: center; - display: flex; - flex-direction: column; -} - -button, -a.button { - align-self: center; - min-width: 200px; - background: #ffb843; - color: black; - padding: 0.5rem; - border: none; - cursor: pointer; - text-decoration: none; - border: 1px solid hsl(37.3, 80%, 37%); - text-align: center; -} - -pre { - margin: 0; - padding: 0; -} - -/***************** Header ********************/ -#header { - display: flex; - justify-content: center; - width: 100%; - background: #292929; - align-items: center; -} - -#header a { - width: 150px; - text-align: center; - padding: 1rem; - color: #ffb843; -} - -#header a.active { - color: #999; - text-decoration: none; -} - -#header .seperator { - border-right: 1px solid #999; - height: 1rem; -} - -/***************** Log ********************/ -#logger { - margin: 0 2rem; - display: flex; - flex-direction: column; - border: 1px solid #999; - padding: 0.5rem; - overflow-y: scroll; - height: calc(100vh - 160px); - background: #0c0c0c; - color: #ccc; -} - -#logger div { - margin-left: 1rem; - text-indent: -1rem; - line-height: 1.4rem; - margin-bottom: 0.1rem; -} - -#logger span.white { color: rgb(242,242,242); } -#logger span.yellow { color: rgb(193,156,0); } -#logger span.cyan { color: rgb(58,150,221); } -#logger span.magenta { color: rgb(136,23,152); } -#logger span.red { color: rgb(197,15,31); } -#logger span.green { color: rgb(19,161,14); } -#logger span.inverse { - color: #0c0c0c; - background: white; - display: inline-block; -} - -#logger .padder { - height: 0.5rem; - flex: 0 0 auto; -} - -/***************** Status ********************/ -#status { - display: flex; - flex-direction: column; -} -#status .split { - margin-top: 2rem; - align-self: center; - width: calc(100% - 4rem); - display: flex; - max-width: 700px; - border: 1px solid #999; - border-right: none; -} -#status .item { - flex: 2 1 50%; - display: flex; - flex-direction: column; - border-right: 1px solid #999; - padding-bottom: 0.5rem; -} -#status .item h4 { - font-size: 1.2rem; - text-align: center; - padding: 1rem; - border-bottom: 1px solid #999; - margin-bottom: 0.5rem; -} -#status .item p { - padding: 0.25rem 1rem; -} -#status .item p.running { - color: rgb(19,161,14); - text-align: center; -} -#status .item p.notrunning { - color: rgb(197,15,31); - text-align: center; -} -#status button { - margin-top: 1rem; -} - -/***************** Updater ********************/ -#update { - display: flex; - flex-direction: column; - width: calc(100vw - 4rem); - align-self: center; - max-width: 700px; -} -#update .actions { - margin: 1rem 0; - flex-wrap: wrap; - display: flex; - justify-content: center; -} -#update .actions .filler { - flex-grow: 2; -} -#update .actions .button.active { - background: transparent; - color: #ffb843; -} - -@media only screen and (max-device-width: 590px) { - #update .actions .filler { - flex: 2 1 100%; - } - #update .actions .button { - flex: 2 1 50%; - } -} - -#update h4 { - text-align: center; - padding: 0 1rem 1rem; - font-size: 1.2rem; -} -#update .info { - margin-top: 0rem; - display: flex; - border: 1px solid #999; - border-right: none; - border-bottom: none; - flex-wrap: wrap; -} -#update .info p { - flex: 2 1 50%; - border-right: 1px solid #999; - border-bottom: 1px solid #999; - padding: 0.5rem; -} - -#update .console { - font-family: "Lucida Console", Monaco, monospace; - margin: 1rem 0 0; - display: flex; - flex-direction: column; - border: 1px solid #999; - padding: 0.5rem; - overflow-y: scroll; - height: calc(100vh - 160px); - background: #0c0c0c; - color: #ccc; -} - -@media only screen and (min-height: 650px) { - #update .console { - height: calc(100vh - 340px); - } -} -