diff --git a/api/javascript/liotr.js b/api/javascript/liotr.js index 2a5889e..37de00a 100644 --- a/api/javascript/liotr.js +++ b/api/javascript/liotr.js @@ -1,4 +1,4 @@ -if(typeof XMLHttpRequest === 'undefined') { +if (typeof XMLHttpRequest === 'undefined') { XMLHttpRequest = require('XMLHttpRequest'); } @@ -11,11 +11,11 @@ function LiotR() { /** * The URL of the Liot R server to connect to. */ -LiotR.SERVER = "http://localhost:7474";//eye.lyku.org +LiotR.SERVER = 'http://localhost:7474'; //eye.lyku.org /** -* Session ID of the current login session. Currently unused. -*/ + * Session ID of the current login session. Currently unused. + */ LiotR.SESSION = null; /** @@ -28,26 +28,27 @@ LiotR.SESSION = null; */ LiotR.post = (data, callback) => { var xml = new XMLHttpRequest(); - if(typeof callback == "function") { - xml.addEventListener('load', ()=> { - //alert(xml.response) - callback(JSON.parse(xml.responseText)) + if (typeof callback == 'function') { + xml.addEventListener('load', () => { + //alert(xml.response) + callback(JSON.parse(xml.responseText)); }); xml.addEventListener('error', () => { - callback({err: 'Unable to contact server.'}) + callback({ err: 'Unable to contact server.' }); }); } - - - if(LiotR.SESSION)data.sessionid = LiotR.SESSION; + if (LiotR.SESSION) data.sessionid = LiotR.SESSION; //alert(JSON.stringify(data)) xml.open('POST', LiotR.SERVER); - xml.setRequestHeader("Content-type", "application/json") + xml.setRequestHeader( + 'Content-type', + 'application/json' + ); xml.send(JSON.stringify(data)); return xml; -} +}; /** * Creates one or more packet collectors. @@ -60,9 +61,9 @@ LiotR.post = (data, callback) => { */ LiotR.addCollectors = (data, callback) => { - data.action = "add collectors"; + data.action = 'add collectors'; return LiotR.post(data, callback); -} +}; /** * Lists any packet collectors. @@ -76,9 +77,9 @@ LiotR.addCollectors = (data, callback) => { */ LiotR.listCollectors = (data, callback) => { - data.action = "list collectors"; + data.action = 'list collectors'; return LiotR.post(data, callback); -} +}; /** * Retreives specified packet collectors. @@ -91,9 +92,9 @@ LiotR.listCollectors = (data, callback) => { */ LiotR.getCollectors = (data, callback) => { - data.action = "get collectors"; + data.action = 'get collectors'; return LiotR.post(data, callback); -} +}; /** * Lists any packet collectors. @@ -107,86 +108,86 @@ LiotR.getCollectors = (data, callback) => { */ LiotR.deleteCollectors = (data, callback) => { - data.action = "delete collectors"; + data.action = 'delete collectors'; return LiotR.post(data, callback); -} +}; LiotR.listFilters = (data, callback) => { - data.action = "list filters"; + data.action = 'list filters'; return LiotR.post(data, callback); -} +}; LiotR.addFilters = (data, callback) => { - data.action = "add filters"; + data.action = 'add filters'; return LiotR.post(data, callback); -} +}; LiotR.getFilters = (data, callback) => { - data.action = "get filters"; + data.action = 'get filters'; return LiotR.post(data, callback); -} +}; LiotR.deleteFilters = (data, callback) => { - data.action = "delete filters"; + data.action = 'delete filters'; return LiotR.post(data, callback); -} +}; LiotR.countFilterReferences = (data, callback) => { - data.action = "count filter references"; + data.action = 'count filter references'; return LiotR.post(data, callback); -} +}; LiotR.listFilterReferrers = (data, callback) => { - data.action = "list filter referrers"; + data.action = 'list filter referrers'; return LiotR.post(data, callback); -} +}; LiotR.addCollators = (data, callback) => { - data.action = "add collators"; + data.action = 'add collators'; return LiotR.post(data, callback); -} +}; LiotR.listCollators = (data, callback) => { - data.action = "list collators"; + data.action = 'list collators'; return LiotR.post(data, callback); -} +}; LiotR.getCollators = (data, callback) => { - data.action = "get collators"; + data.action = 'get collators'; return LiotR.post(data, callback); -} +}; LiotR.deleteCollators = (data, callback) => { - data.action = "delete collators"; + data.action = 'delete collators'; return LiotR.post(data, callback); -} +}; LiotR.countCollatorReferences = (data, callback) => { - data.action = "count collator references"; + data.action = 'count collator references'; return LiotR.post(data, callback); -} +}; LiotR.addDistributors = (data, callback) => { - data.action = "add distributors"; + data.action = 'add distributors'; return LiotR.post(data, callback); -} +}; LiotR.listDistributors = (data, callback) => { - data.action = "list distributors"; + data.action = 'list distributors'; return LiotR.post(data, callback); -} +}; LiotR.getDistributors = (data, callback) => { - data.action = "get distributors"; + data.action = 'get distributors'; return LiotR.post(data, callback); -} +}; LiotR.deleteDistributors = (data, callback) => { - data.action = "delete distributors"; + data.action = 'delete distributors'; return LiotR.post(data, callback); -} +}; LiotR.pushUpdate = (data, callback) => { - data.action = "push update"; + data.action = 'push update'; return LiotR.post(data, callback); -} +}; diff --git a/api/javascript/liotr.min.js b/api/javascript/liotr.min.js index 0b825bf..e3eeb9c 100644 --- a/api/javascript/liotr.min.js +++ b/api/javascript/liotr.min.js @@ -1,6 +1,100 @@ -"undefined"===typeof XMLHttpRequest&&(XMLHttpRequest=require("XMLHttpRequest"));function LiotR(){}LiotR.SERVER="http://localhost:7474";LiotR.SESSION=null; -LiotR.post=function(a,b){var c=new XMLHttpRequest;"function"==typeof b&&(c.addEventListener("load",function(){b(JSON.parse(c.responseText))}),c.addEventListener("error",function(){b({err:"Unable to contact server."})}));LiotR.SESSION&&(a.sessionid=LiotR.SESSION);c.open("POST",LiotR.SERVER);c.setRequestHeader("Content-type","application/json");c.send(JSON.stringify(a));return c};LiotR.addCollectors=function(a,b){a.action="add collectors";return LiotR.post(a,b)}; -LiotR.listCollectors=function(a,b){a.action="list collectors";return LiotR.post(a,b)};LiotR.getCollectors=function(a,b){a.action="get collectors";return LiotR.post(a,b)};LiotR.deleteCollectors=function(a,b){a.action="delete collectors";return LiotR.post(a,b)};LiotR.listFilters=function(a,b){a.action="list filters";return LiotR.post(a,b)};LiotR.addFilters=function(a,b){a.action="add filters";return LiotR.post(a,b)};LiotR.getFilters=function(a,b){a.action="get filters";return LiotR.post(a,b)}; -LiotR.deleteFilters=function(a,b){a.action="delete filters";return LiotR.post(a,b)};LiotR.countFilterReferences=function(a,b){a.action="count filter references";return LiotR.post(a,b)};LiotR.listFilterReferrers=function(a,b){a.action="list filter referrers";return LiotR.post(a,b)};LiotR.addCollators=function(a,b){a.action="add collators";return LiotR.post(a,b)};LiotR.listCollators=function(a,b){a.action="list collators";return LiotR.post(a,b)}; -LiotR.getCollators=function(a,b){a.action="get collators";return LiotR.post(a,b)};LiotR.deleteCollators=function(a,b){a.action="delete collators";return LiotR.post(a,b)};LiotR.countCollatorReferences=function(a,b){a.action="count collator references";return LiotR.post(a,b)};LiotR.addDistributors=function(a,b){a.action="add distributors";return LiotR.post(a,b)};LiotR.listDistributors=function(a,b){a.action="list distributors";return LiotR.post(a,b)}; -LiotR.getDistributors=function(a,b){a.action="get distributors";return LiotR.post(a,b)};LiotR.deleteDistributors=function(a,b){a.action="delete distributors";return LiotR.post(a,b)};LiotR.pushUpdate=function(a,b){a.action="push update";return LiotR.post(a,b)}; +'undefined' === typeof XMLHttpRequest && + (XMLHttpRequest = require('XMLHttpRequest')); +function LiotR() {} +LiotR.SERVER = 'http://localhost:7474'; +LiotR.SESSION = null; +LiotR.post = function (a, b) { + var c = new XMLHttpRequest(); + 'function' == typeof b && + (c.addEventListener('load', function () { + b(JSON.parse(c.responseText)); + }), + c.addEventListener('error', function () { + b({ err: 'Unable to contact server.' }); + })); + LiotR.SESSION && (a.sessionid = LiotR.SESSION); + c.open('POST', LiotR.SERVER); + c.setRequestHeader('Content-type', 'application/json'); + c.send(JSON.stringify(a)); + return c; +}; +LiotR.addCollectors = function (a, b) { + a.action = 'add collectors'; + return LiotR.post(a, b); +}; +LiotR.listCollectors = function (a, b) { + a.action = 'list collectors'; + return LiotR.post(a, b); +}; +LiotR.getCollectors = function (a, b) { + a.action = 'get collectors'; + return LiotR.post(a, b); +}; +LiotR.deleteCollectors = function (a, b) { + a.action = 'delete collectors'; + return LiotR.post(a, b); +}; +LiotR.listFilters = function (a, b) { + a.action = 'list filters'; + return LiotR.post(a, b); +}; +LiotR.addFilters = function (a, b) { + a.action = 'add filters'; + return LiotR.post(a, b); +}; +LiotR.getFilters = function (a, b) { + a.action = 'get filters'; + return LiotR.post(a, b); +}; +LiotR.deleteFilters = function (a, b) { + a.action = 'delete filters'; + return LiotR.post(a, b); +}; +LiotR.countFilterReferences = function (a, b) { + a.action = 'count filter references'; + return LiotR.post(a, b); +}; +LiotR.listFilterReferrers = function (a, b) { + a.action = 'list filter referrers'; + return LiotR.post(a, b); +}; +LiotR.addCollators = function (a, b) { + a.action = 'add collators'; + return LiotR.post(a, b); +}; +LiotR.listCollators = function (a, b) { + a.action = 'list collators'; + return LiotR.post(a, b); +}; +LiotR.getCollators = function (a, b) { + a.action = 'get collators'; + return LiotR.post(a, b); +}; +LiotR.deleteCollators = function (a, b) { + a.action = 'delete collators'; + return LiotR.post(a, b); +}; +LiotR.countCollatorReferences = function (a, b) { + a.action = 'count collator references'; + return LiotR.post(a, b); +}; +LiotR.addDistributors = function (a, b) { + a.action = 'add distributors'; + return LiotR.post(a, b); +}; +LiotR.listDistributors = function (a, b) { + a.action = 'list distributors'; + return LiotR.post(a, b); +}; +LiotR.getDistributors = function (a, b) { + a.action = 'get distributors'; + return LiotR.post(a, b); +}; +LiotR.deleteDistributors = function (a, b) { + a.action = 'delete distributors'; + return LiotR.post(a, b); +}; +LiotR.pushUpdate = function (a, b) { + a.action = 'push update'; + return LiotR.post(a, b); +}; diff --git a/api/javascript/lir.min.js b/api/javascript/lir.min.js index 0b825bf..e3eeb9c 100644 --- a/api/javascript/lir.min.js +++ b/api/javascript/lir.min.js @@ -1,6 +1,100 @@ -"undefined"===typeof XMLHttpRequest&&(XMLHttpRequest=require("XMLHttpRequest"));function LiotR(){}LiotR.SERVER="http://localhost:7474";LiotR.SESSION=null; -LiotR.post=function(a,b){var c=new XMLHttpRequest;"function"==typeof b&&(c.addEventListener("load",function(){b(JSON.parse(c.responseText))}),c.addEventListener("error",function(){b({err:"Unable to contact server."})}));LiotR.SESSION&&(a.sessionid=LiotR.SESSION);c.open("POST",LiotR.SERVER);c.setRequestHeader("Content-type","application/json");c.send(JSON.stringify(a));return c};LiotR.addCollectors=function(a,b){a.action="add collectors";return LiotR.post(a,b)}; -LiotR.listCollectors=function(a,b){a.action="list collectors";return LiotR.post(a,b)};LiotR.getCollectors=function(a,b){a.action="get collectors";return LiotR.post(a,b)};LiotR.deleteCollectors=function(a,b){a.action="delete collectors";return LiotR.post(a,b)};LiotR.listFilters=function(a,b){a.action="list filters";return LiotR.post(a,b)};LiotR.addFilters=function(a,b){a.action="add filters";return LiotR.post(a,b)};LiotR.getFilters=function(a,b){a.action="get filters";return LiotR.post(a,b)}; -LiotR.deleteFilters=function(a,b){a.action="delete filters";return LiotR.post(a,b)};LiotR.countFilterReferences=function(a,b){a.action="count filter references";return LiotR.post(a,b)};LiotR.listFilterReferrers=function(a,b){a.action="list filter referrers";return LiotR.post(a,b)};LiotR.addCollators=function(a,b){a.action="add collators";return LiotR.post(a,b)};LiotR.listCollators=function(a,b){a.action="list collators";return LiotR.post(a,b)}; -LiotR.getCollators=function(a,b){a.action="get collators";return LiotR.post(a,b)};LiotR.deleteCollators=function(a,b){a.action="delete collators";return LiotR.post(a,b)};LiotR.countCollatorReferences=function(a,b){a.action="count collator references";return LiotR.post(a,b)};LiotR.addDistributors=function(a,b){a.action="add distributors";return LiotR.post(a,b)};LiotR.listDistributors=function(a,b){a.action="list distributors";return LiotR.post(a,b)}; -LiotR.getDistributors=function(a,b){a.action="get distributors";return LiotR.post(a,b)};LiotR.deleteDistributors=function(a,b){a.action="delete distributors";return LiotR.post(a,b)};LiotR.pushUpdate=function(a,b){a.action="push update";return LiotR.post(a,b)}; +'undefined' === typeof XMLHttpRequest && + (XMLHttpRequest = require('XMLHttpRequest')); +function LiotR() {} +LiotR.SERVER = 'http://localhost:7474'; +LiotR.SESSION = null; +LiotR.post = function (a, b) { + var c = new XMLHttpRequest(); + 'function' == typeof b && + (c.addEventListener('load', function () { + b(JSON.parse(c.responseText)); + }), + c.addEventListener('error', function () { + b({ err: 'Unable to contact server.' }); + })); + LiotR.SESSION && (a.sessionid = LiotR.SESSION); + c.open('POST', LiotR.SERVER); + c.setRequestHeader('Content-type', 'application/json'); + c.send(JSON.stringify(a)); + return c; +}; +LiotR.addCollectors = function (a, b) { + a.action = 'add collectors'; + return LiotR.post(a, b); +}; +LiotR.listCollectors = function (a, b) { + a.action = 'list collectors'; + return LiotR.post(a, b); +}; +LiotR.getCollectors = function (a, b) { + a.action = 'get collectors'; + return LiotR.post(a, b); +}; +LiotR.deleteCollectors = function (a, b) { + a.action = 'delete collectors'; + return LiotR.post(a, b); +}; +LiotR.listFilters = function (a, b) { + a.action = 'list filters'; + return LiotR.post(a, b); +}; +LiotR.addFilters = function (a, b) { + a.action = 'add filters'; + return LiotR.post(a, b); +}; +LiotR.getFilters = function (a, b) { + a.action = 'get filters'; + return LiotR.post(a, b); +}; +LiotR.deleteFilters = function (a, b) { + a.action = 'delete filters'; + return LiotR.post(a, b); +}; +LiotR.countFilterReferences = function (a, b) { + a.action = 'count filter references'; + return LiotR.post(a, b); +}; +LiotR.listFilterReferrers = function (a, b) { + a.action = 'list filter referrers'; + return LiotR.post(a, b); +}; +LiotR.addCollators = function (a, b) { + a.action = 'add collators'; + return LiotR.post(a, b); +}; +LiotR.listCollators = function (a, b) { + a.action = 'list collators'; + return LiotR.post(a, b); +}; +LiotR.getCollators = function (a, b) { + a.action = 'get collators'; + return LiotR.post(a, b); +}; +LiotR.deleteCollators = function (a, b) { + a.action = 'delete collators'; + return LiotR.post(a, b); +}; +LiotR.countCollatorReferences = function (a, b) { + a.action = 'count collator references'; + return LiotR.post(a, b); +}; +LiotR.addDistributors = function (a, b) { + a.action = 'add distributors'; + return LiotR.post(a, b); +}; +LiotR.listDistributors = function (a, b) { + a.action = 'list distributors'; + return LiotR.post(a, b); +}; +LiotR.getDistributors = function (a, b) { + a.action = 'get distributors'; + return LiotR.post(a, b); +}; +LiotR.deleteDistributors = function (a, b) { + a.action = 'delete distributors'; + return LiotR.post(a, b); +}; +LiotR.pushUpdate = function (a, b) { + a.action = 'push update'; + return LiotR.post(a, b); +}; diff --git a/examples/demo-collector.js b/examples/demo-collector.js index 60ab981..85ac6e7 100644 --- a/examples/demo-collector.js +++ b/examples/demo-collector.js @@ -5,25 +5,29 @@ var interval = setInterval(query, 5); var counterval = setInterval(counter, 1000); function counter() { - process.stdout.clearLine(); - process.stdout.cursorTo(0); - process.stdout.write("Q: "+queue) + process.stdout.clearLine(); + process.stdout.cursorTo(0); + process.stdout.write('Q: ' + queue); } function query() { - //console.log("querying"); - queue++; - request.post({ - url:'http://localhost:7474', - body: { - accessor: '9903a075-86f5-48eb-b4a4-acb8b35c55f4', - action: 'push update', - value: 63 - }, - json:true - }, (err, res, bod) => { - //console.log(err || bod || res); - queue--; - //console.log(queue); - }) + //console.log("querying"); + queue++; + request.post( + { + url: 'http://localhost:7474', + body: { + accessor: + '9903a075-86f5-48eb-b4a4-acb8b35c55f4', + action: 'push update', + value: 63 + }, + json: true + }, + (err, res, bod) => { + //console.log(err || bod || res); + queue--; + //console.log(queue); + } + ); } diff --git a/examples/demo-receiver.js b/examples/demo-receiver.js index 7b70c09..510a176 100644 --- a/examples/demo-receiver.js +++ b/examples/demo-receiver.js @@ -1,29 +1,20 @@ - var COMPARATORS = [ - "EQUALS", - "NEQUALS", - "TFEQUALS", - "TFNEQUALS", - "OVER", - "OVEROR", - "UNDER", - "UNDEROR", -] - -var OPERATORS = [ - "AND", - "OR", - "NAND", - "NOR", - "XOR", - "SAME", -] - + 'EQUALS', + 'NEQUALS', + 'TFEQUALS', + 'TFNEQUALS', + 'OVER', + 'OVEROR', + 'UNDER', + 'UNDEROR' +]; + +var OPERATORS = ['AND', 'OR', 'NAND', 'NOR', 'XOR', 'SAME']; var r = require('rethinkdb'); var express = require('express'); var bodyParser = require('body-parser'); -var validUrl = require('valid-url') +var validUrl = require('valid-url'); var request = require('request'); const app = express(); var fs = require('fs'); @@ -33,102 +24,126 @@ var sinceLast = 0; var counterval = setInterval(counter, 1000); function counter() { - process.stdout.clearLine(); - process.stdout.cursorTo(0); - process.stdout.write("QPS: "+sinceLast) - sinceLast = 0; + process.stdout.clearLine(); + process.stdout.cursorTo(0); + process.stdout.write('QPS: ' + sinceLast); + sinceLast = 0; } app.use(bodyParser.json()); app.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header( + 'Access-Control-Allow-Headers', + 'Origin, X-Requested-With, Content-Type, Accept' + ); + next(); +}); - res.header('Access-Control-Allow-Origin','*') - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - next(); -}) - +var kRETURN_CHANGES = { return_changes: true }; -var kRETURN_CHANGES = {return_changes: true}; - -var ADMINACTIONS = { -} - -var PUBLICACTIONS = { -} +var ADMINACTIONS = {}; +var PUBLICACTIONS = {}; readConfig(); function readConfig() { - fs.readFile('liot-server-conf.json', (err, buffer) => { - if(buffer) { - var json = JSON.parse(buffer.toString()); - if(json.port)CONFIG.port = json.port; - console.log(json); - startRethinkServer(); - launchHttpServer(); - } else { - startRethinkServer(); - launchHttpServer(); - } - }) + fs.readFile('liot-server-conf.json', (err, buffer) => { + if (buffer) { + var json = JSON.parse(buffer.toString()); + if (json.port) CONFIG.port = json.port; + console.log(json); + startRethinkServer(); + launchHttpServer(); + } else { + startRethinkServer(); + launchHttpServer(); + } + }); } -function startRethinkServer() {/* 1.db.yup.place => localhost */ - r.connect({host:'localhost'},(err, conn)=>{ - if(err || !conn) { - console.log("Cannot connect to RethinkDB"); - } else { - r.dbList().contains('LiotR') - .do(exists=>{ - return r.branch( - exists, - {dbs_created: 0}, - r.dbCreate('LiotR') - ); - }).run(conn, (err, status) => { - if(err || !conn) { - console.log('Could not ensure existence of database for Liot R.'); - return false; - } else { - CONNECTION = conn; - conn.use('LiotR'); - if(status.dbs_created) - console.log("Created database for Liot R.") - else - console.log("Found database for Liot R.") - console.log('Connected to database for Liot R.'); - return true; - } - }) - } - }) +function startRethinkServer() { + /* 1.db.yup.place => localhost */ + r.connect({ host: 'localhost' }, (err, conn) => { + if (err || !conn) { + console.log('Cannot connect to RethinkDB'); + } else { + r.dbList() + .contains('LiotR') + .do(exists => { + return r.branch( + exists, + { dbs_created: 0 }, + r.dbCreate('LiotR') + ); + }) + .run(conn, (err, status) => { + if (err || !conn) { + console.log( + 'Could not ensure existence of database for Liot R.' + ); + return false; + } else { + CONNECTION = conn; + conn.use('LiotR'); + if (status.dbs_created) + console.log( + 'Created database for Liot R.' + ); + else + console.log( + 'Found database for Liot R.' + ); + console.log( + 'Connected to database for Liot R.' + ); + return true; + } + }); + } + }); //r.db('Yup'); } function launchHttpServer() { - app.post('/', rcvdPost) + app.post('/', rcvdPost); - app.listen(CONFIG.port) + app.listen(CONFIG.port); } function rcvdPost(req, res) { - var address = req.connection.remoteAddress; - var isLocal = address.match(/^(127.0.0.1|::ffff:127.0.0.1|::1)$/)&&true; - //console.log(isLocal) - //console.log(req.body); - var json = req.body; - var action = json.action - res.header('Access-Control-Allow-Origin','*') - if(action) { - var dat = req.body; - if(isLocal && action in ADMINACTIONS) { - ADMINACTIONS[action](DEBUG, CONNECTION, req, res, dat); - } else if(action in PUBLICACTIONS) { - PUBLICACTIONS[action](DEBUG, CONNECTION, req, res, dat); - } - } - sinceLast++; - //console.log(req) + var address = req.connection.remoteAddress; + var isLocal = + address.match( + /^(127.0.0.1|::ffff:127.0.0.1|::1)$/ + ) && true; + //console.log(isLocal) + //console.log(req.body); + var json = req.body; + var action = json.action; + res.header('Access-Control-Allow-Origin', '*'); + if (action) { + var dat = req.body; + if (isLocal && action in ADMINACTIONS) { + ADMINACTIONS[action]( + DEBUG, + CONNECTION, + req, + res, + dat + ); + } else if (action in PUBLICACTIONS) { + PUBLICACTIONS[action]( + DEBUG, + CONNECTION, + req, + res, + dat + ); + } + } + sinceLast++; + //console.log(req) } diff --git a/server/index.ts b/server/index.ts index 8cba21f..3d39382 100644 --- a/server/index.ts +++ b/server/index.ts @@ -1,16 +1,21 @@ import * as fs from 'fs/promises'; -import {exists as existsCallback} from 'fs'; -import {promisify} from "util"; +import { exists as existsCallback } from 'fs'; +import { promisify } from 'util'; import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as dash from 'rethinkdbdash'; const exists = promisify(existsCallback); -const TABLES = ['Filters', 'Collectors', 'Collators', 'Distributors', 'DistributedData'] +const TABLES = [ + 'Filters', + 'Collectors', + 'Collators', + 'Distributors', + 'DistributedData' +]; const ENSURED_TABLES = []; - let r; const app = express(); @@ -22,147 +27,164 @@ CONFIG.port = 7474; app.use(bodyParser.json()); app.use((req, res, next) => { - - res.header('Access-Control-Allow-Origin', '*') - res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); - next(); -}) - + res.header('Access-Control-Allow-Origin', '*'); + res.header( + 'Access-Control-Allow-Headers', + 'Origin, X-Requested-With, Content-Type, Accept' + ); + next(); +}); const actions = { - collectors: { - list: require('./modules/actions/action-list-collectors'), - add: require('./modules/actions/action-add-collectors'), - get: require('./modules/actions/action-get-collectors'), - delete: require('./modules/actions/action-delete-collectors') - }, - filters: { - list: require('./modules/actions/action-list-filters'), - add: require('./modules/actions/action-add-filters'), - get: require('./modules/actions/action-get-filters'), - delete: require('./modules/actions/action-delete-filters'), - references: { - count: require('./modules/actions/action-count-filter-references') - }, - referrers: { - list: require('./modules/actions/action-list-filter-referrers') - } - }, - collators: { - list: require('./modules/actions/action-list-collators'), - add: require('./modules/actions/action-add-collators'), - get: require('./modules/actions/action-get-collators'), - delete: require('./modules/actions/action-delete-collators'), - references: { - count: require('./modules/actions/action-count-collator-references') - } - }, - distributors: { - list: require('./modules/actions/action-list-distributors'), - add: require('./modules/actions/action-add-distributors'), - get: require('./modules/actions/action-get-distributors'), - delete: require('./modules/actions/action-delete-distributors') - }, - updates: { - push: require('./modules/actions/action-push-update') - } -} + collectors: { + list: require('./modules/actions/action-list-collectors'), + add: require('./modules/actions/action-add-collectors'), + get: require('./modules/actions/action-get-collectors'), + delete: require('./modules/actions/action-delete-collectors') + }, + filters: { + list: require('./modules/actions/action-list-filters'), + add: require('./modules/actions/action-add-filters'), + get: require('./modules/actions/action-get-filters'), + delete: require('./modules/actions/action-delete-filters'), + references: { + count: require('./modules/actions/action-count-filter-references') + }, + referrers: { + list: require('./modules/actions/action-list-filter-referrers') + } + }, + collators: { + list: require('./modules/actions/action-list-collators'), + add: require('./modules/actions/action-add-collators'), + get: require('./modules/actions/action-get-collators'), + delete: require('./modules/actions/action-delete-collators'), + references: { + count: require('./modules/actions/action-count-collator-references') + } + }, + distributors: { + list: require('./modules/actions/action-list-distributors'), + add: require('./modules/actions/action-add-distributors'), + get: require('./modules/actions/action-get-distributors'), + delete: require('./modules/actions/action-delete-distributors') + }, + updates: { + push: require('./modules/actions/action-push-update') + } +}; const adminActions = { - /*Collectors*/ - "list collectors": actions.collectors.list, - "add collectors": actions.collectors.add, - "get collectors": actions.collectors.get, - "delete collectors": actions.collectors.delete, - //"get referenced collectors": actionGetReferencedCollectors, - /*Filters*/ - "list filters": actions.filters.list, - "add filters": actions.filters.add, - "get filters": actions.filters.get, - "delete filters": actions.filters.delete, - "count filter references": actions.filters.references.count, - "list filter referrers": actions.filters.referrers.list, - /*Collators*/ - "list collators": actions.collators.list, - "add collators": actions.collators.add, - "get collators": actions.collators.get, - "delete collators": actions.collators.delete, - "count collator references": actions.collators.references.count, - /*Distributors*/ - "list distributors": actions.distributors.list, - "add distributors": actions.distributors.add, - "get distributors": actions.distributors.get, - "delete distributors": actions.distributors.delete, - /*Misc*/ - "push update": actions.updates.push + /*Collectors*/ + 'list collectors': actions.collectors.list, + 'add collectors': actions.collectors.add, + 'get collectors': actions.collectors.get, + 'delete collectors': actions.collectors.delete, + //"get referenced collectors": actionGetReferencedCollectors, + /*Filters*/ + 'list filters': actions.filters.list, + 'add filters': actions.filters.add, + 'get filters': actions.filters.get, + 'delete filters': actions.filters.delete, + 'count filter references': + actions.filters.references.count, + 'list filter referrers': actions.filters.referrers.list, + /*Collators*/ + 'list collators': actions.collators.list, + 'add collators': actions.collators.add, + 'get collators': actions.collators.get, + 'delete collators': actions.collators.delete, + 'count collator references': + actions.collators.references.count, + /*Distributors*/ + 'list distributors': actions.distributors.list, + 'add distributors': actions.distributors.add, + 'get distributors': actions.distributors.get, + 'delete distributors': actions.distributors.delete, + /*Misc*/ + 'push update': actions.updates.push }; const publicActions = {}; - readConfig(); async function readConfig() { - const text = await fs.readFile('liot-server-conf.json', 'utf8'), - json = JSON.parse(text); - if (json.port) CONFIG.port = json.port; - console.log('config', json); - await startRethinkServer(); - await launchHttpServer(); + const text = await fs.readFile( + 'liot-server-conf.json', + 'utf8' + ), + json = JSON.parse(text); + if (json.port) CONFIG.port = json.port; + console.log('config', json); + await startRethinkServer(); + await launchHttpServer(); } async function startRethinkServer() { - r = dash({}); - await r.dbList().contains('LiotR') - .do(exists => { - return r.branch( - exists, - {dbs_created: 0}, - r.dbCreate('LiotR') - ); - }); - r = dash({db: 'LiotR'}); - console.log('Connected to database for Liot R.'); - for (const t of TABLES) - await ensureTable(t); - return true; + r = dash({}); + await r + .dbList() + .contains('LiotR') + .do(exists => { + return r.branch( + exists, + { dbs_created: 0 }, + r.dbCreate('LiotR') + ); + }); + r = dash({ db: 'LiotR' }); + console.log('Connected to database for Liot R.'); + for (const t of TABLES) await ensureTable(t); + return true; } async function ensureTable(t) { - const status = await r.tableList().contains(t).do(e => - r.branch(e, - {dbs_created: 0}, - r.tableCreate(t) - ) - ); - if (status.dbs_created) console.log("Table " + t + " created."); - ENSURED_TABLES.push(t); - if (ENSURED_TABLES.length == TABLES.length) - console.log('All tables ensured.'); + const status = await r + .tableList() + .contains(t) + .do(e => + r.branch( + e, + { dbs_created: 0 }, + r.tableCreate(t) + ) + ); + if (status.dbs_created) + console.log('Table ' + t + ' created.'); + ENSURED_TABLES.push(t); + if (ENSURED_TABLES.length == TABLES.length) + console.log('All tables ensured.'); } async function launchHttpServer() { - app.post('/', rcvdPost) - console.log(`HTTP server launched on port ${CONFIG.port}.`) - app.listen(CONFIG.port) - if (await exists('./webui')) { - adminPanel.listen(80); - adminPanel.use(express.static('./webui')); - console.log(`Admin panel launched on port ${80}.`) - } else - console.log("No admin panel detected. Running in headless mode."); + app.post('/', rcvdPost); + console.log( + `HTTP server launched on port ${CONFIG.port}.` + ); + app.listen(CONFIG.port); + if (await exists('./webui')) { + adminPanel.listen(80); + adminPanel.use(express.static('./webui')); + console.log(`Admin panel launched on port ${80}.`); + } else + console.log( + 'No admin panel detected. Running in headless mode.' + ); } async function rcvdPost(req, res) { - const address = req.connection.remoteAddress, - isLocal = address.match(/^(127.0.0.1|::ffff:127.0.0.1|::1)$/) && true, - json = req.body, - {action} = json; - res.header('Access-Control-Allow-Origin', '*') - if (!action) - return; - if (isLocal && action in adminActions) - res.send(adminActions[action](json, r)); - else if (action in publicActions) - res.send(publicActions[action](json, r)); + const address = req.connection.remoteAddress, + isLocal = + address.match( + /^(127.0.0.1|::ffff:127.0.0.1|::1)$/ + ) && true, + json = req.body, + { action } = json; + res.header('Access-Control-Allow-Origin', '*'); + if (!action) return; + if (isLocal && action in adminActions) + res.send(adminActions[action](json, r)); + else if (action in publicActions) + res.send(publicActions[action](json, r)); } diff --git a/server/modules/ComparatorList.ts b/server/modules/ComparatorList.ts index a9049cc..6210c6f 100644 --- a/server/modules/ComparatorList.ts +++ b/server/modules/ComparatorList.ts @@ -1,10 +1,10 @@ export const COMPARATORS = [ - "EQUALS", - "NEQUALS", - "TFEQUALS", - "TFNEQUALS", - "OVER", - "OVEROR", - "UNDER", - "UNDEROR", -] \ No newline at end of file + 'EQUALS', + 'NEQUALS', + 'TFEQUALS', + 'TFNEQUALS', + 'OVER', + 'OVEROR', + 'UNDER', + 'UNDEROR' +]; diff --git a/server/modules/OperatorList.ts b/server/modules/OperatorList.ts index 6c1c89c..f384f3d 100644 --- a/server/modules/OperatorList.ts +++ b/server/modules/OperatorList.ts @@ -1,8 +1,8 @@ export const OPERATORS = [ - "AND", - "OR", - "NAND", - "NOR", - "XOR", - "SAME", + 'AND', + 'OR', + 'NAND', + 'NOR', + 'XOR', + 'SAME' ]; diff --git a/server/modules/actions/action-add-collators.ts b/server/modules/actions/action-add-collators.ts index 5f9af17..3c08bdb 100644 --- a/server/modules/actions/action-add-collators.ts +++ b/server/modules/actions/action-add-collators.ts @@ -1,4 +1,4 @@ -import {insertCollators} from '../insert-collators'; +import { insertCollators } from '../insert-collators'; /** * Creates one or more filter collators. @@ -6,25 +6,33 @@ import {insertCollators} from '../insert-collators'; * @function */ export async function actionAddCollators(params, r) { - const collators = [], tcol: any = {}, filters = []; - if (Array.isArray(params.collators)) - for (const collator of params.collators) { - if (typeof collator.id === "string") - tcol.id = collator.id; - if (typeof collator.name === "string" && collator.name.length) - tcol.name = collator.name; - if (Array.isArray(collator.filters)) - for (const filter of collator.filters) - if (typeof filter === 'string' && filters.indexOf(filter) === -1) - filters.push(filter); - tcol.filters = filters; - collators.push(tcol); - } - try { - await insertCollators(r, collators); - } catch (err) { - console.error(err); - return {err: "Unable to create collators."}; - } - return {}; + const collators = [], + tcol: any = {}, + filters = []; + if (Array.isArray(params.collators)) + for (const collator of params.collators) { + if (typeof collator.id === 'string') + tcol.id = collator.id; + if ( + typeof collator.name === 'string' && + collator.name.length + ) + tcol.name = collator.name; + if (Array.isArray(collator.filters)) + for (const filter of collator.filters) + if ( + typeof filter === 'string' && + filters.indexOf(filter) === -1 + ) + filters.push(filter); + tcol.filters = filters; + collators.push(tcol); + } + try { + await insertCollators(r, collators); + } catch (err) { + console.error(err); + return { err: 'Unable to create collators.' }; + } + return {}; } diff --git a/server/modules/actions/action-add-collectors.ts b/server/modules/actions/action-add-collectors.ts index bf31d20..6a74718 100644 --- a/server/modules/actions/action-add-collectors.ts +++ b/server/modules/actions/action-add-collectors.ts @@ -1,38 +1,62 @@ -import {sortify} from '../sortify'; -import {insertCollectors} from '../insert-collectors'; +import { sortify } from '../sortify'; +import { insertCollectors } from '../insert-collectors'; /** * Creates one or more packet collectors. * @name Action: Add Collectors * @function */ -export async function actionAddCollectors({collectors}, r) { - const sanitizedCollectors = []; - const manufacturer_attributes = ['manufacture_req.bodye', 'manufacturer', 'model', 'series']; - if (!Array.isArray(collectors)) - return {err: '`collectors` must be an array'}; - for (const collector of collectors) { - if (typeof collector !== 'object') - return {err: 'All collectors must be valid objects'}; - const trec: any = {}; - if (typeof collector.device_info === 'object') { - const device_info = collector.device_info; - trec.device_info = {}; - for (const manufacturer_attribute of manufacturer_attributes) - if (typeof device_info[manufacturer_attribute] === 'string' && device_info[manufacturer_attribute].length < 100) - trec.device_info[manufacturer_attribute] = device_info[manufacturer_attribute]; - } - if (typeof collector.name === 'string' && collector.name.length < 100) - trec.name = collector.name; - trec.value = 0; - trec.smart = sortify(collector.name || ""); - trec.aggregate = !!collector.aggregate; - trec.accessor = r.uuid();//rename collators to funnels? - sanitizedCollectors.push(trec); - } - try { - return await insertCollectors(r, sanitizedCollectors); - } catch (err) { - return {err: 'Could not create collectors.'}; - } -} \ No newline at end of file +export async function actionAddCollectors( + { collectors }, + r +) { + const sanitizedCollectors = []; + const manufacturer_attributes = [ + 'manufacture_req.bodye', + 'manufacturer', + 'model', + 'series' + ]; + if (!Array.isArray(collectors)) + return { err: '`collectors` must be an array' }; + for (const collector of collectors) { + if (typeof collector !== 'object') + return { + err: 'All collectors must be valid objects' + }; + const trec: any = {}; + if (typeof collector.device_info === 'object') { + const device_info = collector.device_info; + trec.device_info = {}; + for (const manufacturer_attribute of manufacturer_attributes) + if ( + typeof device_info[ + manufacturer_attribute + ] === 'string' && + device_info[manufacturer_attribute] + .length < 100 + ) + trec.device_info[ + manufacturer_attribute + ] = device_info[manufacturer_attribute]; + } + if ( + typeof collector.name === 'string' && + collector.name.length < 100 + ) + trec.name = collector.name; + trec.value = 0; + trec.smart = sortify(collector.name || ''); + trec.aggregate = !!collector.aggregate; + trec.accessor = r.uuid(); //rename collators to funnels? + sanitizedCollectors.push(trec); + } + try { + return await insertCollectors( + r, + sanitizedCollectors + ); + } catch (err) { + return { err: 'Could not create collectors.' }; + } +} diff --git a/server/modules/actions/action-add-distributors.ts b/server/modules/actions/action-add-distributors.ts index 385f738..df4b900 100644 --- a/server/modules/actions/action-add-distributors.ts +++ b/server/modules/actions/action-add-distributors.ts @@ -1,4 +1,4 @@ -import {insertDistributors} from '../insert-distributors'; +import { insertDistributors } from '../insert-distributors'; import * as validUrl from 'valid-url'; /** @@ -7,32 +7,42 @@ import * as validUrl from 'valid-url'; * @function */ export async function actionAddDistributors(params, r) { - if (!Array.isArray(params.distributors)) - return {err: '`distributors` must be a valid array'}; - const distributors = []; - for (const distributor of params.distributors) { - if(typeof distributor !== 'object') - return {err: 'All distributors must be valid objects'}; - const trans: any = {collators: []}; - if (typeof distributor.id === "string") - trans.id = distributor.id; - if (Array.isArray(distributor.collators)) - for (const collator of distributor.collators) - trans.collators.push(collator); - if (typeof distributor.url === 'string' && validUrl.isUri(distributor.url)) - trans.url = distributor.url; - if (typeof distributor.name === 'string' && distributor.name.length > 0) - trans.name = distributor.name; - trans.push = !!distributor.push; - trans.queue = !!distributor.queue; - trans.callback = !!distributor.callback; - distributors.push(trans); - } - try { - await insertDistributors(r, distributors); - } catch (err) { - console.error(err); - return {err: 'Error creating distributors.'}; - } - return {}; + if (!Array.isArray(params.distributors)) + return { + err: '`distributors` must be a valid array' + }; + const distributors = []; + for (const distributor of params.distributors) { + if (typeof distributor !== 'object') + return { + err: 'All distributors must be valid objects' + }; + const trans: any = { collators: [] }; + if (typeof distributor.id === 'string') + trans.id = distributor.id; + if (Array.isArray(distributor.collators)) + for (const collator of distributor.collators) + trans.collators.push(collator); + if ( + typeof distributor.url === 'string' && + validUrl.isUri(distributor.url) + ) + trans.url = distributor.url; + if ( + typeof distributor.name === 'string' && + distributor.name.length > 0 + ) + trans.name = distributor.name; + trans.push = !!distributor.push; + trans.queue = !!distributor.queue; + trans.callback = !!distributor.callback; + distributors.push(trans); + } + try { + await insertDistributors(r, distributors); + } catch (err) { + console.error(err); + return { err: 'Error creating distributors.' }; + } + return {}; } diff --git a/server/modules/actions/action-add-filters.ts b/server/modules/actions/action-add-filters.ts index 7b0fa01..e33fb81 100644 --- a/server/modules/actions/action-add-filters.ts +++ b/server/modules/actions/action-add-filters.ts @@ -1,7 +1,6 @@ -import {insertFilters} from '../insert-filters'; -import {COMPARATORS} from "../ComparatorList"; -import {OPERATORS} from "../OperatorList"; - +import { insertFilters } from '../insert-filters'; +import { COMPARATORS } from '../ComparatorList'; +import { OPERATORS } from '../OperatorList'; /** * Creates one or more packet filters. @@ -9,62 +8,97 @@ import {OPERATORS} from "../OperatorList"; * @function */ export async function actionAddFilters(params, r) { - if (!Array.isArray(params.filters)) - return {err: '`filters` must be a valid array'}; - const filters = []; - for (const filter of params.filters) { - const trans: any = {}; - if (typeof filter.name === "string") - trans.name = filter.name; - if (typeof filter.id === "string") - trans.id = filter.id; - if (typeof filter.code === "string") { - const code = filter.code; - let json; - try { - json = JSON.parse(code); - } catch (error) { - return {err: 'Invalid JSON'}; - } - recur(json); + if (!Array.isArray(params.filters)) + return { err: '`filters` must be a valid array' }; + const filters = []; + for (const filter of params.filters) { + const trans: any = {}; + if (typeof filter.name === 'string') + trans.name = filter.name; + if (typeof filter.id === 'string') + trans.id = filter.id; + if (typeof filter.code === 'string') { + const code = filter.code; + let json; + try { + json = JSON.parse(code); + } catch (error) { + return { err: 'Invalid JSON' }; + } + recur(json); - function recur(tree, current?) { - //console.log(tree, current); - const top = typeof current == 'undefined'; - if (!top && ['number', 'string'].includes(typeof tree[current])) { - if (!COMPARATORS.includes(current)) - return {err: 'All numbers and strings must reside in comparators.'}; - } else if (!Array.isArray(tree)) { - if (!top && current && !OPERATORS.includes(current)) - return {err: 'Not a valid operator.'}; - const keys = Object.keys(tree); - //console.log(top && keys.length != 1) - if (top && keys.length != 1) - return {err: "Root object must contain exactly one object, not " + keys.length}; - if (!top && keys.length !== 2) - return {err: 'Operator ' + current + ' expects 2 parameters, not ' + keys.length}; - for (const key of keys) { - if (!COMPARATORS.includes(key) && !OPERATORS.includes(key)) - return {err: 'Invalid comparator or operator.'}; - recur(tree[key], key); - } - } else { // Tree is an array - //console.log('array: ' + current); - if (!COMPARATORS.includes(current)) - return {err: 'Invalid comparator.'}; - if (tree.length != 2) - return {err: 'All comparators expect 2 parameters. Found ' + tree.length}; - } - } + function recur(tree, current?) { + //console.log(tree, current); + const top = typeof current == 'undefined'; + if ( + !top && + ['number', 'string'].includes( + typeof tree[current] + ) + ) { + if (!COMPARATORS.includes(current)) + return { + err: 'All numbers and strings must reside in comparators.' + }; + } else if (!Array.isArray(tree)) { + if ( + !top && + current && + !OPERATORS.includes(current) + ) + return { + err: 'Not a valid operator.' + }; + const keys = Object.keys(tree); + //console.log(top && keys.length != 1) + if (top && keys.length != 1) + return { + err: + 'Root object must contain exactly one object, not ' + + keys.length + }; + if (!top && keys.length !== 2) + return { + err: + 'Operator ' + + current + + ' expects 2 parameters, not ' + + keys.length + }; + for (const key of keys) { + if ( + !COMPARATORS.includes(key) && + !OPERATORS.includes(key) + ) + return { + err: 'Invalid comparator or operator.' + }; + recur(tree[key], key); + } + } else { + // Tree is an array + //console.log('array: ' + current); + if (!COMPARATORS.includes(current)) + return { + err: 'Invalid comparator.' + }; + if (tree.length != 2) + return { + err: + 'All comparators expect 2 parameters. Found ' + + tree.length + }; + } + } - trans.code = filter.code; - trans.json = json; - } - filters.push(trans); - } - try { - await insertFilters(r, filters); - } catch (err) { - return {err: 'Error creating filters.'}; - } + trans.code = filter.code; + trans.json = json; + } + filters.push(trans); + } + try { + await insertFilters(r, filters); + } catch (err) { + return { err: 'Error creating filters.' }; + } } diff --git a/server/modules/actions/action-count-collator-references.ts b/server/modules/actions/action-count-collator-references.ts index 9caee4b..ea49475 100644 --- a/server/modules/actions/action-count-collator-references.ts +++ b/server/modules/actions/action-count-collator-references.ts @@ -1,4 +1,4 @@ -import {buildCollatorReferenceCounterQuery} from '../query-builder'; +import { buildCollatorReferenceCounterQuery } from '../query-builder'; /** * Count the number of distributors referencing one or more filter collators. @@ -7,18 +7,21 @@ import {buildCollatorReferenceCounterQuery} from '../query-builder'; * @param {array} ids - I don't remember * @param {object} r - connection to the RethinkDB database */ -export async function actionCountCollatorReferences({ids}, r) { - const query = buildCollatorReferenceCounterQuery( - Array.isArray(ids) - ? ids - : null, - r - ); - try { - const collators = await query; - console.log('Collators', collators); - return {collators}; - } catch (err) { - return {err: 'Error counting collator references.'}; - } +export async function actionCountCollatorReferences( + { ids }, + r +) { + const query = buildCollatorReferenceCounterQuery( + Array.isArray(ids) ? ids : null, + r + ); + try { + const collators = await query; + console.log('Collators', collators); + return { collators }; + } catch (err) { + return { + err: 'Error counting collator references.' + }; + } } diff --git a/server/modules/actions/action-count-filter-references.ts b/server/modules/actions/action-count-filter-references.ts index 0a7443c..fc4512c 100644 --- a/server/modules/actions/action-count-filter-references.ts +++ b/server/modules/actions/action-count-filter-references.ts @@ -1,4 +1,4 @@ -import {buildFilterReferenceCounterQuery} from '../query-builder'; +import { buildFilterReferenceCounterQuery } from '../query-builder'; /** * Count the number of collators referencing one or more packet filters. @@ -7,12 +7,18 @@ import {buildFilterReferenceCounterQuery} from '../query-builder'; * @param {array} ids - I don't remember * @param {object} r - connection to the RethinkDB database */ -export async function actionCountFilterReferences({ids}, r) { - const query = buildFilterReferenceCounterQuery(Array.isArray(ids) ? ids : null, r); - try { - const filters = await query.coerceTo('array'); - return {filters}; - } catch(e) { - return {err: 'Error counting filter references.'}; - } +export async function actionCountFilterReferences( + { ids }, + r +) { + const query = buildFilterReferenceCounterQuery( + Array.isArray(ids) ? ids : null, + r + ); + try { + const filters = await query.coerceTo('array'); + return { filters }; + } catch (e) { + return { err: 'Error counting filter references.' }; + } } diff --git a/server/modules/actions/action-delete-collators.ts b/server/modules/actions/action-delete-collators.ts index 8cd32b0..0abbbce 100644 --- a/server/modules/actions/action-delete-collators.ts +++ b/server/modules/actions/action-delete-collators.ts @@ -1,4 +1,4 @@ -import {deleteCollators} from '../delete-collators'; +import { deleteCollators } from '../delete-collators'; /** * Delete one or more filter collators. Exposed to API. @@ -9,16 +9,19 @@ import {deleteCollators} from '../delete-collators'; * @param {object} req - Express request * @param {object} res - Express response */ -export async function actionDeleteCollators({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'} - try { - const collators = await deleteCollators(r, ids); - console.log('Deleted collators.', collators); - return {collators: collators}; - } catch (err) { - return {err: 'Unable to delete collators.'}; - } +export async function actionDeleteCollators({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const collators = await deleteCollators(r, ids); + console.log('Deleted collators.', collators); + return { collators: collators }; + } catch (err) { + return { err: 'Unable to delete collators.' }; + } } diff --git a/server/modules/actions/action-delete-collectors.ts b/server/modules/actions/action-delete-collectors.ts index 82cff51..232c39a 100644 --- a/server/modules/actions/action-delete-collectors.ts +++ b/server/modules/actions/action-delete-collectors.ts @@ -1,4 +1,4 @@ -import {deleteCollectors} from "../delete-collectors"; +import { deleteCollectors } from '../delete-collectors'; /** * Delete one or more packet collectors. @@ -7,17 +7,19 @@ import {deleteCollectors} from "../delete-collectors"; * @param {boolean} {ids} - request supposedly containing collector ID list * @param {object} r - connection to the RethinkDB database */ -export function actionDeleteCollectors({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) - if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const deleted = deleteCollectors(r, ids); - console.log('Deleted collectors.', deleted); - return {}; - } catch (err) { - return {err: 'Unable to delete collectors.'}; - } +export function actionDeleteCollectors({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const deleted = deleteCollectors(r, ids); + console.log('Deleted collectors.', deleted); + return {}; + } catch (err) { + return { err: 'Unable to delete collectors.' }; + } } diff --git a/server/modules/actions/action-delete-distributors.ts b/server/modules/actions/action-delete-distributors.ts index 9553673..a9c60f3 100644 --- a/server/modules/actions/action-delete-distributors.ts +++ b/server/modules/actions/action-delete-distributors.ts @@ -1,4 +1,4 @@ -import {deleteDistributors} from "../delete-distributors"; +import { deleteDistributors } from '../delete-distributors'; /** * Delete one or more packet distributors. @@ -9,20 +9,30 @@ import {deleteDistributors} from "../delete-distributors"; * @param {object} req - Express request * @param {object} res - Express response */ -export async function actionDeleteDistributors(DEBUG, CONNECTION, req, res) { - if (!Array.isArray(req.body.ids)) - return {err: "No list of IDs provided."}; - for (const id of req.body.ids) - if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const deleted = await deleteDistributors(CONNECTION, req.body.ids); - console.log('Deleted distributors.', deleted); - return {}; - } catch (err) { - console.error(err); - return {err: 'Unable to delete distributors.'}; - } +export async function actionDeleteDistributors( + DEBUG, + CONNECTION, + req, + res +) { + if (!Array.isArray(req.body.ids)) + return { err: 'No list of IDs provided.' }; + for (const id of req.body.ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const deleted = await deleteDistributors( + CONNECTION, + req.body.ids + ); + console.log('Deleted distributors.', deleted); + return {}; + } catch (err) { + console.error(err); + return { err: 'Unable to delete distributors.' }; + } } module.exports = actionDeleteDistributors; diff --git a/server/modules/actions/action-delete-filters.ts b/server/modules/actions/action-delete-filters.ts index 8f534cd..7184fde 100644 --- a/server/modules/actions/action-delete-filters.ts +++ b/server/modules/actions/action-delete-filters.ts @@ -1,4 +1,4 @@ -import {deleteFilters} from "../delete-filters"; +import { deleteFilters } from '../delete-filters'; /** * Delete one or more packet filters. @@ -7,17 +7,19 @@ import {deleteFilters} from "../delete-filters"; * @param {array} params - request supposedly containing filter IDs * @param {object} r - connection to the RethinkDB database */ -export async function actionDeleteFilters({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) - if (typeof id !== 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const filters = await deleteFilters(r, ids); - console.log('Deleted filters', filters); - return {}; - } catch (err) { - return {err: 'Unable to delete filters.'}; - } +export async function actionDeleteFilters({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id !== 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const filters = await deleteFilters(r, ids); + console.log('Deleted filters', filters); + return {}; + } catch (err) { + return { err: 'Unable to delete filters.' }; + } } diff --git a/server/modules/actions/action-get-collators.ts b/server/modules/actions/action-get-collators.ts index 8a977f9..28d9e9b 100644 --- a/server/modules/actions/action-get-collators.ts +++ b/server/modules/actions/action-get-collators.ts @@ -1,4 +1,4 @@ -import {getCollators} from "../get-collators"; +import { getCollators } from '../get-collators'; /** * Retreive one or more filter collators. @@ -7,18 +7,20 @@ import {getCollators} from "../get-collators"; * @param {object} params - request supposedly containing collator IDs * @param {object} r - connection to the RethinkDB database */ -export async function actionGetCollators({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) - if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const collators = await getCollators(r, ids); - console.log('Got collators', collators); - return {collators}; - } catch (err) { - console.error(err); - return {err: 'Unable to get collators.'}; - } +export async function actionGetCollators({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const collators = await getCollators(r, ids); + console.log('Got collators', collators); + return { collators }; + } catch (err) { + console.error(err); + return { err: 'Unable to get collators.' }; + } } diff --git a/server/modules/actions/action-get-collectors.ts b/server/modules/actions/action-get-collectors.ts index 38a56a3..14d6afc 100644 --- a/server/modules/actions/action-get-collectors.ts +++ b/server/modules/actions/action-get-collectors.ts @@ -1,4 +1,4 @@ -import {getCollectors} from '../get-collectors'; +import { getCollectors } from '../get-collectors'; /** * Retreive one or more packet collectors @@ -7,16 +7,18 @@ import {getCollectors} from '../get-collectors'; * @param {object} params - request supposedly containing collector ID list * @param {object} r - connection to the RethinkDB database */ -export async function actionGetCollectors({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) - if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const collectors = await getCollectors(r, ids); - return {collectors}; - } catch (err) { - return {err: 'Unable to get collectors.'}; - } +export async function actionGetCollectors({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const collectors = await getCollectors(r, ids); + return { collectors }; + } catch (err) { + return { err: 'Unable to get collectors.' }; + } } diff --git a/server/modules/actions/action-get-distributors.ts b/server/modules/actions/action-get-distributors.ts index 8dd85b7..e7fa1d2 100644 --- a/server/modules/actions/action-get-distributors.ts +++ b/server/modules/actions/action-get-distributors.ts @@ -1,4 +1,4 @@ -import {getDistributors} from "../get-distributors"; +import { getDistributors } from '../get-distributors'; /** * Retreive one or more packet distributors. @@ -7,16 +7,18 @@ import {getDistributors} from "../get-distributors"; * @param {object} params - request supposedly containing a list of distributor IDs * @param {object} r - connection to the RethinkDB database */ -export async function actionGetDistributors({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) - if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const distributors = await getDistributors(r, ids); - return {distributors}; - } catch (err) { - return {err: 'Unable to get distributors.'}; - } +export async function actionGetDistributors({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const distributors = await getDistributors(r, ids); + return { distributors }; + } catch (err) { + return { err: 'Unable to get distributors.' }; + } } diff --git a/server/modules/actions/action-get-filters.ts b/server/modules/actions/action-get-filters.ts index 1481833..931f185 100644 --- a/server/modules/actions/action-get-filters.ts +++ b/server/modules/actions/action-get-filters.ts @@ -1,4 +1,4 @@ -import {getFilters} from "../get-filters"; +import { getFilters } from '../get-filters'; /** * Retreive the contents of one or more packet filters. @@ -7,16 +7,18 @@ import {getFilters} from "../get-filters"; * @param {object} params - request params supposedly containing a list of filter IDs * @param {object} r - connection to the RethinkDB database */ -async function actionGetFilters({ids}, r) { - if (!Array.isArray(ids)) - return {err: "No list of IDs provided."}; - for (const id of ids) - if (typeof id != 'string' || id.length > 55) - return {err: 'Invalid (non-string) ID provided.'}; - try { - const filters = await getFilters(r, ids); - return {filters}; - } catch (err) { - return {err: 'Unable to get filters.'}; - } +async function actionGetFilters({ ids }, r) { + if (!Array.isArray(ids)) + return { err: 'No list of IDs provided.' }; + for (const id of ids) + if (typeof id != 'string' || id.length > 55) + return { + err: 'Invalid (non-string) ID provided.' + }; + try { + const filters = await getFilters(r, ids); + return { filters }; + } catch (err) { + return { err: 'Unable to get filters.' }; + } } diff --git a/server/modules/actions/action-list-collators.ts b/server/modules/actions/action-list-collators.ts index 35804cf..b7a46dd 100644 --- a/server/modules/actions/action-list-collators.ts +++ b/server/modules/actions/action-list-collators.ts @@ -1,5 +1,5 @@ -import {listCollators} from "../list-collators"; -import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; +import { listCollators } from '../list-collators'; +import { getAfterCountOrderDirection } from '../getAfterCountOrderDirection'; /** * List nonspecific filter collators. @@ -9,10 +9,12 @@ import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; * @param {object} r - connection to the RethinkDB database */ export async function actionListCollators(params, r) { - try { - const collators = await listCollators(...getAfterCountOrderDirection(r, params)); - return {collators}; - } catch (err) { - return {err: 'Unable to list collators.'}; - } + try { + const collators = await listCollators( + ...getAfterCountOrderDirection(r, params) + ); + return { collators }; + } catch (err) { + return { err: 'Unable to list collators.' }; + } } diff --git a/server/modules/actions/action-list-collectors.ts b/server/modules/actions/action-list-collectors.ts index a4fcb71..60b26d2 100644 --- a/server/modules/actions/action-list-collectors.ts +++ b/server/modules/actions/action-list-collectors.ts @@ -1,5 +1,5 @@ -import {listCollectors} from "../list-collectors"; -import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; +import { listCollectors } from '../list-collectors'; +import { getAfterCountOrderDirection } from '../getAfterCountOrderDirection'; /** * List nonspecific packet collectors. @@ -10,10 +10,12 @@ import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; */ export async function actionListCollectors(params, r) { - try { - const collectors = await listCollectors(...getAfterCountOrderDirection(r, params)); - return {collectors}; - } catch (err) { - return {err: 'Unable to list collectors.'}; - } + try { + const collectors = await listCollectors( + ...getAfterCountOrderDirection(r, params) + ); + return { collectors }; + } catch (err) { + return { err: 'Unable to list collectors.' }; + } } diff --git a/server/modules/actions/action-list-distributors.ts b/server/modules/actions/action-list-distributors.ts index ff23cb8..e4cd65b 100644 --- a/server/modules/actions/action-list-distributors.ts +++ b/server/modules/actions/action-list-distributors.ts @@ -1,6 +1,6 @@ -import {listDistributors} from "../list-distributors"; +import { listDistributors } from '../list-distributors'; -import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; +import { getAfterCountOrderDirection } from '../getAfterCountOrderDirection'; /** * List nonspecific packet distributors. @@ -10,10 +10,12 @@ import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; * @param {object} r - connection to the RethinkDB database */ export async function actionListDistributors(params, r) { - try { - const distributors = await listDistributors(...getAfterCountOrderDirection(r, params)); - return {distributors}; - } catch (err) { - return {err: 'Unable to list distributors.'}; - } + try { + const distributors = await listDistributors( + ...getAfterCountOrderDirection(r, params) + ); + return { distributors }; + } catch (err) { + return { err: 'Unable to list distributors.' }; + } } diff --git a/server/modules/actions/action-list-filter-distributors.ts b/server/modules/actions/action-list-filter-distributors.ts index 7d74546..3b97128 100644 --- a/server/modules/actions/action-list-filter-distributors.ts +++ b/server/modules/actions/action-list-filter-distributors.ts @@ -1,4 +1,4 @@ -import {buildFilterReferrerListerQuery} from "../query-builder"; +import { buildFilterReferrerListerQuery } from '../query-builder'; /** * Lists the distributors referencing one or more filters, recursively building the reference tree. @@ -7,12 +7,18 @@ import {buildFilterReferrerListerQuery} from "../query-builder"; * @param {object} params - request parameters * @param {object} r - connection to the RethinkDB database */ -export async function actionListFilterDistributors({ids}, r) { - const query = buildFilterReferrerListerQuery(Array.isArray(ids) ? ids : null, r); - try { - const filters = await query; - return {filters}; - } catch (err) { - return {err: 'Error listing filter referrers.'}; - } +export async function actionListFilterDistributors( + { ids }, + r +) { + const query = buildFilterReferrerListerQuery( + Array.isArray(ids) ? ids : null, + r + ); + try { + const filters = await query; + return { filters }; + } catch (err) { + return { err: 'Error listing filter referrers.' }; + } } diff --git a/server/modules/actions/action-list-filter-referrers.ts b/server/modules/actions/action-list-filter-referrers.ts index 8b058cb..9e2046b 100644 --- a/server/modules/actions/action-list-filter-referrers.ts +++ b/server/modules/actions/action-list-filter-referrers.ts @@ -1,4 +1,4 @@ -import {buildFilterReferrerListerQuery} from '../query-builder'; +import { buildFilterReferrerListerQuery } from '../query-builder'; /** * Lists the collators referencing one or more packet filters. * @name Action: List Filters @@ -8,12 +8,19 @@ import {buildFilterReferrerListerQuery} from '../query-builder'; * @param {object} req - Express request * @param {object} res - Express response */ -export async function actionListFilterReferrers({ids}, r) { - try { - const filters = await buildFilterReferrerListerQuery(Array.isArray(ids) ? ids : null, r); - return {filters}; - } catch (err) { - return {err: 'Error listing filter referrers.'}; - } +export async function actionListFilterReferrers( + { ids }, + r +) { + try { + const filters = + await buildFilterReferrerListerQuery( + Array.isArray(ids) ? ids : null, + r + ); + return { filters }; + } catch (err) { + return { err: 'Error listing filter referrers.' }; + } } module.exports = actionListFilterReferrers; diff --git a/server/modules/actions/action-list-filters.ts b/server/modules/actions/action-list-filters.ts index ca4e9f1..e5d6963 100644 --- a/server/modules/actions/action-list-filters.ts +++ b/server/modules/actions/action-list-filters.ts @@ -1,6 +1,6 @@ -import {getAfterCountOrderDirection} from "../getAfterCountOrderDirection"; +import { getAfterCountOrderDirection } from '../getAfterCountOrderDirection'; -import {listFilters} from "../list-filters"; +import { listFilters } from '../list-filters'; /** * List packet filters. @@ -10,10 +10,12 @@ import {listFilters} from "../list-filters"; * @param {object} r - connection to the RethinkDB database */ export async function actionListFilters(params, r) { - try { - const filters = await listFilters(...getAfterCountOrderDirection(params, r)); - return {filters}; - } catch { - return {err: 'Unable to query.'}; - } + try { + const filters = await listFilters( + ...getAfterCountOrderDirection(params, r) + ); + return { filters }; + } catch { + return { err: 'Unable to query.' }; + } } diff --git a/server/modules/actions/action-push-update.ts b/server/modules/actions/action-push-update.ts index a791da4..e9efc64 100644 --- a/server/modules/actions/action-push-update.ts +++ b/server/modules/actions/action-push-update.ts @@ -1,5 +1,5 @@ -import {validUrl} from 'valid-url'; -import {request} from "express"; +import { validUrl } from 'valid-url'; +import { request } from 'express'; /** * Push an update to a collector. @@ -10,34 +10,43 @@ import {request} from "express"; * @param {object} r - connection to the RethinkDB database */ export async function actionPushUpdate(params, r) { - const newUpdate: any = {}; - if (typeof params.accessor !== 'string') - return {err: 'No accessor specified.'}; + const newUpdate: any = {}; + if (typeof params.accessor !== 'string') + return { err: 'No accessor specified.' }; - if (['undefined', 'null'].includes(typeof params.value)) - return {err: 'No value specified.'}; - if (typeof params.id === 'string') { - newUpdate.id = params.id; - return; - } - newUpdate.accessor = params.accessor; - newUpdate.value = params.value; - //idsAndAccessors.push({id:dat.id,accessor:dat.accessor}); - //var idsExpr = r.expr(idsAndAccessors); - if (newUpdate.id) { - return await updated(await r.branch( - r.table('Collectors') - .getAll(newUpdate.accessor, {index: 'accessor'}) - .filter({aggregate: true}) - .limit(1) - .count() - .eq(1), - r.table('Collectors') - .get(newUpdate.id) - .update({value: newUpdate.value}, {return_changes: 'always'}), - {replaced: 0} - )); - /*r.table('Collectors') + if (['undefined', 'null'].includes(typeof params.value)) + return { err: 'No value specified.' }; + if (typeof params.id === 'string') { + newUpdate.id = params.id; + return; + } + newUpdate.accessor = params.accessor; + newUpdate.value = params.value; + //idsAndAccessors.push({id:dat.id,accessor:dat.accessor}); + //var idsExpr = r.expr(idsAndAccessors); + if (newUpdate.id) { + return await updated( + await r.branch( + r + .table('Collectors') + .getAll(newUpdate.accessor, { + index: 'accessor' + }) + .filter({ aggregate: true }) + .limit(1) + .count() + .eq(1), + r + .table('Collectors') + .get(newUpdate.id) + .update( + { value: newUpdate.value }, + { return_changes: 'always' } + ), + { replaced: 0 } + ) + ); + /*r.table('Collectors') .getAll(newUpdate.accessor,{index:"accessor"}) .filter({aggregate:true}) .count() @@ -47,174 +56,223 @@ export async function actionPushUpdate(params, r) { updateDocument(); } })*/ - } else { - return await updated(await r.table('Collectors') - .getAll(newUpdate.accessor, {index: "accessor"}) - .update({value: newUpdate.value}, {return_changes: 'always'}) - ); - /*r.table('Collectors') + } else { + return await updated( + await r + .table('Collectors') + .getAll(newUpdate.accessor, { + index: 'accessor' + }) + .update( + { value: newUpdate.value }, + { return_changes: 'always' } + ) + ); + /*r.table('Collectors') .getAll(newUpdate.accessor,{index:"accessor"}) .map({changes:[{new_val:r.row()}]})*/ - } + } - async function updated(updated) { - if (updated && typeof updated.changes[0].new_val == 'object') { - var nv = updated.changes[0].new_val; - const rows = await r.table('Distributors') - .without('name') - .merge(doc => ({ - collators: - r.table('Collators') - .getAll(r.args(doc('collators'))) - .pluck('id', 'filters') - .merge(doc => ({ - filters: - r.table('Filters') - .getAll(r.args(doc('filters'))) - .pluck("id", "json", "code") - .coerceTo('array') - })).coerceTo('array') - }) - ); - //if(DEBUG)console.log(err || rows) - const filters = {}; - const distributedData = []; - for (const distributor of rows) - for (const collator of distributor.collators) - for (const filter of collator.filters) - if (!filters.hasOwnProperty(filter.id)) filters[filter.id] = filter.json; - console.log(filters); - const keys = Object.keys(filters); - for (const k of keys) - if (recur(filters[k], nv, 'ROOT')) { - filters[k] = true; - } - for (const distributor of rows) - for (const collator of distributor.collators) { - let pass = false; - for (const filter of collator.filters) - if (filters[filter.id]) { - const data = JSON.parse(JSON.stringify(newUpdate)); - if (distributor.accessor) { - data.accessor = distributor.accessor; - } - if (distributor.push && !distributor.queue) - data.id = r.uuid(data.id + " " + distributor.id); - data.distributor = distributor.id; - //dostributors.push({id:distributor.id,accessor:distributor.accessor}) - distributedData.push(data); - if (distributor.callback && validUrl.isUri(distributor.url)) { - sendDataToCallback(data, distributor.url); - } else if (distributor.push) { - try { - const inserted = await r.table('DistributedData').insert(distributedData); - console.log('inserted', inserted); - } catch (err) { - console.error(err) - } - } - pass = true; - break; - } - if (pass) break; - } - console.log("PASS"); - return {}; - } - } + async function updated(updated) { + if ( + updated && + typeof updated.changes[0].new_val == 'object' + ) { + var nv = updated.changes[0].new_val; + const rows = await r + .table('Distributors') + .without('name') + .merge(doc => ({ + collators: r + .table('Collators') + .getAll(r.args(doc('collators'))) + .pluck('id', 'filters') + .merge(doc => ({ + filters: r + .table('Filters') + .getAll( + r.args(doc('filters')) + ) + .pluck('id', 'json', 'code') + .coerceTo('array') + })) + .coerceTo('array') + })); + //if(DEBUG)console.log(err || rows) + const filters = {}; + const distributedData = []; + for (const distributor of rows) + for (const collator of distributor.collators) + for (const filter of collator.filters) + if ( + !filters.hasOwnProperty( + filter.id + ) + ) + filters[filter.id] = + filter.json; + console.log(filters); + const keys = Object.keys(filters); + for (const k of keys) + if (recur(filters[k], nv, 'ROOT')) { + filters[k] = true; + } + for (const distributor of rows) + for (const collator of distributor.collators) { + let pass = false; + for (const filter of collator.filters) + if (filters[filter.id]) { + const data = JSON.parse( + JSON.stringify(newUpdate) + ); + if (distributor.accessor) { + data.accessor = + distributor.accessor; + } + if ( + distributor.push && + !distributor.queue + ) + data.id = r.uuid( + data.id + + ' ' + + distributor.id + ); + data.distributor = + distributor.id; + //dostributors.push({id:distributor.id,accessor:distributor.accessor}) + distributedData.push(data); + if ( + distributor.callback && + validUrl.isUri( + distributor.url + ) + ) { + sendDataToCallback( + data, + distributor.url + ); + } else if (distributor.push) { + try { + const inserted = await r + .table( + 'DistributedData' + ) + .insert( + distributedData + ); + console.log( + 'inserted', + inserted + ); + } catch (err) { + console.error(err); + } + } + pass = true; + break; + } + if (pass) break; + } + console.log('PASS'); + return {}; + } + } - /*r.table('Collectors').filter(collector=>{ + /*r.table('Collectors').filter(collector=>{ //if(collector('accessor').eq()) })*/ } async function sendDataToCallback(data, url) { - if (!url.match(/^[A-Za-z]+:\/\//)) url = "http://" + url; - await request.post({ - headers: {'content-type': 'application/json'}, - url: url, - body: data, - json: true - }); + if (!url.match(/^[A-Za-z]+:\/\//)) + url = 'http://' + url; + await request.post({ + headers: { 'content-type': 'application/json' }, + url: url, + body: data, + json: true + }); } function recur(root, update, gate) { - //if(DEBUG)console.log(gate) - const left = evaluateProperty(root, update, 0), - right = evaluateProperty(root, update, 1); - let res = false; - switch (gate) { - case 'ROOT': - res = !!left; - break; - case 'AND': - res = left && right; - break; - case 'OR': - res = left || right; - break; - case 'NAND': - res = !(left && right); - break; - case 'NOR': - res = !(left || right); - break; - case 'XOR': - res = (left || right) && !(left && right); - break; + //if(DEBUG)console.log(gate) + const left = evaluateProperty(root, update, 0), + right = evaluateProperty(root, update, 1); + let res = false; + switch (gate) { + case 'ROOT': + res = !!left; + break; + case 'AND': + res = left && right; + break; + case 'OR': + res = left || right; + break; + case 'NAND': + res = !(left && right); + break; + case 'NOR': + res = !(left || right); + break; + case 'XOR': + res = (left || right) && !(left && right); + break; - case 'UNDER': - res = left < right; - break; - case 'OVER': - res = left > right; - break; - case 'EQUALS': - res = left == right; - break; - case 'TFEQUALS': - res = left === right; - break; - case 'NEQUALS': - res = left != right; - break; - case 'TFNEQUALS': - res = left !== right; - break; - case 'OVEROR': - res = left >= right; - break; - case 'UNDEROR': - res = left <= right; - break; - } - console.log(root, left, right, gate, res) - return res; + case 'UNDER': + res = left < right; + break; + case 'OVER': + res = left > right; + break; + case 'EQUALS': + res = left == right; + break; + case 'TFEQUALS': + res = left === right; + break; + case 'NEQUALS': + res = left != right; + break; + case 'TFNEQUALS': + res = left !== right; + break; + case 'OVEROR': + res = left >= right; + break; + case 'UNDEROR': + res = left <= right; + break; + } + console.log(root, left, right, gate, res); + return res; } function getProperty(object, key) { - for (const k of key.substring(1).split('.')) { - const sub = object[k]; - console.log(k, sub) - if (['undefined', 'sub'].includes(typeof sub)) object = sub; - else return null; - } - console.log('PROP', object) - return object; + for (const k of key.substring(1).split('.')) { + const sub = object[k]; + console.log(k, sub); + if (['undefined', 'sub'].includes(typeof sub)) + object = sub; + else return null; + } + console.log('PROP', object); + return object; } function evaluateProperty(object, update, child) { - const keys = Object.keys(object); - const key = keys[child]; - let side = object[key]; - switch (typeof side) { - case 'object': - side = recur(side, update, key); - break; - case 'string': - if (side[0] === "$") - side = getProperty(update, side); - break; - } - return side; + const keys = Object.keys(object); + const key = keys[child]; + let side = object[key]; + switch (typeof side) { + case 'object': + side = recur(side, update, key); + break; + case 'string': + if (side[0] === '$') + side = getProperty(update, side); + break; + } + return side; } diff --git a/server/modules/actions/action-push-updates.ts b/server/modules/actions/action-push-updates.ts index 1b2bf0d..fbebbc5 100644 --- a/server/modules/actions/action-push-updates.ts +++ b/server/modules/actions/action-push-updates.ts @@ -1,5 +1,5 @@ /* THIS FUNCTION IS INCOMPLETE AND NOT READY FOR PRODUCTION */ -import {actionPushUpdate} from "./action-push-update"; +import { actionPushUpdate } from './action-push-update'; /** * Push multiple update simultaneously for batch processing. Currently not fully implemented. @@ -9,7 +9,11 @@ import {actionPushUpdate} from "./action-push-update"; * @param {object} r - connection to the RethinkDB database */ export function actionPushUpdates(params, r) { - if (!Array.isArray(params.updates)) - return {err: 'No updates specified.'}; - return Promise.allSettled(params.updates.map(update => actionPushUpdate(update, r))) + if (!Array.isArray(params.updates)) + return { err: 'No updates specified.' }; + return Promise.allSettled( + params.updates.map(update => + actionPushUpdate(update, r) + ) + ); } diff --git a/server/modules/delete-collators.ts b/server/modules/delete-collators.ts index fd230db..69254b0 100644 --- a/server/modules/delete-collators.ts +++ b/server/modules/delete-collators.ts @@ -1,4 +1,3 @@ - /** * Delete one or more filter collators. * @name Database: Delete Collators @@ -7,6 +6,9 @@ * @param {array} collators - List of collator IDs to delete */ export const deleteCollators = (r, collators) => - r.table('Collators') - .filter(doc=>{return r.expr(collators).contains(doc('id'))}) - .delete(); + r + .table('Collators') + .filter(doc => { + return r.expr(collators).contains(doc('id')); + }) + .delete(); diff --git a/server/modules/delete-collectors.ts b/server/modules/delete-collectors.ts index 73d4c58..3197f66 100644 --- a/server/modules/delete-collectors.ts +++ b/server/modules/delete-collectors.ts @@ -6,6 +6,9 @@ * @param {array} collectors - List of collector IDs to delete */ export const deleteCollectors = (r, collectors) => - r.table('Collectors') - .filter(doc => r.expr(collectors).contains(doc('id'))) - .delete(); + r + .table('Collectors') + .filter(doc => + r.expr(collectors).contains(doc('id')) + ) + .delete(); diff --git a/server/modules/delete-distributors.ts b/server/modules/delete-distributors.ts index 8f3e9b4..ceb99ee 100644 --- a/server/modules/delete-distributors.ts +++ b/server/modules/delete-distributors.ts @@ -6,6 +6,9 @@ * @param {array} distributors - List of distributor IDs to delete */ export const deleteDistributors = (r, distributors) => - r.table('Distributors') - .filter(doc=>{return r.expr(distributors).contains(doc('id'))}) - .delete(); + r + .table('Distributors') + .filter(doc => { + return r.expr(distributors).contains(doc('id')); + }) + .delete(); diff --git a/server/modules/delete-filters.ts b/server/modules/delete-filters.ts index e3ce498..7d30061 100644 --- a/server/modules/delete-filters.ts +++ b/server/modules/delete-filters.ts @@ -6,8 +6,9 @@ * @param {array} filters - List of filter IDs to delete */ export const deleteFilters = (r, filters) => - r.table('Filters') - .filter(doc => { - return r.expr(filters).contains(doc('id')) - }) - .delete(); + r + .table('Filters') + .filter(doc => { + return r.expr(filters).contains(doc('id')); + }) + .delete(); diff --git a/server/modules/get-collators.ts b/server/modules/get-collators.ts index 98be0e6..c9faa92 100644 --- a/server/modules/get-collators.ts +++ b/server/modules/get-collators.ts @@ -6,10 +6,15 @@ * @param {array} collators - List of collators to retrieve */ export const getCollators = (r, collators) => - r.table('Collators') - .filter(doc => r.expr(collators).contains(doc('id'))) - .merge(doc => ({ - filtrets: r.table('Filters') - .getAll(r.args(doc('filters'))).coerceTo('array') - })) - .coerceTo('array'); + r + .table('Collators') + .filter(doc => + r.expr(collators).contains(doc('id')) + ) + .merge(doc => ({ + filtrets: r + .table('Filters') + .getAll(r.args(doc('filters'))) + .coerceTo('array') + })) + .coerceTo('array'); diff --git a/server/modules/get-collectors.ts b/server/modules/get-collectors.ts index c01203d..d4ff599 100644 --- a/server/modules/get-collectors.ts +++ b/server/modules/get-collectors.ts @@ -6,5 +6,6 @@ * @param {array} collectors - List of collectors to retrieve */ export const getCollectors = async (r, collectors) => - r.table('Collectors') - .filter(doc=>{return r.expr(collectors).contains(doc('id'))}); + r.table('Collectors').filter(doc => { + return r.expr(collectors).contains(doc('id')); + }); diff --git a/server/modules/get-distributors.ts b/server/modules/get-distributors.ts index fc98e1e..e7fe326 100644 --- a/server/modules/get-distributors.ts +++ b/server/modules/get-distributors.ts @@ -6,18 +6,20 @@ * @param {array} distributors - List of distributors to retrieve */ export const getDistributors = (r, distributors) => - r.table('Distributors') - .filter(doc => { - return r.expr(distributors).contains(doc('id')) - }) - .merge(doc => ({ - collators: - r.table('Collators') - .getAll(r.args(doc('collators'))) - .merge(doc => ({ - filters: - r.table('Filters') - .getAll(r.args(doc('filters'))) - .coerceTo('array') - })).coerceTo('array') - })); \ No newline at end of file + r + .table('Distributors') + .filter(doc => { + return r.expr(distributors).contains(doc('id')); + }) + .merge(doc => ({ + collators: r + .table('Collators') + .getAll(r.args(doc('collators'))) + .merge(doc => ({ + filters: r + .table('Filters') + .getAll(r.args(doc('filters'))) + .coerceTo('array') + })) + .coerceTo('array') + })); diff --git a/server/modules/get-filters.ts b/server/modules/get-filters.ts index e99d3eb..431fcc4 100644 --- a/server/modules/get-filters.ts +++ b/server/modules/get-filters.ts @@ -7,8 +7,7 @@ * @param {function} callback - Function(error, result) to execute upon success or error */ - - export const getFilters = async (r, filters) => - r.table('Filters') - .filter(doc => r.expr(filters).contains(doc('id'))); + r + .table('Filters') + .filter(doc => r.expr(filters).contains(doc('id'))); diff --git a/server/modules/insert-distributors.ts b/server/modules/insert-distributors.ts index f3eff14..d40d512 100644 --- a/server/modules/insert-distributors.ts +++ b/server/modules/insert-distributors.ts @@ -1,4 +1,3 @@ - /** * Inserts one or more packet distributors. * @name Database: Insert Distributors @@ -7,4 +6,6 @@ * @param {array} distributors - List of distributors to insert */ export const insertDistributors = (r, distributors) => - r.table('Distributors').insert(distributors, { conflict: 'replace' }); + r + .table('Distributors') + .insert(distributors, { conflict: 'replace' }); diff --git a/server/modules/insert-filters.ts b/server/modules/insert-filters.ts index 280bbfa..e8c72b2 100644 --- a/server/modules/insert-filters.ts +++ b/server/modules/insert-filters.ts @@ -6,5 +6,6 @@ * @param {array} filters - List of filters to insert */ export const insertFilters = (r, filters) => - r.table('Filters').insert(filters, {conflict: 'replace'}) - + r + .table('Filters') + .insert(filters, { conflict: 'replace' }); diff --git a/server/modules/list-collators.ts b/server/modules/list-collators.ts index fd4bdbc..a88f7a7 100644 --- a/server/modules/list-collators.ts +++ b/server/modules/list-collators.ts @@ -8,14 +8,23 @@ * @param {string|object} order - key or method for sorting */ -export const listCollators = async (r, after, count, order) => { - const total = await r.table('Collators').count(); - if (after < 0) - after += total; - after = Math.max(0, after); - return await r.table('Collators') - .orderBy(order) - .slice(after, after + count).merge(doc => ({ - filtrets: r.table('Filters').getAll(r.args(doc('filters'))).coerceTo('array') - })); -} +export const listCollators = async ( + r, + after, + count, + order +) => { + const total = await r.table('Collators').count(); + if (after < 0) after += total; + after = Math.max(0, after); + return await r + .table('Collators') + .orderBy(order) + .slice(after, after + count) + .merge(doc => ({ + filtrets: r + .table('Filters') + .getAll(r.args(doc('filters'))) + .coerceTo('array') + })); +}; diff --git a/server/modules/list-collectors.ts b/server/modules/list-collectors.ts index 3101b73..cb164ac 100644 --- a/server/modules/list-collectors.ts +++ b/server/modules/list-collectors.ts @@ -7,11 +7,17 @@ * @param {number} count - number of collectors to return * @param {string|object} order - key or method for sorting */ -export const listCollectors = async (r, after, count, order) => { - const total = await r.table('Collectors').count(); - if (after < 0) after += total; - after = Math.max(0, after); - return await r.table('Collectors') - .orderBy(order) - .slice(after, after + count); -} +export const listCollectors = async ( + r, + after, + count, + order +) => { + const total = await r.table('Collectors').count(); + if (after < 0) after += total; + after = Math.max(0, after); + return await r + .table('Collectors') + .orderBy(order) + .slice(after, after + count); +}; diff --git a/server/modules/list-distributors.ts b/server/modules/list-distributors.ts index 516a9f5..e7cff14 100644 --- a/server/modules/list-distributors.ts +++ b/server/modules/list-distributors.ts @@ -7,16 +7,29 @@ * @param {number} count - number of distributors to return * @param {string|object} order - key or method for sorting */ -export const listDistributors = async (r, after, count, order) => { - const total = await r.table('Distributors').count(); - if (after < 0) after += total; - after = Math.max(0, after); - return await r.table('Distributors') - .orderBy(order) - .slice(after, after + count).merge(doc => ({ - collets: r.table('Collators').getAll(r.args(doc('collators'))) - .merge(doc => ({ - filtrets: r.table('Filters').getAll(r.args(doc('filters'))).coerceTo('array') - })).coerceTo('array') - })) -} +export const listDistributors = async ( + r, + after, + count, + order +) => { + const total = await r.table('Distributors').count(); + if (after < 0) after += total; + after = Math.max(0, after); + return await r + .table('Distributors') + .orderBy(order) + .slice(after, after + count) + .merge(doc => ({ + collets: r + .table('Collators') + .getAll(r.args(doc('collators'))) + .merge(doc => ({ + filtrets: r + .table('Filters') + .getAll(r.args(doc('filters'))) + .coerceTo('array') + })) + .coerceTo('array') + })); +}; diff --git a/server/modules/list-filters.ts b/server/modules/list-filters.ts index c5b37b5..0a800a7 100644 --- a/server/modules/list-filters.ts +++ b/server/modules/list-filters.ts @@ -7,12 +7,18 @@ * @param {number} count - number of filters to return * @param {string|object} order - key or method for sorting */ -export const listFilters = async (r, after, count, order) => { - const total = await r.table('Filters').count(); - if (after < 0) after += total; - after = Math.max(0, after); - return await r.table('Filters') - .orderBy(order) - .slice(after, after + count) - .coerceTo('array') -} +export const listFilters = async ( + r, + after, + count, + order +) => { + const total = await r.table('Filters').count(); + if (after < 0) after += total; + after = Math.max(0, after); + return await r + .table('Filters') + .orderBy(order) + .slice(after, after + count) + .coerceTo('array'); +}; diff --git a/server/modules/query-builder.ts b/server/modules/query-builder.ts index c71c1dc..1a4b07f 100644 --- a/server/modules/query-builder.ts +++ b/server/modules/query-builder.ts @@ -8,19 +8,25 @@ * @returns {object} - RethinkDB query for retrieving the reference count */ export function buildFilterReferenceCounterQuery(ids, r) { - let query = r.table('Filters'); - if (Array.isArray(ids)) - query = query.filter(d => { - return r.expr(ids).contains(d('id')) - }); - query = query.map(filt => ({ - id: filt('id'), - refcount: r.table("Collators").group('id')('filters')(0).contains(filt('id')).ungroup()('reduction').filter(r => { - return r.eq(true) - }).count() - })) - //query = query.filter(isReferencedFilter); - return query; + let query = r.table('Filters'); + if (Array.isArray(ids)) + query = query.filter(d => { + return r.expr(ids).contains(d('id')); + }); + query = query.map(filt => ({ + id: filt('id'), + refcount: r + .table('Collators') + .group('id')('filters')(0) + .contains(filt('id')) + .ungroup()('reduction') + .filter(r => { + return r.eq(true); + }) + .count() + })); + //query = query.filter(isReferencedFilter); + return query; } /** @@ -32,20 +38,24 @@ export function buildFilterReferenceCounterQuery(ids, r) { * @returns {object} - RethinkDB query for retreiving the reference count */ export function buildCollatorReferenceCounterQuery(ids, r) { - let query = r.table('Collators'); - if (Array.isArray(ids)) - query = query.filter(d => r.expr(ids).contains(d('id'))); - query = query.map(filt => ({ - id: filt('id'), - refcount: r.table("Distributors") - .group('id')('collators')(0) - .contains(filt('id')) - .ungroup()('reduction') - .filter(r => { - return r.eq(true) - }).count() - })) - return query; + let query = r.table('Collators'); + if (Array.isArray(ids)) + query = query.filter(d => + r.expr(ids).contains(d('id')) + ); + query = query.map(filt => ({ + id: filt('id'), + refcount: r + .table('Distributors') + .group('id')('collators')(0) + .contains(filt('id')) + .ungroup()('reduction') + .filter(r => { + return r.eq(true); + }) + .count() + })); + return query; } /** @@ -57,21 +67,29 @@ export function buildCollatorReferenceCounterQuery(ids, r) { * @returns {object} - RethinkDB query for retreiving the reference list */ export function buildFilterReferrerListerQuery(ids, r) { - let query = r.table('Filters'); - if (Array.isArray(ids)) - query = query.filter(d => r.expr(ids).contains(d('id'))); - query = query.map(filt => ({ - id: filt('id'), - referrers: r.db('LiotR') - .table("Collators") - .filter(col => { - return col('filters') - .contains(filt('id')) - }).merge(doc => { - return {filtrets: r.table('Filters').getAll(r.args(doc('filters'))).coerceTo('array')} - }) - })) - return query; + let query = r.table('Filters'); + if (Array.isArray(ids)) + query = query.filter(d => + r.expr(ids).contains(d('id')) + ); + query = query.map(filt => ({ + id: filt('id'), + referrers: r + .db('LiotR') + .table('Collators') + .filter(col => { + return col('filters').contains(filt('id')); + }) + .merge(doc => { + return { + filtrets: r + .table('Filters') + .getAll(r.args(doc('filters'))) + .coerceTo('array') + }; + }) + })); + return query; } /** @@ -83,19 +101,27 @@ export function buildFilterReferrerListerQuery(ids, r) { * @returns {object} - RethinkDB query for retreiving the reference list */ export function buildFilterDistributorListerQuery(ids, r) { - let query = r.table('Filters'); - if (Array.isArray(ids)) - query = query.filter(d => r.expr(ids).contains(d('id'))); - query = query.map(filt => ({ - id: filt('id'), - referrers: r.db('LiotR') - .table("Collators") - .filter(col => { - return col('filters') - .contains(filt('id')) - }).merge(doc => { - return {filtrets: r.table('Filters').getAll(r.args(doc('filters'))).coerceTo('array')} - }) - })) - return query; + let query = r.table('Filters'); + if (Array.isArray(ids)) + query = query.filter(d => + r.expr(ids).contains(d('id')) + ); + query = query.map(filt => ({ + id: filt('id'), + referrers: r + .db('LiotR') + .table('Collators') + .filter(col => { + return col('filters').contains(filt('id')); + }) + .merge(doc => { + return { + filtrets: r + .table('Filters') + .getAll(r.args(doc('filters'))) + .coerceTo('array') + }; + }) + })); + return query; } diff --git a/server/modules/sortify.ts b/server/modules/sortify.ts index d3f9555..9ccefdc 100644 --- a/server/modules/sortify.ts +++ b/server/modules/sortify.ts @@ -6,21 +6,20 @@ * @returns {number} - index value of the provided text */ export function sortify(text: string) { - const reg = /([A-Za-z]+|[0-9]+|.+?)/g; - const regontxt = text.match(reg); - if (!regontxt) - return 0; - let score = 0; - for (const match of regontxt) { - if (match.match(/^[A-Za-z]+$/)) { - for (let l = 0; l < match.length; l++) - score += match.charCodeAt(l); - } else if (match.match(/^[0-9]+$/)) { - score += parseInt(match); - } else { - for (let l = 0; l < match.length; l++) - score += match.charCodeAt(l); - } - } - return score; + const reg = /([A-Za-z]+|[0-9]+|.+?)/g; + const regontxt = text.match(reg); + if (!regontxt) return 0; + let score = 0; + for (const match of regontxt) { + if (match.match(/^[A-Za-z]+$/)) { + for (let l = 0; l < match.length; l++) + score += match.charCodeAt(l); + } else if (match.match(/^[0-9]+$/)) { + score += parseInt(match); + } else { + for (let l = 0; l < match.length; l++) + score += match.charCodeAt(l); + } + } + return score; } diff --git a/weave/unwoven-site/bonus.js b/weave/unwoven-site/bonus.js index 69da30e..490bc95 100644 --- a/weave/unwoven-site/bonus.js +++ b/weave/unwoven-site/bonus.js @@ -2,106 +2,202 @@ /* check if param is string or element. if string, get element of that id */ /* e.g. grab('myelem') or grab(myelem) */ -function grab(elem){if(typeof elem==='string'){var o=[];elem.split('|').forEach(x=>o.push(document.getElementById(x)));return o.length==1?o[0]:o}return elem} +function grab(elem) { + if (typeof elem === 'string') { + var o = []; + elem.split('|').forEach(x => + o.push(document.getElementById(x)) + ); + return o.length == 1 ? o[0] : o; + } + return elem; +} /* add an event listener to an element. if element is string, grab() it. */ /* e.g. bind(myelem, 'click', ()=>{}) */ -function bind(elem,evt,func){iterate(grab(elem),(x)=>{x.addEventListener(evt, func);if(!bind.bound[x])bind.bound[x]=[];bind.bound[x].push(func)})} +function bind(elem, evt, func) { + iterate(grab(elem), x => { + x.addEventListener(evt, func); + if (!bind.bound[x]) bind.bound[x] = []; + bind.bound[x].push(func); + }); +} bind.bound = {}; /* run function when window is loaded. uses event listener, not window.onload = */ /* e.g. load(()=>{}) */ -function load(func){iterate(func,(x)=>{bind(window,'load',x)})} +function load(func) { + iterate(func, x => { + bind(window, 'load', x); + }); +} /* output text to grab('log') element */ /* e.g. log('oops') */ -function log(text){grab('log').innerHTML=text} +function log(text) { + grab('log').innerHTML = text; +} /* remove class from element */ /* e.g. remc(myelem) or remc('myelem') */ -function remc(elem,clas){iterate(grab(elem),(x)=>{x.classList.remove(clas)})} +function remc(elem, clas) { + iterate(grab(elem), x => { + x.classList.remove(clas); + }); +} /* add class to element */ /* e.g. addc(myelem, 'hidden') or addc('myelem', 'myclass') */ -function addc(elem,clas){iterate(grab(elem),(x)=>{x.classList.add(clas)})} +function addc(elem, clas) { + iterate(grab(elem), x => { + x.classList.add(clas); + }); +} /*check if element has class */ /* e.g. x = hasc(myelem, 'myclass') or x = hasc('myelem', 'myclass') */ -function hasc(elem,clas){return grab(elem).classList.contains(clas)} +function hasc(elem, clas) { + return grab(elem).classList.contains(clas); +} /* toggle class of element, returns if element now has class */ /* e.g. x = togc(myelem, 'myclass') or x = togc('myelem', 'myclass') */ -function togc(elem,clas){var e=grab(elem);var hc=hasc(e,clas);if(hc)remc(e,clas);else addc(e,clas);return !hc} +function togc(elem, clas) { + var e = grab(elem); + var hc = hasc(e, clas); + if (hc) remc(e, clas); + else addc(e, clas); + return !hc; +} -function togcp(elem,clas){iterate(grab(elem),(e)=>{var hc=hasc(e,clas);if(hc)remc(e,clas);else addc(e,clas)})}//togc plus +function togcp(elem, clas) { + iterate(grab(elem), e => { + var hc = hasc(e, clas); + if (hc) remc(e, clas); + else addc(e, clas); + }); +} //togc plus /* set whether element has class */ /* e.g. setc(myelem, 'myclass', true) or setc('myelem', 'myclass', 0) */ -function setc(elem,clas,to){iterate(grab(elem),(e)=>{if(to)addc(e,clas);else remc(e,clas)})} +function setc(elem, clas, to) { + iterate(grab(elem), e => { + if (to) addc(e, clas); + else remc(e, clas); + }); +} -function iterate(elems, func){if(Array.isArray(elems))elems.forEach(func);else func(elems)} +function iterate(elems, func) { + if (Array.isArray(elems)) elems.forEach(func); + else func(elems); +} -function retrieve(path, callback){var e=new XMLHttpRequest();e.open("GET",path);bind(e,'load',()=>{callback(e)});return e} +function retrieve(path, callback) { + var e = new XMLHttpRequest(); + e.open('GET', path); + bind(e, 'load', () => { + callback(e); + }); + return e; +} /* end of freely stealable code */ function pang(path, callback) { var x = new XMLHttpRequest(); - x.open('GET', imgroot + "pangpacks/" + "frames.pangpack"); - bind(x, 'load', () => { - callback(x.response.split("|")); - //alert('done'); - }) - x.send(); - return x; + x.open( + 'GET', + imgroot + 'pangpacks/' + 'frames.pangpack' + ); + bind(x, 'load', () => { + callback(x.response.split('|')); + //alert('done'); + }); + x.send(); + return x; } -if(typeof BS == 'undefined'){ - BS = (zone) => { - - var addClass=(e,c)=>{e.classList.add(c)} - var remClass=(e,c)=>{e.classList.remove(c)} - var setClass=(e,c,v)=>{if(v)addClass(e,c);else remClass(e,c)} - var place = (zone || document).getElementsByClassName('bs-textbox'); -for(var bi = 0; bi < place.length; bi ++) { - var box = place[bi]; - bindbox(box); - - function bindbox(box) { - var correct = box.getAttribute('bs-correct'); - var incorrect = box.getAttribute('bs-incorrect'); - var empty = box.getAttribute('bs-empty'); - //var regex = box.getAttribute('bigbox-regex'); - box.children[1].innerHTML = empty; - box.addEventListener('input', ()=>{dotype(box, box.children[0],box.children[1],correct,incorrect,empty)}); +if (typeof BS == 'undefined') { + BS = zone => { + var addClass = (e, c) => { + e.classList.add(c); + }; + var remClass = (e, c) => { + e.classList.remove(c); + }; + var setClass = (e, c, v) => { + if (v) addClass(e, c); + else remClass(e, c); + }; + var place = ( + zone || document + ).getElementsByClassName('bs-textbox'); + for (var bi = 0; bi < place.length; bi++) { + var box = place[bi]; + bindbox(box); + + function bindbox(box) { + var correct = + box.getAttribute('bs-correct'); + var incorrect = + box.getAttribute('bs-incorrect'); + var empty = box.getAttribute('bs-empty'); + //var regex = box.getAttribute('bigbox-regex'); + box.children[1].innerHTML = empty; + box.addEventListener('input', () => { + dotype( + box, + box.children[0], + box.children[1], + correct, + incorrect, + empty + ); + }); box.addEventListener('mousedown', () => { - setTimeout(()=>{box.children[0].focus()},0); - }) - } - } - function dotype(box, inb, lab, correct, incorrect, empty) { - var good = false; - var inp=inb.value - setClass(box,'occupied',inp.length); - var reg = getRegex(box); - if(!inp.length)lab.innerHTML=empty; - else if(reg.test(inp)){good=true;lab.innerHTML=correct;} - else lab.innerHTML = incorrect; - inb.setAttribute('bs-valid', good); - } -} + setTimeout(() => { + box.children[0].focus(); + }, 0); + }); + } + } + function dotype( + box, + inb, + lab, + correct, + incorrect, + empty + ) { + var good = false; + var inp = inb.value; + setClass(box, 'occupied', inp.length); + var reg = getRegex(box); + if (!inp.length) lab.innerHTML = empty; + else if (reg.test(inp)) { + good = true; + lab.innerHTML = correct; + } else lab.innerHTML = incorrect; + inb.setAttribute('bs-valid', good); + } + }; function getRegex(box) { - regex=box.getAttribute('bs-regex'); - var end = regex.lastIndexOf('/'); - var reg = new RegExp(regex.substring(1,end), regex.substr(end+1)); - return reg; + regex = box.getAttribute('bs-regex'); + var end = regex.lastIndexOf('/'); + var reg = new RegExp( + regex.substring(1, end), + regex.substr(end + 1) + ); + return reg; } - BS.check = (box) => { + BS.check = box => { return box.getAttribute('bs-valid') == 'true'; - } + }; -load(()=>{BS()}) + load(() => { + BS(); + }); } diff --git a/weave/unwoven-site/bonus.min.js b/weave/unwoven-site/bonus.min.js index fc7dc47..cc813cb 100644 --- a/weave/unwoven-site/bonus.min.js +++ b/weave/unwoven-site/bonus.min.js @@ -1,5 +1,127 @@ -function grab(a){if("string"===typeof a){var b=[];a.split("|").forEach(function(c){return b.push(document.getElementById(c))});return 1==b.length?b[0]:b}return a}function bind(a,b,c){iterate(grab(a),function(a){a.addEventListener(b,c);bind.bound[a]||(bind.bound[a]=[]);bind.bound[a].push(c)})}bind.bound={};function load(a){iterate(a,function(a){bind(window,"load",a)})}function log(a){grab("log").innerHTML=a}function remc(a,b){iterate(grab(a),function(a){a.classList.remove(b)})} -function addc(a,b){iterate(grab(a),function(a){a.classList.add(b)})}function hasc(a,b){return grab(a).classList.contains(b)}function togc(a,b){var c=grab(a),d=hasc(c,b);d?remc(c,b):addc(c,b);return!d}function togcp(a,b){iterate(grab(a),function(a){hasc(a,b)?remc(a,b):addc(a,b)})}function setc(a,b,c){iterate(grab(a),function(a){c?addc(a,b):remc(a,b)})}function iterate(a,b){Array.isArray(a)?a.forEach(b):b(a)} -function retrieve(a,b){var c=new XMLHttpRequest;c.open("GET",a);bind(c,"load",function(){b(c)});return c}function pang(a,b){var c=new XMLHttpRequest;c.open("GET",imgroot+"pangpacks/frames.pangpack");bind(c,"load",function(){b(c.response.split("|"))});c.send();return c} -if("undefined"==typeof BS){var getRegex=function(a){regex=a.getAttribute("bs-regex");a=regex.lastIndexOf("/");return new RegExp(regex.substring(1,a),regex.substr(a+1))};BS=function(a){a=(a||document).getElementsByClassName("bs-textbox");for(var b=0;b)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); +PR.registerLangHandler( + PR.createSimpleLexer( + [['pln', /^[\t\n\f\r ]+/, null, ' \t\r\n ']], + [ + [ + 'str', + /^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/, + null + ], + [ + 'str', + /^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/, + null + ], + ['lang-css-str', /^url\(([^"')]*)\)/i], + [ + 'kwd', + /^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i, + null + ], + [ + 'lang-css-kw', + /^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i + ], + ['com', /^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//], + ['com', /^(?:<\!--|--\>)/], + ['lit', /^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i], + ['lit', /^#[\da-f]{3,6}/i], + [ + 'pln', + /^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i + ], + ['pun', /^[^\s\w"']+/] + ] + ), + ['css'] +); +PR.registerLangHandler( + PR.createSimpleLexer( + [], + [ + [ + 'kwd', + /^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i + ] + ] + ), + ['css-kw'] +); +PR.registerLangHandler( + PR.createSimpleLexer([], [['str', /^[^"')]+/]]), + ['css-str'] +); diff --git a/weave/unwoven-site/docs/scripts/prettify/prettify.js b/weave/unwoven-site/docs/scripts/prettify/prettify.js index eef5ad7..f34477a 100644 --- a/weave/unwoven-site/docs/scripts/prettify/prettify.js +++ b/weave/unwoven-site/docs/scripts/prettify/prettify.js @@ -1,28 +1,934 @@ -var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; -(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= -[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), -l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, -q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, -q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, -"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), -a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} -for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], -"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], -H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], -J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ -I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), -["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", -/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), -["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", -hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= -!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p 122 || + (d < 65 || + j > 90 || + b.push([ + Math.max(65, j) | 32, + Math.min(d, 90) | 32 + ]), + d < 97 || + j > 122 || + b.push([ + Math.max(97, j) & -33, + Math.min(d, 122) & -33 + ])); + } + } + b.sort(function (a, f) { + return a[0] - f[0] || f[1] - a[1]; + }); + f = []; + j = [NaN, NaN]; + for (c = 0; c < b.length; ++c) + (i = b[c]), + i[0] <= j[1] + 1 + ? (j[1] = Math.max(j[1], i[1])) + : f.push((j = i)); + b = ['[']; + o && b.push('^'); + b.push.apply(b, a); + for (c = 0; c < f.length; ++c) + (i = f[c]), + b.push(e(i[0])), + i[1] > i[0] && + (i[1] + 1 > i[0] && b.push('-'), + b.push(e(i[1]))); + b.push(']'); + return b.join(''); + } + function y(a) { + for ( + var f = a.source.match( + /\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g + ), + b = f.length, + d = [], + c = 0, + i = 0; + c < b; + ++c + ) { + var j = f[c]; + j === '(' + ? ++i + : '\\' === j.charAt(0) && + (j = +j.substring(1)) && + j <= i && + (d[j] = -1); + } + for (c = 1; c < d.length; ++c) + -1 === d[c] && (d[c] = ++t); + for (i = c = 0; c < b; ++c) + (j = f[c]), + j === '(' + ? (++i, + d[i] === void 0 && (f[c] = '(?:')) + : '\\' === j.charAt(0) && + (j = +j.substring(1)) && + j <= i && + (f[c] = '\\' + d[i]); + for (i = c = 0; c < b; ++c) + '^' === f[c] && + '^' !== f[c + 1] && + (f[c] = ''); + if (a.ignoreCase && s) + for (c = 0; c < b; ++c) + (j = f[c]), + (a = j.charAt(0)), + j.length >= 2 && a === '[' + ? (f[c] = h(j)) + : a !== '\\' && + (f[c] = j.replace( + /[A-Za-z]/g, + function (a) { + a = a.charCodeAt(0); + return ( + '[' + + String.fromCharCode( + a & -33, + a | 32 + ) + + ']' + ); + } + )); + return f.join(''); + } + for ( + var t = 0, s = !1, l = !1, p = 0, d = a.length; + p < d; + ++p + ) { + var g = a[p]; + if (g.ignoreCase) l = !0; + else if ( + /[a-z]/i.test( + g.source.replace( + /\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi, + '' + ) + ) + ) { + s = !0; + l = !1; + break; + } + } + for ( + var r = { + b: 8, + t: 9, + n: 10, + v: 11, + f: 12, + r: 13 + }, + n = [], + p = 0, + d = a.length; + p < d; + ++p + ) { + g = a[p]; + if (g.global || g.multiline) + throw Error('' + g); + n.push('(?:' + y(g) + ')'); + } + return RegExp(n.join('|'), l ? 'gi' : 'g'); + } + function M(a) { + function m(a) { + switch (a.nodeType) { + case 1: + if (e.test(a.className)) break; + for ( + var g = a.firstChild; + g; + g = g.nextSibling + ) + m(g); + g = a.nodeName; + if ('BR' === g || 'LI' === g) + (h[s] = '\n'), + (t[s << 1] = y++), + (t[(s++ << 1) | 1] = a); + break; + case 3: + case 4: + (g = a.nodeValue), + g.length && + ((g = p + ? g.replace(/\r\n?/g, '\n') + : g.replace( + /[\t\n\r ]+/g, + ' ' + )), + (h[s] = g), + (t[s << 1] = y), + (y += g.length), + (t[(s++ << 1) | 1] = a)); + } + } + var e = /(?:^|\s)nocode(?:\s|$)/, + h = [], + y = 0, + t = [], + s = 0, + l; + a.currentStyle + ? (l = a.currentStyle.whiteSpace) + : window.getComputedStyle && + (l = document.defaultView + .getComputedStyle(a, q) + .getPropertyValue('white-space')); + var p = l && 'pre' === l.substring(0, 3); + m(a); + return { a: h.join('').replace(/\n$/, ''), c: t }; + } + function B(a, m, e, h) { + m && + ((a = { a: m, d: a }), + e(a), + h.push.apply(h, a.e)); + } + function x(a, m) { + function e(a) { + for ( + var l = a.d, + p = [l, 'pln'], + d = 0, + g = a.a.match(y) || [], + r = {}, + n = 0, + z = g.length; + n < z; + ++n + ) { + var f = g[n], + b = r[f], + o = void 0, + c; + if (typeof b === 'string') c = !1; + else { + var i = h[f.charAt(0)]; + if (i) (o = f.match(i[1])), (b = i[0]); + else { + for (c = 0; c < t; ++c) + if ( + ((i = m[c]), + (o = f.match(i[1]))) + ) { + b = i[0]; + break; + } + o || (b = 'pln'); + } + if ( + (c = + b.length >= 5 && + 'lang-' === + b.substring(0, 5)) && + !(o && typeof o[1] === 'string') + ) + (c = !1), (b = 'src'); + c || (r[f] = b); + } + i = d; + d += f.length; + if (c) { + c = o[1]; + var j = f.indexOf(c), + k = j + c.length; + o[2] && + ((k = f.length - o[2].length), + (j = k - c.length)); + b = b.substring(5); + B(l + i, f.substring(0, j), e, p); + B(l + i + j, c, C(b, c), p); + B(l + i + k, f.substring(k), e, p); + } else p.push(l + i, b); + } + a.e = p; + } + var h = {}, + y; + (function () { + for ( + var e = a.concat(m), + l = [], + p = {}, + d = 0, + g = e.length; + d < g; + ++d + ) { + var r = e[d], + n = r[3]; + if (n) + for (var k = n.length; --k >= 0; ) + h[n.charAt(k)] = r; + r = r[1]; + n = '' + r; + p.hasOwnProperty(n) || + (l.push(r), (p[n] = q)); + } + l.push(/[\S\s]/); + y = L(l); + })(); + var t = m.length; + return e; + } + function u(a) { + var m = [], + e = []; + a.tripleQuotedStrings + ? m.push([ + 'str', + /^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/, + q, + '\'"' + ]) + : a.multiLineStrings + ? m.push([ + 'str', + /^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, + q, + '\'"`' + ]) + : m.push([ + 'str', + /^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/, + q, + '"\'' + ]); + a.verbatimStrings && + e.push(['str', /^@"(?:[^"]|"")*(?:"|$)/, q]); + var h = a.hashComments; + h && + (a.cStyleComments + ? (h > 1 + ? m.push([ + 'com', + /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, + q, + '#' + ]) + : m.push([ + 'com', + /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/, + q, + '#' + ]), + e.push([ + 'str', + /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, + q + ])) + : m.push(['com', /^#[^\n\r]*/, q, '#'])); + a.cStyleComments && + (e.push(['com', /^\/\/[^\n\r]*/, q]), + e.push(['com', /^\/\*[\S\s]*?(?:\*\/|$)/, q])); + a.regexLiterals && + e.push([ + 'lang-regex', + /^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/ + ]); + (h = a.types) && e.push(['typ', h]); + a = ('' + a.keywords).replace(/^ | $/g, ''); + a.length && + e.push([ + 'kwd', + RegExp( + '^(?:' + + a.replace(/[\s,]+/g, '|') + + ')\\b' + ), + q + ]); + m.push(['pln', /^\s+/, q, ' \r\n\t\xa0']); + e.push( + ['lit', /^@[$_a-z][\w$@]*/i, q], + [ + 'typ', + /^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/, + q + ], + ['pln', /^[$_a-z][\w$@]*/i, q], + [ + 'lit', + /^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i, + q, + '0123456789' + ], + ['pln', /^\\[\S\s]?/, q], + ['pun', /^.[^\s\w"-$'./@\\`]*/, q] + ); + return x(m, e); + } + function D(a, m) { + function e(a) { + switch (a.nodeType) { + case 1: + if (k.test(a.className)) break; + if ('BR' === a.nodeName) + h(a), + a.parentNode && + a.parentNode.removeChild(a); + else + for ( + a = a.firstChild; + a; + a = a.nextSibling + ) + e(a); + break; + case 3: + case 4: + if (p) { + var b = a.nodeValue, + d = b.match(t); + if (d) { + var c = b.substring(0, d.index); + a.nodeValue = c; + (b = b.substring( + d.index + d[0].length + )) && + a.parentNode.insertBefore( + s.createTextNode(b), + a.nextSibling + ); + h(a); + c || + a.parentNode.removeChild(a); + } + } + } + } + function h(a) { + function b(a, d) { + var e = d ? a.cloneNode(!1) : a, + f = a.parentNode; + if (f) { + var f = b(f, 1), + g = a.nextSibling; + f.appendChild(e); + for (var h = g; h; h = g) + (g = h.nextSibling), + f.appendChild(h); + } + return e; + } + for (; !a.nextSibling; ) + if (((a = a.parentNode), !a)) return; + for ( + var a = b(a.nextSibling, 0), e; + (e = a.parentNode) && e.nodeType === 1; + + ) + a = e; + d.push(a); + } + var k = /(?:^|\s)nocode(?:\s|$)/, + t = /\r\n?|\n/, + s = a.ownerDocument, + l; + a.currentStyle + ? (l = a.currentStyle.whiteSpace) + : window.getComputedStyle && + (l = s.defaultView + .getComputedStyle(a, q) + .getPropertyValue('white-space')); + var p = l && 'pre' === l.substring(0, 3); + for (l = s.createElement('LI'); a.firstChild; ) + l.appendChild(a.firstChild); + for (var d = [l], g = 0; g < d.length; ++g) e(d[g]); + m === (m | 0) && d[0].setAttribute('value', m); + var r = s.createElement('OL'); + r.className = 'linenums'; + for ( + var n = Math.max(0, (m - 1) | 0) || 0, + g = 0, + z = d.length; + g < z; + ++g + ) + (l = d[g]), + (l.className = 'L' + ((g + n) % 10)), + l.firstChild || + l.appendChild(s.createTextNode('\xa0')), + r.appendChild(l); + a.appendChild(r); + } + function k(a, m) { + for (var e = m.length; --e >= 0; ) { + var h = m[e]; + A.hasOwnProperty(h) + ? window.console && + console.warn( + 'cannot override language handler %s', + h + ) + : (A[h] = a); + } + } + function C(a, m) { + if (!a || !A.hasOwnProperty(a)) + a = /^\s*= o && (h += 2); + e >= c && (a += 2); + } + } catch (w) { + 'console' in window && + console.log(w && w.stack ? w.stack : w); + } + } + var v = ['break,continue,do,else,for,if,return,while'], + w = [ + [ + v, + 'auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile' + ], + 'catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof' + ], + F = [ + w, + 'alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where' + ], + G = [ + w, + 'abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient' + ], + H = [ + G, + 'as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var' + ], + w = [ + w, + 'debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN' + ], + I = [ + v, + 'and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None' + ], + J = [ + v, + 'alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END' + ], + v = [ + v, + 'case,done,elif,esac,eval,fi,function,in,local,set,then,until' + ], + K = + /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/, + N = /\S/, + O = u({ + keywords: [ + F, + H, + w, + 'caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END' + + I, + J, + v + ], + hashComments: !0, + cStyleComments: !0, + multiLineStrings: !0, + regexLiterals: !0 + }), + A = {}; + k(O, ['default-code']); + k( + x( + [], + [ + ['pln', /^[^]*(?:>|$)/], + ['com', /^<\!--[\S\s]*?(?:--\>|$)/], + ['lang-', /^<\?([\S\s]+?)(?:\?>|$)/], + ['lang-', /^<%([\S\s]+?)(?:%>|$)/], + ['pun', /^(?:<[%?]|[%?]>)/], + [ + 'lang-', + /^]*>([\S\s]+?)<\/xmp\b[^>]*>/i + ], + [ + 'lang-js', + /^]*>([\S\s]*?)(<\/script\b[^>]*>)/i + ], + [ + 'lang-css', + /^]*>([\S\s]*?)(<\/style\b[^>]*>)/i + ], + ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i] + ] + ), + [ + 'default-markup', + 'htm', + 'html', + 'mxml', + 'xhtml', + 'xml', + 'xsl' + ] + ); + k( + x( + [ + ['pln', /^\s+/, q, ' \t\r\n'], + ['atv', /^(?:"[^"]*"?|'[^']*'?)/, q, '"\''] + ], + [ + [ + 'tag', + /^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i + ], + [ + 'atn', + /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i + ], + [ + 'lang-uq.val', + /^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/ + ], + ['pun', /^[/<->]+/], + ['lang-js', /^on\w+\s*=\s*"([^"]+)"/i], + ['lang-js', /^on\w+\s*=\s*'([^']+)'/i], + ['lang-js', /^on\w+\s*=\s*([^\s"'>]+)/i], + ['lang-css', /^style\s*=\s*"([^"]+)"/i], + ['lang-css', /^style\s*=\s*'([^']+)'/i], + ['lang-css', /^style\s*=\s*([^\s"'>]+)/i] + ] + ), + ['in.tag'] + ); + k(x([], [['atv', /^[\S\s]+/]]), ['uq.val']); + k( + u({ + keywords: F, + hashComments: !0, + cStyleComments: !0, + types: K + }), + ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm'] + ); + k(u({ keywords: 'null,true,false' }), ['json']); + k( + u({ + keywords: H, + hashComments: !0, + cStyleComments: !0, + verbatimStrings: !0, + types: K + }), + ['cs'] + ); + k(u({ keywords: G, cStyleComments: !0 }), ['java']); + k( + u({ + keywords: v, + hashComments: !0, + multiLineStrings: !0 + }), + ['bsh', 'csh', 'sh'] + ); + k( + u({ + keywords: I, + hashComments: !0, + multiLineStrings: !0, + tripleQuotedStrings: !0 + }), + ['cv', 'py'] + ); + k( + u({ + keywords: + 'caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END', + hashComments: !0, + multiLineStrings: !0, + regexLiterals: !0 + }), + ['perl', 'pl', 'pm'] + ); + k( + u({ + keywords: J, + hashComments: !0, + multiLineStrings: !0, + regexLiterals: !0 + }), + ['rb'] + ); + k( + u({ + keywords: w, + cStyleComments: !0, + regexLiterals: !0 + }), + ['js'] + ); + k( + u({ + keywords: + 'all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes', + hashComments: 3, + cStyleComments: !0, + multilineStrings: !0, + tripleQuotedStrings: !0, + regexLiterals: !0 + }), + ['coffee'] + ); + k(x([], [['str', /^[\S\s]+/]]), ['regex']); + window.prettyPrintOne = function (a, m, e) { + var h = document.createElement('PRE'); + h.innerHTML = a; + e && D(h, e); + E({ g: m, i: e, h: h }); + return h.innerHTML; + }; + window.prettyPrint = function (a) { + function m() { + for ( + var e = window.PR_SHOULD_USE_CONTINUATION + ? l.now() + 250 + : Infinity; + p < h.length && l.now() < e; + p++ + ) { + var n = h[p], + k = n.className; + if (k.indexOf('prettyprint') >= 0) { + var k = k.match(g), + f, + b; + if ((b = !k)) { + b = n; + for ( + var o = void 0, + c = b.firstChild; + c; + c = c.nextSibling + ) + var i = c.nodeType, + o = + i === 1 + ? o + ? b + : c + : i === 3 + ? N.test( + c.nodeValue + ) + ? b + : o + : o; + b = + (f = o === b ? void 0 : o) && + 'CODE' === f.tagName; + } + b && (k = f.className.match(g)); + k && (k = k[1]); + b = !1; + for ( + o = n.parentNode; + o; + o = o.parentNode + ) + if ( + (o.tagName === 'pre' || + o.tagName === 'code' || + o.tagName === 'xmp') && + o.className && + o.className.indexOf( + 'prettyprint' + ) >= 0 + ) { + b = !0; + break; + } + b || + ((b = (b = n.className.match( + /\blinenums\b(?::(\d+))?/ + )) + ? b[1] && b[1].length + ? +b[1] + : !0 + : !1) && D(n, b), + (d = { g: k, h: n, i: b }), + E(d)); + } + } + p < h.length ? setTimeout(m, 250) : a && a(); + } + for ( + var e = [ + document.getElementsByTagName('pre'), + document.getElementsByTagName('code'), + document.getElementsByTagName('xmp') + ], + h = [], + k = 0; + k < e.length; + ++k + ) + for (var t = 0, s = e[k].length; t < s; ++t) + h.push(e[k][t]); + var e = q, + l = Date; + l.now || + (l = { + now: function () { + return +new Date(); + } + }); + var p = 0, + d, + g = /\blang(?:uage)?-([\w.]+)(?!\S)/; + m(); + }; + window.PR = { + createSimpleLexer: x, + registerLangHandler: k, + sourceDecorator: u, + PR_ATTRIB_NAME: 'atn', + PR_ATTRIB_VALUE: 'atv', + PR_COMMENT: 'com', + PR_DECLARATION: 'dec', + PR_KEYWORD: 'kwd', + PR_LITERAL: 'lit', + PR_NOCODE: 'nocode', + PR_PLAIN: 'pln', + PR_PUNCTUATION: 'pun', + PR_SOURCE: 'src', + PR_STRING: 'str', + PR_TAG: 'tag', + PR_TYPE: 'typ' + }; +})(); diff --git a/weave/unwoven-site/index.html b/weave/unwoven-site/index.html index 006c8f3..aa2db0b 100644 --- a/weave/unwoven-site/index.html +++ b/weave/unwoven-site/index.html @@ -1,14 +1,8 @@ - - Liot R: Admin - @@/head.html - - - - @@/nav.html - - + + Liot R: Admin + @@/head.html + + + @@/nav.html +; diff --git a/weave/unwoven-site/liotr.js b/weave/unwoven-site/liotr.js index 2a5889e..37de00a 100644 --- a/weave/unwoven-site/liotr.js +++ b/weave/unwoven-site/liotr.js @@ -1,4 +1,4 @@ -if(typeof XMLHttpRequest === 'undefined') { +if (typeof XMLHttpRequest === 'undefined') { XMLHttpRequest = require('XMLHttpRequest'); } @@ -11,11 +11,11 @@ function LiotR() { /** * The URL of the Liot R server to connect to. */ -LiotR.SERVER = "http://localhost:7474";//eye.lyku.org +LiotR.SERVER = 'http://localhost:7474'; //eye.lyku.org /** -* Session ID of the current login session. Currently unused. -*/ + * Session ID of the current login session. Currently unused. + */ LiotR.SESSION = null; /** @@ -28,26 +28,27 @@ LiotR.SESSION = null; */ LiotR.post = (data, callback) => { var xml = new XMLHttpRequest(); - if(typeof callback == "function") { - xml.addEventListener('load', ()=> { - //alert(xml.response) - callback(JSON.parse(xml.responseText)) + if (typeof callback == 'function') { + xml.addEventListener('load', () => { + //alert(xml.response) + callback(JSON.parse(xml.responseText)); }); xml.addEventListener('error', () => { - callback({err: 'Unable to contact server.'}) + callback({ err: 'Unable to contact server.' }); }); } - - - if(LiotR.SESSION)data.sessionid = LiotR.SESSION; + if (LiotR.SESSION) data.sessionid = LiotR.SESSION; //alert(JSON.stringify(data)) xml.open('POST', LiotR.SERVER); - xml.setRequestHeader("Content-type", "application/json") + xml.setRequestHeader( + 'Content-type', + 'application/json' + ); xml.send(JSON.stringify(data)); return xml; -} +}; /** * Creates one or more packet collectors. @@ -60,9 +61,9 @@ LiotR.post = (data, callback) => { */ LiotR.addCollectors = (data, callback) => { - data.action = "add collectors"; + data.action = 'add collectors'; return LiotR.post(data, callback); -} +}; /** * Lists any packet collectors. @@ -76,9 +77,9 @@ LiotR.addCollectors = (data, callback) => { */ LiotR.listCollectors = (data, callback) => { - data.action = "list collectors"; + data.action = 'list collectors'; return LiotR.post(data, callback); -} +}; /** * Retreives specified packet collectors. @@ -91,9 +92,9 @@ LiotR.listCollectors = (data, callback) => { */ LiotR.getCollectors = (data, callback) => { - data.action = "get collectors"; + data.action = 'get collectors'; return LiotR.post(data, callback); -} +}; /** * Lists any packet collectors. @@ -107,86 +108,86 @@ LiotR.getCollectors = (data, callback) => { */ LiotR.deleteCollectors = (data, callback) => { - data.action = "delete collectors"; + data.action = 'delete collectors'; return LiotR.post(data, callback); -} +}; LiotR.listFilters = (data, callback) => { - data.action = "list filters"; + data.action = 'list filters'; return LiotR.post(data, callback); -} +}; LiotR.addFilters = (data, callback) => { - data.action = "add filters"; + data.action = 'add filters'; return LiotR.post(data, callback); -} +}; LiotR.getFilters = (data, callback) => { - data.action = "get filters"; + data.action = 'get filters'; return LiotR.post(data, callback); -} +}; LiotR.deleteFilters = (data, callback) => { - data.action = "delete filters"; + data.action = 'delete filters'; return LiotR.post(data, callback); -} +}; LiotR.countFilterReferences = (data, callback) => { - data.action = "count filter references"; + data.action = 'count filter references'; return LiotR.post(data, callback); -} +}; LiotR.listFilterReferrers = (data, callback) => { - data.action = "list filter referrers"; + data.action = 'list filter referrers'; return LiotR.post(data, callback); -} +}; LiotR.addCollators = (data, callback) => { - data.action = "add collators"; + data.action = 'add collators'; return LiotR.post(data, callback); -} +}; LiotR.listCollators = (data, callback) => { - data.action = "list collators"; + data.action = 'list collators'; return LiotR.post(data, callback); -} +}; LiotR.getCollators = (data, callback) => { - data.action = "get collators"; + data.action = 'get collators'; return LiotR.post(data, callback); -} +}; LiotR.deleteCollators = (data, callback) => { - data.action = "delete collators"; + data.action = 'delete collators'; return LiotR.post(data, callback); -} +}; LiotR.countCollatorReferences = (data, callback) => { - data.action = "count collator references"; + data.action = 'count collator references'; return LiotR.post(data, callback); -} +}; LiotR.addDistributors = (data, callback) => { - data.action = "add distributors"; + data.action = 'add distributors'; return LiotR.post(data, callback); -} +}; LiotR.listDistributors = (data, callback) => { - data.action = "list distributors"; + data.action = 'list distributors'; return LiotR.post(data, callback); -} +}; LiotR.getDistributors = (data, callback) => { - data.action = "get distributors"; + data.action = 'get distributors'; return LiotR.post(data, callback); -} +}; LiotR.deleteDistributors = (data, callback) => { - data.action = "delete distributors"; + data.action = 'delete distributors'; return LiotR.post(data, callback); -} +}; LiotR.pushUpdate = (data, callback) => { - data.action = "push update"; + data.action = 'push update'; return LiotR.post(data, callback); -} +}; diff --git a/weave/unwoven-site/liotr.min.js b/weave/unwoven-site/liotr.min.js index 0b825bf..e3eeb9c 100644 --- a/weave/unwoven-site/liotr.min.js +++ b/weave/unwoven-site/liotr.min.js @@ -1,6 +1,100 @@ -"undefined"===typeof XMLHttpRequest&&(XMLHttpRequest=require("XMLHttpRequest"));function LiotR(){}LiotR.SERVER="http://localhost:7474";LiotR.SESSION=null; -LiotR.post=function(a,b){var c=new XMLHttpRequest;"function"==typeof b&&(c.addEventListener("load",function(){b(JSON.parse(c.responseText))}),c.addEventListener("error",function(){b({err:"Unable to contact server."})}));LiotR.SESSION&&(a.sessionid=LiotR.SESSION);c.open("POST",LiotR.SERVER);c.setRequestHeader("Content-type","application/json");c.send(JSON.stringify(a));return c};LiotR.addCollectors=function(a,b){a.action="add collectors";return LiotR.post(a,b)}; -LiotR.listCollectors=function(a,b){a.action="list collectors";return LiotR.post(a,b)};LiotR.getCollectors=function(a,b){a.action="get collectors";return LiotR.post(a,b)};LiotR.deleteCollectors=function(a,b){a.action="delete collectors";return LiotR.post(a,b)};LiotR.listFilters=function(a,b){a.action="list filters";return LiotR.post(a,b)};LiotR.addFilters=function(a,b){a.action="add filters";return LiotR.post(a,b)};LiotR.getFilters=function(a,b){a.action="get filters";return LiotR.post(a,b)}; -LiotR.deleteFilters=function(a,b){a.action="delete filters";return LiotR.post(a,b)};LiotR.countFilterReferences=function(a,b){a.action="count filter references";return LiotR.post(a,b)};LiotR.listFilterReferrers=function(a,b){a.action="list filter referrers";return LiotR.post(a,b)};LiotR.addCollators=function(a,b){a.action="add collators";return LiotR.post(a,b)};LiotR.listCollators=function(a,b){a.action="list collators";return LiotR.post(a,b)}; -LiotR.getCollators=function(a,b){a.action="get collators";return LiotR.post(a,b)};LiotR.deleteCollators=function(a,b){a.action="delete collators";return LiotR.post(a,b)};LiotR.countCollatorReferences=function(a,b){a.action="count collator references";return LiotR.post(a,b)};LiotR.addDistributors=function(a,b){a.action="add distributors";return LiotR.post(a,b)};LiotR.listDistributors=function(a,b){a.action="list distributors";return LiotR.post(a,b)}; -LiotR.getDistributors=function(a,b){a.action="get distributors";return LiotR.post(a,b)};LiotR.deleteDistributors=function(a,b){a.action="delete distributors";return LiotR.post(a,b)};LiotR.pushUpdate=function(a,b){a.action="push update";return LiotR.post(a,b)}; +'undefined' === typeof XMLHttpRequest && + (XMLHttpRequest = require('XMLHttpRequest')); +function LiotR() {} +LiotR.SERVER = 'http://localhost:7474'; +LiotR.SESSION = null; +LiotR.post = function (a, b) { + var c = new XMLHttpRequest(); + 'function' == typeof b && + (c.addEventListener('load', function () { + b(JSON.parse(c.responseText)); + }), + c.addEventListener('error', function () { + b({ err: 'Unable to contact server.' }); + })); + LiotR.SESSION && (a.sessionid = LiotR.SESSION); + c.open('POST', LiotR.SERVER); + c.setRequestHeader('Content-type', 'application/json'); + c.send(JSON.stringify(a)); + return c; +}; +LiotR.addCollectors = function (a, b) { + a.action = 'add collectors'; + return LiotR.post(a, b); +}; +LiotR.listCollectors = function (a, b) { + a.action = 'list collectors'; + return LiotR.post(a, b); +}; +LiotR.getCollectors = function (a, b) { + a.action = 'get collectors'; + return LiotR.post(a, b); +}; +LiotR.deleteCollectors = function (a, b) { + a.action = 'delete collectors'; + return LiotR.post(a, b); +}; +LiotR.listFilters = function (a, b) { + a.action = 'list filters'; + return LiotR.post(a, b); +}; +LiotR.addFilters = function (a, b) { + a.action = 'add filters'; + return LiotR.post(a, b); +}; +LiotR.getFilters = function (a, b) { + a.action = 'get filters'; + return LiotR.post(a, b); +}; +LiotR.deleteFilters = function (a, b) { + a.action = 'delete filters'; + return LiotR.post(a, b); +}; +LiotR.countFilterReferences = function (a, b) { + a.action = 'count filter references'; + return LiotR.post(a, b); +}; +LiotR.listFilterReferrers = function (a, b) { + a.action = 'list filter referrers'; + return LiotR.post(a, b); +}; +LiotR.addCollators = function (a, b) { + a.action = 'add collators'; + return LiotR.post(a, b); +}; +LiotR.listCollators = function (a, b) { + a.action = 'list collators'; + return LiotR.post(a, b); +}; +LiotR.getCollators = function (a, b) { + a.action = 'get collators'; + return LiotR.post(a, b); +}; +LiotR.deleteCollators = function (a, b) { + a.action = 'delete collators'; + return LiotR.post(a, b); +}; +LiotR.countCollatorReferences = function (a, b) { + a.action = 'count collator references'; + return LiotR.post(a, b); +}; +LiotR.addDistributors = function (a, b) { + a.action = 'add distributors'; + return LiotR.post(a, b); +}; +LiotR.listDistributors = function (a, b) { + a.action = 'list distributors'; + return LiotR.post(a, b); +}; +LiotR.getDistributors = function (a, b) { + a.action = 'get distributors'; + return LiotR.post(a, b); +}; +LiotR.deleteDistributors = function (a, b) { + a.action = 'delete distributors'; + return LiotR.post(a, b); +}; +LiotR.pushUpdate = function (a, b) { + a.action = 'push update'; + return LiotR.post(a, b); +}; diff --git a/weave/unwoven-site/lir.min.js b/weave/unwoven-site/lir.min.js index 318f8cc..33adb2d 100644 --- a/weave/unwoven-site/lir.min.js +++ b/weave/unwoven-site/lir.min.js @@ -1,5 +1,98 @@ -function LiotR(){}LiotR.SERVER="http://localhost:7474";LiotR.SESSION=null;LiotR.post=function(a,b){var c=new XMLHttpRequest;"function"==typeof b&&(c.addEventListener("load",function(){b(JSON.parse(c.responseText))}),c.addEventListener("error",function(){b({err:"Unable to contact server."})}));LiotR.SESSION&&(a.sessionid=LiotR.SESSION);c.open("POST",LiotR.SERVER);c.setRequestHeader("Content-type","application/json");c.send(JSON.stringify(a));return c}; -LiotR.addCollectors=function(a,b){a.action="add collectors";return LiotR.post(a,b)};LiotR.listCollectors=function(a,b){a.action="list collectors";return LiotR.post(a,b)};LiotR.getCollectors=function(a,b){a.action="get collectors";return LiotR.post(a,b)};LiotR.deleteCollectors=function(a,b){a.action="delete collectors";return LiotR.post(a,b)};LiotR.listFilters=function(a,b){a.action="list filters";return LiotR.post(a,b)};LiotR.addFilters=function(a,b){a.action="add filters";return LiotR.post(a,b)}; -LiotR.getFilters=function(a,b){a.action="get filters";return LiotR.post(a,b)};LiotR.deleteFilters=function(a,b){a.action="delete filters";return LiotR.post(a,b)};LiotR.countFilterReferences=function(a,b){a.action="count filter references";return LiotR.post(a,b)};LiotR.listFilterReferrers=function(a,b){a.action="list filter referrers";return LiotR.post(a,b)};LiotR.addCollators=function(a,b){a.action="add collators";return LiotR.post(a,b)};LiotR.listCollators=function(a,b){a.action="list collators";return LiotR.post(a,b)}; -LiotR.getCollators=function(a,b){a.action="get collators";return LiotR.post(a,b)};LiotR.deleteCollators=function(a,b){a.action="delete collators";return LiotR.post(a,b)};LiotR.countCollatorReferences=function(a,b){a.action="count collator references";return LiotR.post(a,b)};LiotR.addDistributors=function(a,b){a.action="add distributors";return LiotR.post(a,b)};LiotR.listDistributors=function(a,b){a.action="list distributors";return LiotR.post(a,b)}; -LiotR.getDistributors=function(a,b){a.action="get distributors";return LiotR.post(a,b)};LiotR.deleteDistributors=function(a,b){a.action="delete distributors";return LiotR.post(a,b)};LiotR.pushUpdate=function(a,b){a.action="push update";return LiotR.post(a,b)}; +function LiotR() {} +LiotR.SERVER = 'http://localhost:7474'; +LiotR.SESSION = null; +LiotR.post = function (a, b) { + var c = new XMLHttpRequest(); + 'function' == typeof b && + (c.addEventListener('load', function () { + b(JSON.parse(c.responseText)); + }), + c.addEventListener('error', function () { + b({ err: 'Unable to contact server.' }); + })); + LiotR.SESSION && (a.sessionid = LiotR.SESSION); + c.open('POST', LiotR.SERVER); + c.setRequestHeader('Content-type', 'application/json'); + c.send(JSON.stringify(a)); + return c; +}; +LiotR.addCollectors = function (a, b) { + a.action = 'add collectors'; + return LiotR.post(a, b); +}; +LiotR.listCollectors = function (a, b) { + a.action = 'list collectors'; + return LiotR.post(a, b); +}; +LiotR.getCollectors = function (a, b) { + a.action = 'get collectors'; + return LiotR.post(a, b); +}; +LiotR.deleteCollectors = function (a, b) { + a.action = 'delete collectors'; + return LiotR.post(a, b); +}; +LiotR.listFilters = function (a, b) { + a.action = 'list filters'; + return LiotR.post(a, b); +}; +LiotR.addFilters = function (a, b) { + a.action = 'add filters'; + return LiotR.post(a, b); +}; +LiotR.getFilters = function (a, b) { + a.action = 'get filters'; + return LiotR.post(a, b); +}; +LiotR.deleteFilters = function (a, b) { + a.action = 'delete filters'; + return LiotR.post(a, b); +}; +LiotR.countFilterReferences = function (a, b) { + a.action = 'count filter references'; + return LiotR.post(a, b); +}; +LiotR.listFilterReferrers = function (a, b) { + a.action = 'list filter referrers'; + return LiotR.post(a, b); +}; +LiotR.addCollators = function (a, b) { + a.action = 'add collators'; + return LiotR.post(a, b); +}; +LiotR.listCollators = function (a, b) { + a.action = 'list collators'; + return LiotR.post(a, b); +}; +LiotR.getCollators = function (a, b) { + a.action = 'get collators'; + return LiotR.post(a, b); +}; +LiotR.deleteCollators = function (a, b) { + a.action = 'delete collators'; + return LiotR.post(a, b); +}; +LiotR.countCollatorReferences = function (a, b) { + a.action = 'count collator references'; + return LiotR.post(a, b); +}; +LiotR.addDistributors = function (a, b) { + a.action = 'add distributors'; + return LiotR.post(a, b); +}; +LiotR.listDistributors = function (a, b) { + a.action = 'list distributors'; + return LiotR.post(a, b); +}; +LiotR.getDistributors = function (a, b) { + a.action = 'get distributors'; + return LiotR.post(a, b); +}; +LiotR.deleteDistributors = function (a, b) { + a.action = 'delete distributors'; + return LiotR.post(a, b); +}; +LiotR.pushUpdate = function (a, b) { + a.action = 'push update'; + return LiotR.post(a, b); +}; diff --git a/weave/unwoven-site/script.js b/weave/unwoven-site/script.js index d8d8ecf..4e83470 100644 --- a/weave/unwoven-site/script.js +++ b/weave/unwoven-site/script.js @@ -1,41 +1,65 @@ function grab(elem, root) { - return typeof elem === 'string' ? (grab(root) || document).getElementById(elem) : elem; + return typeof elem === 'string' + ? (grab(root) || document).getElementById(elem) + : elem; } function bind(elem, trigger, func) { - elem.addEventListener(trigger, func) + elem.addEventListener(trigger, func); } function load(func) { - bind(window, 'DOMContentLoaded', func) + bind(window, 'DOMContentLoaded', func); } function namify(rec, type, editing) { - var name = xss(rec.name||''), id = xss(rec.id); - var edit = `edit${editing?'ing':''}`; - return ( name.length ? name : 'Unnamed ' + type[0].toUpperCase() + type.substr(1) + "" ) + edit + " ["+id+"]"; - /*return rec.name && rec.name.length ? + var name = xss(rec.name || ''), + id = xss(rec.id); + var edit = `edit${ + editing ? 'ing' : '' + }`; + return ( + (name.length + ? name + : 'Unnamed ' + + type[0].toUpperCase() + + type.substr(1) + + '') + + edit + + " [" + + id + + ']' + ); + /*return rec.name && rec.name.length ? name + edit + " ["+id+"]" : `[${id}]` + edit;*/ } function appendCollators(collators, to, id) { - for(var i = 0; i < collators.length; i ++) { - var rec = collators[i]; - var bubble = nelem('div'); - addc(bubble, 'bubble'); - var top = nelem('div'); - addc(top, 'bubble-top'); - bubble.appendChild(top); - var nameBox = nelem('label'); - nameBox.innerHTML = namify(rec, 'collator', id == rec.id); - //xss((rec.name || "["+rec.id+"]") + ""); - var idBox = nelem('label'); - idBox.innerHTML = xss(rec.id); + for (var i = 0; i < collators.length; i++) { + var rec = collators[i]; + var bubble = nelem('div'); + addc(bubble, 'bubble'); + var top = nelem('div'); + addc(top, 'bubble-top'); + bubble.appendChild(top); + var nameBox = nelem('label'); + nameBox.innerHTML = namify( + rec, + 'collator', + id == rec.id + ); + //xss((rec.name || "["+rec.id+"]") + ""); + var idBox = nelem('label'); + idBox.innerHTML = xss(rec.id); - var valBox = nelem('label'); - //addc(valBox, 'filters-tooltip'); - var filternames = ''; - var filterNodes = []; - for(var filtret of rec.filtrets) { - filternames += (filtret.name || filtret.id.substring(0,10)) + ', '; - /*var filterBox = nelem('div'); + var valBox = nelem('label'); + //addc(valBox, 'filters-tooltip'); + var filternames = ''; + var filterNodes = []; + for (var filtret of rec.filtrets) { + filternames += + (filtret.name || + filtret.id.substring(0, 10)) + ', '; + /*var filterBox = nelem('div'); addc(filterBox, 'bubble'); addc(filterBox, 'subble'); var filterName = nelem('label'); @@ -46,80 +70,99 @@ function appendCollators(collators, to, id) { filterBox.appendChild(filterCode); filterNodes.push(filterBox); appendDropper(filterBox);*/ - } - filternames = "("+filternames.substring(0,filternames.length-2)+")"; - valBox.innerHTML = xss(filternames) - top.appendChild(nameBox); - //top.appendChild(valBox); - for(var n of filterNodes)bubble.appendChild(n); - //bubble.appendChild(idBox); - //console.log(filtret.code) - to.appendChild(bubble); - appendFilters(rec.filtrets, bubble, id); - appendDropper(bubble); - appendSpecifics(bubble, rec.id, 'collator'); - //bindBubble(bubble,rec) - } - if(!collators.length) appendPlaceholder('collators', to); + } + filternames = + '(' + + filternames.substring( + 0, + filternames.length - 2 + ) + + ')'; + valBox.innerHTML = xss(filternames); + top.appendChild(nameBox); + //top.appendChild(valBox); + for (var n of filterNodes) bubble.appendChild(n); + //bubble.appendChild(idBox); + //console.log(filtret.code) + to.appendChild(bubble); + appendFilters(rec.filtrets, bubble, id); + appendDropper(bubble); + appendSpecifics(bubble, rec.id, 'collator'); + //bindBubble(bubble,rec) + } + if (!collators.length) + appendPlaceholder('collators', to); } function appendPlaceholder(type, to) { - var span = nelem('div'); - addc(span, 'placehodler'); - span.innerHTML = 'No ' + type; - to.appendChild(span); + var span = nelem('div'); + addc(span, 'placehodler'); + span.innerHTML = 'No ' + type; + to.appendChild(span); } function appendFilters(filters, filterList, id) { - for(var i = 0; i < filters.length; i ++) { - var rec = filters[i]; - var bubble = nelem('div'); - addc(bubble, 'bubble'); - var top = nelem('div'); - addc(top, 'bubble-top'); - bubble.appendChild(top); - var nameBox = nelem('label'); - nameBox.innerHTML = namify(rec, 'filter', id == rec.id);//xss((rec.name || rec.id)); - var idBox = nelem('label'); - idBox.innerHTML = xss(rec.id); + for (var i = 0; i < filters.length; i++) { + var rec = filters[i]; + var bubble = nelem('div'); + addc(bubble, 'bubble'); + var top = nelem('div'); + addc(top, 'bubble-top'); + bubble.appendChild(top); + var nameBox = nelem('label'); + nameBox.innerHTML = namify( + rec, + 'filter', + id == rec.id + ); //xss((rec.name || rec.id)); + var idBox = nelem('label'); + idBox.innerHTML = xss(rec.id); - var valBox = nelem('pre'); - valBox.innerHTML = codify(xss(rec.code)) - top.appendChild(nameBox); - bubble.appendChild(valBox); - //bubble.appendChild(idBox); - filterList.appendChild(bubble); - appendDropper(bubble); - //bindBubble(bubble,rec) - appendSpecifics(bubble, rec.id, 'filter'); - } - if(!filters.length) appendPlaceholder('filters', filterList); + var valBox = nelem('pre'); + valBox.innerHTML = codify(xss(rec.code)); + top.appendChild(nameBox); + bubble.appendChild(valBox); + //bubble.appendChild(idBox); + filterList.appendChild(bubble); + appendDropper(bubble); + //bindBubble(bubble,rec) + appendSpecifics(bubble, rec.id, 'filter'); + } + if (!filters.length) + appendPlaceholder('filters', filterList); } function appendCollectors(filters, filterList, id) { - for(var i = 0; i < filters.length; i ++) { - var rec = filters[i]; - var bubble = nelem('div'); - addc(bubble, 'bubble'); - var top = nelem('div'); - addc(top, 'bubble-top'); - bubble.appendChild(top); - var nameBox = nelem('label'); - nameBox.innerHTML = namify(rec, 'collector', id == rec.id);//xss((rec.name || rec.id)); - var idBox = nelem('label'); - idBox.innerHTML = xss(rec.id); + for (var i = 0; i < filters.length; i++) { + var rec = filters[i]; + var bubble = nelem('div'); + addc(bubble, 'bubble'); + var top = nelem('div'); + addc(top, 'bubble-top'); + bubble.appendChild(top); + var nameBox = nelem('label'); + nameBox.innerHTML = namify( + rec, + 'collector', + id == rec.id + ); //xss((rec.name || rec.id)); + var idBox = nelem('label'); + idBox.innerHTML = xss(rec.id); - var valBox = nelem('pre'); - valBox.innerHTML = valify(xss(JSON.stringify(rec,null,3))) - top.appendChild(nameBox); - bubble.appendChild(valBox); - //bubble.appendChild(idBox); - filterList.appendChild(bubble); - appendDropper(bubble); - //bindBubble(bubble,rec) - appendSpecifics(bubble, rec.id, 'collector'); - } - if(!filters.length) appendPlaceholder('collectors', filterList); + var valBox = nelem('pre'); + valBox.innerHTML = valify( + xss(JSON.stringify(rec, null, 3)) + ); + top.appendChild(nameBox); + bubble.appendChild(valBox); + //bubble.appendChild(idBox); + filterList.appendChild(bubble); + appendDropper(bubble); + //bindBubble(bubble,rec) + appendSpecifics(bubble, rec.id, 'collector'); + } + if (!filters.length) + appendPlaceholder('collectors', filterList); } function appendSpecifics(bubble, id, type) { - /*var bottom = nelem('div'); + /*var bottom = nelem('div'); addc(bottom, 'bubble-bottom'); var edit = nelem('a'); edit.innerHTML = "Edit " + type[0].toUpperCase() + type.substring(1); @@ -128,75 +171,112 @@ function appendSpecifics(bubble, id, type) { bubble.appendChild(bottom);*/ } function stringValue(value) { - switch(typeof value) { - case 'object': - value = JSON.stringify(value); - case 'string': - if(value.length < 30) { - if(value.length == 0) - value = "NO VALUE"; - return value; - } else { - return value.substring(0,27)+"..."; - } - break; - case 'number': - return value+""; - break; - } - return value; + switch (typeof value) { + case 'object': + value = JSON.stringify(value); + case 'string': + if (value.length < 30) { + if (value.length == 0) value = 'NO VALUE'; + return value; + } else { + return value.substring(0, 27) + '...'; + } + break; + case 'number': + return value + ''; + break; + } + return value; } function codify(string) { - string = string.replace(/([:,]) ([0-9]+)(,|\n| \])/g, '$1 %%n%%$2%%n%%$3') - //.replace(/([0-9]+)/g, '%%n%%$1%%n%%') - .replace(/"(\$.+?)"/g, "%%v%%$1%%v%%") - //.replace(/(?:^\s+)([^%])("[^$].+?")([^%])/g, "$1%%s%%$2%%s%%$3") - .replace(/^(\s+)"([A-Z]+)"/gm, "$1%%c%%$2%%c%%") - .replace(/"([^$].+?)"/g, "%%s%%$1%%s%%") - .replace(/%%n%%(.+?)%%n%%/g,'$1') - .replace(/%%s%%(.+?)%%s%%/g,'$1') - .replace(/%%c%%(.+?)%%c%%/g,'$1') - .replace(/%%v%%(.+?)%%v%%/g,'$1') - return string - /*.replace(/([0-9])+/g,'$1') + string = string + .replace( + /([:,]) ([0-9]+)(,|\n| \])/g, + '$1 %%n%%$2%%n%%$3' + ) + //.replace(/([0-9]+)/g, '%%n%%$1%%n%%') + .replace(/"(\$.+?)"/g, '%%v%%$1%%v%%') + //.replace(/(?:^\s+)([^%])("[^$].+?")([^%])/g, "$1%%s%%$2%%s%%$3") + .replace(/^(\s+)"([A-Z]+)"/gm, '$1%%c%%$2%%c%%') + .replace(/"([^$].+?)"/g, '%%s%%$1%%s%%') + .replace( + /%%n%%(.+?)%%n%%/g, + '$1' + ) + .replace( + /%%s%%(.+?)%%s%%/g, + '$1' + ) + .replace( + /%%c%%(.+?)%%c%%/g, + '$1' + ) + .replace( + /%%v%%(.+?)%%v%%/g, + '$1' + ); + return string; + /*.replace(/([0-9])+/g,'$1') .replace(/(?!|: [{\[])/g,'$1')*/ } function valify(string) { - string = string.replace(/([:,]) ([0-9]+)(,|\n| \])/g, '$1 %%n%%$2%%n%%$3') - .replace(/"(\$.+?)"/g, "%%v%%$1%%v%%") - //.replace(/(?:^\s+)([^%])("[^$].+?")([^%])/g, "$1%%s%%$2%%s%%$3") - .replace(/^(\s+)"([A-Z]+)"/gm, "$1%%c%%$2%%c%%") - .replace(/"([^$].+?)"/g, "%%s%%$1%%s%%") - .replace(/%%n%%(.+?)%%n%%/g,'$1') - .replace(/%%s%%([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})%%s%%/g,'$1') - .replace(/%%s%%(.+?)%%s%%/g,'$1') - .replace(/%%c%%(.+?)%%c%%/g,'$1') - .replace(/%%v%%(.+?)%%v%%/g,'$1') - .replace(/([:,]) (true|false)(,|\n| \])/g, '$1 $2$3') - return string - /*.replace(/([0-9])+/g,'$1') + string = string + .replace( + /([:,]) ([0-9]+)(,|\n| \])/g, + '$1 %%n%%$2%%n%%$3' + ) + .replace(/"(\$.+?)"/g, '%%v%%$1%%v%%') + //.replace(/(?:^\s+)([^%])("[^$].+?")([^%])/g, "$1%%s%%$2%%s%%$3") + .replace(/^(\s+)"([A-Z]+)"/gm, '$1%%c%%$2%%c%%') + .replace(/"([^$].+?)"/g, '%%s%%$1%%s%%') + .replace( + /%%n%%(.+?)%%n%%/g, + '$1' + ) + .replace( + /%%s%%([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})%%s%%/g, + '$1' + ) + .replace( + /%%s%%(.+?)%%s%%/g, + '$1' + ) + .replace( + /%%c%%(.+?)%%c%%/g, + '$1' + ) + .replace( + /%%v%%(.+?)%%v%%/g, + '$1' + ) + .replace( + /([:,]) (true|false)(,|\n| \])/g, + '$1 $2$3' + ); + return string; + /*.replace(/([0-9])+/g,'$1') .replace(/(?!|: [{\[])/g,'$1')*/ } function appendDropper(bubble) { - var dropper = nelem('div'); - dropper.innerHTML = 'V'; - addc(dropper, 'dropper'); - bind(bubble.children[0], 'click', e=>{ - togc(bubble, 'dropped'); - //e.preventDefault(); - return false; - }) - bubble.appendChild(dropper); + var dropper = nelem('div'); + dropper.innerHTML = 'V'; + addc(dropper, 'dropper'); + bind(bubble.children[0], 'click', e => { + togc(bubble, 'dropped'); + //e.preventDefault(); + return false; + }); + bubble.appendChild(dropper); } function bindBubble(bubble, rec) { - bind(bubble, 'click', ()=>{ - location.href = '/filters/edit?id='+rec.id; - }) + bind(bubble, 'click', () => { + location.href = '/filters/edit?id=' + rec.id; + }); } function getPageId() { - var id = location.href.match(/\?id=(.+)$/) - return id ? id[1] : 0; + var id = location.href.match(/\?id=(.+)$/); + return id ? id[1] : 0; } diff --git a/weave/unwoven-site/script.min.js b/weave/unwoven-site/script.min.js index 8409210..cac535a 100644 --- a/weave/unwoven-site/script.min.js +++ b/weave/unwoven-site/script.min.js @@ -1,13 +1,289 @@ -var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,d){if(d.get||d.set)throw new TypeError("ES3 does not support getters and setters.");a!=Array.prototype&&a!=Object.prototype&&(a[b]=d.value)};$jscomp.getGlobal=function(a){return"undefined"!=typeof window&&window===a?a:"undefined"!=typeof global&&null!=global?global:a};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_"; -$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(a){return $jscomp.SYMBOL_PREFIX+(a||"")+$jscomp.symbolCounter_++}; -$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var a=$jscomp.global.Symbol.iterator;a||(a=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[a]&&$jscomp.defineProperty(Array.prototype,a,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(a){var b=0;return $jscomp.iteratorPrototype(function(){return bedit'+(d?"ing":"")+"";return(f.length?f:"Unnamed "+b[0].toUpperCase()+b.substr(1)+"")+a+" ["+e+"]"} -function appendCollators(a,b,d){for(var f=0;fa.length)0==a.length&&(a="NO VALUE");else return a.substring(0,27)+"...";break;case "number":return a+""}return a} -function codify(a){return a=a.replace(/([:,]) ([0-9]+)(,|\n| \])/g,"$1 %%n%%$2%%n%%$3").replace(/"(\$.+?)"/g,"%%v%%$1%%v%%").replace(/^(\s+)"([A-Z]+)"/gm,"$1%%c%%$2%%c%%").replace(/"([^$].+?)"/g,"%%s%%$1%%s%%").replace(/%%n%%(.+?)%%n%%/g,'$1').replace(/%%s%%(.+?)%%s%%/g,'$1').replace(/%%c%%(.+?)%%c%%/g,'$1').replace(/%%v%%(.+?)%%v%%/g,'$1')} -function valify(a){return a=a.replace(/([:,]) ([0-9]+)(,|\n| \])/g,"$1 %%n%%$2%%n%%$3").replace(/"(\$.+?)"/g,"%%v%%$1%%v%%").replace(/^(\s+)"([A-Z]+)"/gm,"$1%%c%%$2%%c%%").replace(/"([^$].+?)"/g,"%%s%%$1%%s%%").replace(/%%n%%(.+?)%%n%%/g,'$1').replace(/%%s%%([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})%%s%%/g,'$1').replace(/%%s%%(.+?)%%s%%/g,'$1').replace(/%%c%%(.+?)%%c%%/g,'$1').replace(/%%v%%(.+?)%%v%%/g, -'$1').replace(/([:,]) (true|false)(,|\n| \])/g,'$1 $2$3')}function appendDropper(a){var b=nelem("div");b.innerHTML="V";addc(b,"dropper");bind(a.children[0],"click",function(b){togc(a,"dropped");return!1});a.appendChild(b)}function bindBubble(a,b){bind(a,"click",function(){location.href="/filters/edit?id="+b.id})}function getPageId(){var a=location.href.match(/\?id=(.+)$/);return a?a[1]:null}; +var $jscomp = { scope: {} }; +$jscomp.defineProperty = + 'function' == typeof Object.defineProperties + ? Object.defineProperty + : function (a, b, d) { + if (d.get || d.set) + throw new TypeError( + 'ES3 does not support getters and setters.' + ); + a != Array.prototype && + a != Object.prototype && + (a[b] = d.value); + }; +$jscomp.getGlobal = function (a) { + return 'undefined' != typeof window && window === a + ? a + : 'undefined' != typeof global && null != global + ? global + : a; +}; +$jscomp.global = $jscomp.getGlobal(this); +$jscomp.SYMBOL_PREFIX = 'jscomp_symbol_'; +$jscomp.initSymbol = function () { + $jscomp.initSymbol = function () {}; + $jscomp.global.Symbol || + ($jscomp.global.Symbol = $jscomp.Symbol); +}; +$jscomp.symbolCounter_ = 0; +$jscomp.Symbol = function (a) { + return ( + $jscomp.SYMBOL_PREFIX + + (a || '') + + $jscomp.symbolCounter_++ + ); +}; +$jscomp.initSymbolIterator = function () { + $jscomp.initSymbol(); + var a = $jscomp.global.Symbol.iterator; + a || + (a = $jscomp.global.Symbol.iterator = + $jscomp.global.Symbol('iterator')); + 'function' != typeof Array.prototype[a] && + $jscomp.defineProperty(Array.prototype, a, { + configurable: !0, + writable: !0, + value: function () { + return $jscomp.arrayIterator(this); + } + }); + $jscomp.initSymbolIterator = function () {}; +}; +$jscomp.arrayIterator = function (a) { + var b = 0; + return $jscomp.iteratorPrototype(function () { + return b < a.length + ? { done: !1, value: a[b++] } + : { done: !0 }; + }); +}; +$jscomp.iteratorPrototype = function (a) { + $jscomp.initSymbolIterator(); + a = { next: a }; + a[$jscomp.global.Symbol.iterator] = function () { + return this; + }; + return a; +}; +$jscomp.makeIterator = function (a) { + $jscomp.initSymbolIterator(); + var b = a[Symbol.iterator]; + return b ? b.call(a) : $jscomp.arrayIterator(a); +}; +function grab(a, b) { + return 'string' === typeof a + ? (grab(b) || document).getElementById(a) + : a; +} +function bind(a, b, d) { + a.addEventListener(b, d); +} +function load(a) { + bind(window, 'DOMContentLoaded', a); +} +function namify(a, b, d) { + var f = xss(a.name || ''), + e = xss(a.id); + a = + "edit' + + (d ? 'ing' : '') + + ''; + return ( + (f.length + ? f + : 'Unnamed ' + + b[0].toUpperCase() + + b.substr(1) + + '') + + a + + " [" + + e + + ']' + ); +} +function appendCollators(a, b, d) { + for (var f = 0; f < a.length; f++) { + var e = a[f], + c = nelem('div'); + addc(c, 'bubble'); + var g = nelem('div'); + addc(g, 'bubble-top'); + c.appendChild(g); + var h = nelem('label'); + h.innerHTML = namify(e, 'collator', d == e.id); + nelem('label').innerHTML = xss(e.id); + for ( + var k = nelem('label'), + m = '', + n = $jscomp.makeIterator(e.filtrets), + l = n.next(); + !l.done; + l = n.next() + ) + (l = l.value), + (m += + (l.name || l.id.substring(0, 10)) + + ', '); + m = '(' + m.substring(0, m.length - 2) + ')'; + k.innerHTML = xss(m); + g.appendChild(h); + g = $jscomp.makeIterator([]); + for (h = g.next(); !h.done; h = g.next()) + c.appendChild(h.value); + b.appendChild(c); + appendFilters(e.filtrets, c, d); + appendDropper(c); + appendSpecifics(c, e.id, 'collator'); + } + a.length || appendPlaceholder('collators', b); +} +function appendPlaceholder(a, b) { + var d = nelem('div'); + addc(d, 'placehodler'); + d.innerHTML = 'No ' + a; + b.appendChild(d); +} +function appendFilters(a, b, d) { + for (var f = 0; f < a.length; f++) { + var e = a[f], + c = nelem('div'); + addc(c, 'bubble'); + var g = nelem('div'); + addc(g, 'bubble-top'); + c.appendChild(g); + var h = nelem('label'); + h.innerHTML = namify(e, 'filter', d == e.id); + nelem('label').innerHTML = xss(e.id); + var k = nelem('pre'); + k.innerHTML = codify(xss(e.code)); + g.appendChild(h); + c.appendChild(k); + b.appendChild(c); + appendDropper(c); + appendSpecifics(c, e.id, 'filter'); + } + a.length || appendPlaceholder('filters', b); +} +function appendCollectors(a, b, d) { + for (var f = 0; f < a.length; f++) { + var e = a[f], + c = nelem('div'); + addc(c, 'bubble'); + var g = nelem('div'); + addc(g, 'bubble-top'); + c.appendChild(g); + var h = nelem('label'); + h.innerHTML = namify(e, 'collector', d == e.id); + nelem('label').innerHTML = xss(e.id); + var k = nelem('pre'); + k.innerHTML = valify( + xss(JSON.stringify(e, null, 3)) + ); + g.appendChild(h); + c.appendChild(k); + b.appendChild(c); + appendDropper(c); + appendSpecifics(c, e.id, 'collector'); + } + a.length || appendPlaceholder('collectors', b); +} +function appendSpecifics(a, b, d) {} +function stringValue(a) { + switch (typeof a) { + case 'object': + a = JSON.stringify(a); + case 'string': + if (30 > a.length) + 0 == a.length && (a = 'NO VALUE'); + else return a.substring(0, 27) + '...'; + break; + case 'number': + return a + ''; + } + return a; +} +function codify(a) { + return (a = a + .replace( + /([:,]) ([0-9]+)(,|\n| \])/g, + '$1 %%n%%$2%%n%%$3' + ) + .replace(/"(\$.+?)"/g, '%%v%%$1%%v%%') + .replace(/^(\s+)"([A-Z]+)"/gm, '$1%%c%%$2%%c%%') + .replace(/"([^$].+?)"/g, '%%s%%$1%%s%%') + .replace( + /%%n%%(.+?)%%n%%/g, + '$1' + ) + .replace( + /%%s%%(.+?)%%s%%/g, + '$1' + ) + .replace( + /%%c%%(.+?)%%c%%/g, + '$1' + ) + .replace( + /%%v%%(.+?)%%v%%/g, + '$1' + )); +} +function valify(a) { + return (a = a + .replace( + /([:,]) ([0-9]+)(,|\n| \])/g, + '$1 %%n%%$2%%n%%$3' + ) + .replace(/"(\$.+?)"/g, '%%v%%$1%%v%%') + .replace(/^(\s+)"([A-Z]+)"/gm, '$1%%c%%$2%%c%%') + .replace(/"([^$].+?)"/g, '%%s%%$1%%s%%') + .replace( + /%%n%%(.+?)%%n%%/g, + '$1' + ) + .replace( + /%%s%%([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12})%%s%%/g, + '$1' + ) + .replace( + /%%s%%(.+?)%%s%%/g, + '$1' + ) + .replace( + /%%c%%(.+?)%%c%%/g, + '$1' + ) + .replace( + /%%v%%(.+?)%%v%%/g, + '$1' + ) + .replace( + /([:,]) (true|false)(,|\n| \])/g, + '$1 $2$3' + )); +} +function appendDropper(a) { + var b = nelem('div'); + b.innerHTML = 'V'; + addc(b, 'dropper'); + bind(a.children[0], 'click', function (b) { + togc(a, 'dropped'); + return !1; + }); + a.appendChild(b); +} +function bindBubble(a, b) { + bind(a, 'click', function () { + location.href = '/filters/edit?id=' + b.id; + }); +} +function getPageId() { + var a = location.href.match(/\?id=(.+)$/); + return a ? a[1] : null; +} diff --git a/weave/weave.js b/weave/weave.js index 30eb494..e54872d 100644 --- a/weave/weave.js +++ b/weave/weave.js @@ -1,10 +1,10 @@ /*jslint regexp:true */ var fs = require('fs'), - mkdirp = require('mkdirp'), - pather = require('path'); + mkdirp = require('mkdirp'), + pather = require('path'); var DIRECTORIES = []; -var FILES = [] +var FILES = []; var DEPENDENCIES = {}; var UNMET_DEPENDENCIES = {}; var WRITTEN_FILES = {}; @@ -15,275 +15,333 @@ var INTERPOLATED_COUNT = 0; var WRITTEN_FILE_COUNT = 0; var ARGREG = /^[\-\/](.+)$/; -var ATREG = /(?:^|[^\\])(?:\\\\)*@@(.+?)(?:(?:\\\\)*@@|$)/gm; +var ATREG = + /(?:^|[^\\])(?:\\\\)*@@(.+?)(?:(?:\\\\)*@@|$)/gm; var CONF = { - i: 'unwoven-site', - t: 'weaving-site', - o: 'woven-site', - e: ['html', 'js', 'css'] + i: 'unwoven-site', + t: 'weaving-site', + o: 'woven-site', + e: ['html', 'js', 'css'] }; fs.readFile('weave.json', 'utf-8', (err, bod) => { - if(bod) { - //console.log("Conf found!",bod) - var fileConfig = JSON.parse(bod); - if(fileConfig.directories) { - CONF.i = fileConfig.directories.input || CONF.i; - CONF.o = fileConfig.directories.output || CONF.o; - CONF.t = fileConfig.directories.temp || CONF.t; - } - } - CONF.t = CONF.o; - for(var k of ['i','o','t']) - CONF[k]= pather.resolve(CONF[k]) - //console.log(CONF) - getArgs(); - listTree(CONF.i); -}) + if (bod) { + //console.log("Conf found!",bod) + var fileConfig = JSON.parse(bod); + if (fileConfig.directories) { + CONF.i = fileConfig.directories.input || CONF.i; + CONF.o = + fileConfig.directories.output || CONF.o; + CONF.t = fileConfig.directories.temp || CONF.t; + } + } + CONF.t = CONF.o; + for (var k of ['i', 'o', 't']) + CONF[k] = pather.resolve(CONF[k]); + //console.log(CONF) + getArgs(); + listTree(CONF.i); +}); //var ARGS = ['i', 't', 'o']; function getArgs() { - 'use strict'; - var arg, i; - for (i = 2; i < process.argv.length - 1; i += 1) { - arg = process.argv[i].match(ARGREG); - if (!arg) { - throw 'Invalid option format.'; - } - arg = arg[1]; - if (!CONF.hasOwnProperty(arg)) { - throw 'Invalid option provided.'; - } - CONF[arg] = process.argv[i + 1]; - } + 'use strict'; + var arg, i; + for (i = 2; i < process.argv.length - 1; i += 1) { + arg = process.argv[i].match(ARGREG); + if (!arg) { + throw 'Invalid option format.'; + } + arg = arg[1]; + if (!CONF.hasOwnProperty(arg)) { + throw 'Invalid option provided.'; + } + CONF[arg] = process.argv[i + 1]; + } } function listTree(directory) { - 'use strict'; - queueRead(); - fs.readdir(directory, (err, items) => { - if(!Array.isArray(items)) { - throw 'Unable to read input directory.' - } - for(var item of items) { - statItem(item); - } - unqueueRead(); - }) - function statItem(item) { - queueRead(); - var path = pather.join(directory,item); - fs.stat(path, (err, stats) => { - if(stats.isDirectory()) { - DIRECTORIES.push(path); - listTree(path); - unqueueRead(); - } else if(stats.isFile()) { - fs.readFile(path, 'utf-8', processFile) - } - }) - function processFile(err, body) { - var e = ATREG, m, dependencies = []; - var ext = path.match(/\.([a-z0-9]+)$/) - if(ext && CONF.e.includes(ext[1])) { - //console.log("MATCH",ext) - while(m = e.exec(body)) { - var p = pathify(directory, m[1]); - //var op = pathify(outify(directory), m[1]); - var op = pather.join(CONF.t,p.substring(CONF.i.length)) - var pathObj = { - name: m[1], - inputPath: p, - outputPath: op, - inputDir: directory, - outputDir: outify(directory) - } - DEPENDENCY_COUNT++; - if(!dependencies.includes(pathObj)) - dependencies.push(pathObj) - } - } - DEPENDENCIES[path]=dependencies; - FILES.push(path); - unqueueRead(); - } - } + 'use strict'; + queueRead(); + fs.readdir(directory, (err, items) => { + if (!Array.isArray(items)) { + throw 'Unable to read input directory.'; + } + for (var item of items) { + statItem(item); + } + unqueueRead(); + }); + function statItem(item) { + queueRead(); + var path = pather.join(directory, item); + fs.stat(path, (err, stats) => { + if (stats.isDirectory()) { + DIRECTORIES.push(path); + listTree(path); + unqueueRead(); + } else if (stats.isFile()) { + fs.readFile(path, 'utf-8', processFile); + } + }); + function processFile(err, body) { + var e = ATREG, + m, + dependencies = []; + var ext = path.match(/\.([a-z0-9]+)$/); + if (ext && CONF.e.includes(ext[1])) { + //console.log("MATCH",ext) + while ((m = e.exec(body))) { + var p = pathify(directory, m[1]); + //var op = pathify(outify(directory), m[1]); + var op = pather.join( + CONF.t, + p.substring(CONF.i.length) + ); + var pathObj = { + name: m[1], + inputPath: p, + outputPath: op, + inputDir: directory, + outputDir: outify(directory) + }; + DEPENDENCY_COUNT++; + if (!dependencies.includes(pathObj)) + dependencies.push(pathObj); + } + } + DEPENDENCIES[path] = dependencies; + FILES.push(path); + unqueueRead(); + } + } } function queueRead() { - ACTIVE_READS++; + ACTIVE_READS++; } function unqueueRead() { - ACTIVE_READS--; - if(!ACTIVE_READS) { - UNMET_DEPENDENCIES = JSON.parse(JSON.stringify(DEPENDENCIES)) - /*for(k of Object.keys(UNMET_DEPENDENCIES)) + ACTIVE_READS--; + if (!ACTIVE_READS) { + UNMET_DEPENDENCIES = JSON.parse( + JSON.stringify(DEPENDENCIES) + ); + /*for(k of Object.keys(UNMET_DEPENDENCIES)) for(d in UNMET_DEPENDENCIES[k]) UNMET_DEPENDENCIES[k][d].outed = outify(UNMET_DEPENDENCIES[k][d].path)*/ - //console.log("CONT", CONF, "DIRECTORIES", DIRECTORIES, "FILES", FILES,"DEPENDENCIES", DEPENDENCIES, "UNMET", UNMET_DEPENDENCIES); - passDependencies(); - } + //console.log("CONT", CONF, "DIRECTORIES", DIRECTORIES, "FILES", FILES,"DEPENDENCIES", DEPENDENCIES, "UNMET", UNMET_DEPENDENCIES); + passDependencies(); + } } var filesLeftInPass; var filesWrittenInPass; function passDependencies() { - filesLeftInPass = FILES.length; - filesWrittenInPass = 0; - for(var f of FILES) { - readFileInPass(f); - } - function readFileInPass(f) { - if(WRITTEN_FILES[f]) { - tryAnotherPass(); - return; - } - //console.log("PASSING", f, DEPENDENCIES[f]) - if(!UNMET_DEPENDENCIES[f].length) { - var fDepends = {}; - var fContents; - var reqs = DEPENDENCIES[f].length + 1; - fs.readFile(f, 'utf-8', (err, bod) => { - if(err) throw 'Error reading file.' - fContents = bod; - tryInterpolateFile(); - }) - for(var d of DEPENDENCIES[f]) { - readDependent(d); - } - function readDependent(d) { - fs.readFile(d.outputPath, 'utf-8', (err, bod) => { - if(err) throw 'Error reading dependent.'; - fDepends[d.outputPath] = bod; - tryInterpolateFile(); - }) - } - function tryInterpolateFile() { - reqs--; - if(!reqs) { - interpolateFile(f, fContents); - } else { - } - } + filesLeftInPass = FILES.length; + filesWrittenInPass = 0; + for (var f of FILES) { + readFileInPass(f); + } + function readFileInPass(f) { + if (WRITTEN_FILES[f]) { + tryAnotherPass(); + return; + } + //console.log("PASSING", f, DEPENDENCIES[f]) + if (!UNMET_DEPENDENCIES[f].length) { + var fDepends = {}; + var fContents; + var reqs = DEPENDENCIES[f].length + 1; + fs.readFile(f, 'utf-8', (err, bod) => { + if (err) throw 'Error reading file.'; + fContents = bod; + tryInterpolateFile(); + }); + for (var d of DEPENDENCIES[f]) { + readDependent(d); + } + function readDependent(d) { + fs.readFile( + d.outputPath, + 'utf-8', + (err, bod) => { + if (err) + throw 'Error reading dependent.'; + fDepends[d.outputPath] = bod; + tryInterpolateFile(); + } + ); + } + function tryInterpolateFile() { + reqs--; + if (!reqs) { + interpolateFile(f, fContents); + } else { + } + } - function interpolateFile(f) { - var reqs = DEPENDENCIES[f].length; - for(var d of DEPENDENCIES[f]) { - interpolateDependency(d); - } - if(!reqs){ - writeReplaced(); - } - function interpolateDependency(d) { - var fmatch=d.name;//d.substring(CONF.o.length).replace(/[\\\/]/g,'[\\\\\\\/]').replace('.','\\.') - //console.log("INTERPOLATING", f, d); - fs.readFile(d.outputPath,'utf-8',(err,bod) => { - var reg = new RegExp('(^|[^\\\\])(\\\\\\\\)*@@'+fmatch+'((?:\\\\\\\\)*@@|$)','gm'); - //console.log(reg); - fContents = fContents.replace(reg,"$1$2"+bod.replace(/\$/g,'KSFDJKDJIEJIKDJFKJEIFJKDJIEJFK')).replace(/KSFDJKDJIEJIKDJFKJEIFJKDJIEJFK/g,'$') - //well.......it works....... - reqs--; - if(!reqs) { - writeReplaced(); - } else { - } - }) - } - function writeReplaced() { - //console.log("WRITING REPLACED", fContents) - var derp = outify(f).match(/(.+[\/\\])/)[1];//(f.match(/(.+\/)/)||[null,])[1]); - mkdirp(derp,err=>{ - if(err) throw err; - //console.log(fContents) - fs.writeFile(outify(f), fContents, (err) => { - if(err)throw err - for(var k of Object.keys(UNMET_DEPENDENCIES)) { - for(d in UNMET_DEPENDENCIES[k]) { - /*if(f=="C:\\Users\\nikki\\documents\\github\\liot-r\\weave\\unwoven-site\\head.html")//&&UNMET_DEPENDENCIES[k][d].name=="/nav.html") + function interpolateFile(f) { + var reqs = DEPENDENCIES[f].length; + for (var d of DEPENDENCIES[f]) { + interpolateDependency(d); + } + if (!reqs) { + writeReplaced(); + } + function interpolateDependency(d) { + var fmatch = d.name; //d.substring(CONF.o.length).replace(/[\\\/]/g,'[\\\\\\\/]').replace('.','\\.') + //console.log("INTERPOLATING", f, d); + fs.readFile( + d.outputPath, + 'utf-8', + (err, bod) => { + var reg = new RegExp( + '(^|[^\\\\])(\\\\\\\\)*@@' + + fmatch + + '((?:\\\\\\\\)*@@|$)', + 'gm' + ); + //console.log(reg); + fContents = fContents + .replace( + reg, + '$1$2' + + bod.replace( + /\$/g, + 'KSFDJKDJIEJIKDJFKJEIFJKDJIEJFK' + ) + ) + .replace( + /KSFDJKDJIEJIKDJFKJEIFJKDJIEJFK/g, + '$' + ); + //well.......it works....... + reqs--; + if (!reqs) { + writeReplaced(); + } else { + } + } + ); + } + function writeReplaced() { + //console.log("WRITING REPLACED", fContents) + var derp = + outify(f).match(/(.+[\/\\])/)[1]; //(f.match(/(.+\/)/)||[null,])[1]); + mkdirp(derp, err => { + if (err) throw err; + //console.log(fContents) + fs.writeFile( + outify(f), + fContents, + err => { + if (err) throw err; + for (var k of Object.keys( + UNMET_DEPENDENCIES + )) { + for (d in UNMET_DEPENDENCIES[ + k + ]) { + /*if(f=="C:\\Users\\nikki\\documents\\github\\liot-r\\weave\\unwoven-site\\head.html")//&&UNMET_DEPENDENCIES[k][d].name=="/nav.html") console.log(f,UNMET_DEPENDENCIES[k][d].inputPath)*/ - //console.log("UNMET K", UNMET_DEPENDENCIES[k], "UNMET D", UNMET_DEPENDENCIES[k][d], "f", f, "OUTD", outify(f)) - if(UNMET_DEPENDENCIES[k][d].inputPath==f) { - //console.log("MATCHES") - UNMET_DEPENDENCIES[k].splice(d,1); - INTERPOLATED_COUNT++; - break; - } - } - } - WRITTEN_FILES[f] = true; - WRITTEN_FILE_COUNT++; - filesWrittenInPass++; - tryAnotherPass(); - }) - }) - } - } - } else { - tryAnotherPass(); - } - } + //console.log("UNMET K", UNMET_DEPENDENCIES[k], "UNMET D", UNMET_DEPENDENCIES[k][d], "f", f, "OUTD", outify(f)) + if ( + UNMET_DEPENDENCIES[ + k + ][d] + .inputPath == + f + ) { + //console.log("MATCHES") + UNMET_DEPENDENCIES[ + k + ].splice(d, 1); + INTERPOLATED_COUNT++; + break; + } + } + } + WRITTEN_FILES[f] = true; + WRITTEN_FILE_COUNT++; + filesWrittenInPass++; + tryAnotherPass(); + } + ); + }); + } + } + } else { + tryAnotherPass(); + } + } } function outify(d) { - //var out = CONF.t+(d.match(/([\/\\].+)/)||[0,"/"+d])[1] - //out = pather.resolve(out) - var out = d; - if(CONF.i==d.substring(0,CONF.i.length)) out = pather.join(CONF.o,d.substring(CONF.i.length+1)) - //console.log("OUTEDY", out) - //console.log("OUTIFY", d, CONF.i, out) - return out + //var out = CONF.t+(d.match(/([\/\\].+)/)||[0,"/"+d])[1] + //out = pather.resolve(out) + var out = d; + if (CONF.i == d.substring(0, CONF.i.length)) + out = pather.join( + CONF.o, + d.substring(CONF.i.length + 1) + ); + //console.log("OUTEDY", out) + //console.log("OUTIFY", d, CONF.i, out) + return out; } function pathify(directory, m) { - //console.log('PATHING',m,m[0].match(/[\/\\]/),pather.join(CONF.t,m)) - if(m[0].match(/[\/\\]/)) return pather.join(CONF.i,m)//.substring(1); - //console.log("STILL PATHING") - var t; - var path = (m.match(/(.+[\/\\])/)||[null,m])[1]; - var file = m.match(/[^\\\/]+$/)[1]; - while(path.substring(0,3)=='../') { - path=path.substring(3); - directory = directory.match(/(.+[\/\\])/)[1] - } - return pather.join(directory, m) + //console.log('PATHING',m,m[0].match(/[\/\\]/),pather.join(CONF.t,m)) + if (m[0].match(/[\/\\]/)) return pather.join(CONF.i, m); //.substring(1); + //console.log("STILL PATHING") + var t; + var path = (m.match(/(.+[\/\\])/) || [null, m])[1]; + var file = m.match(/[^\\\/]+$/)[1]; + while (path.substring(0, 3) == '../') { + path = path.substring(3); + directory = directory.match(/(.+[\/\\])/)[1]; + } + return pather.join(directory, m); } function tryAnotherPass() { - filesLeftInPass--; - if(filesLeftInPass==0) { - if(filesWrittenInPass) { - //setTimeout(passDependencies,1000) - passDependencies(); - } else { - var t = ''; - var failed; - for(var k of Object.keys(UNMET_DEPENDENCIES)) { - if(UNMET_DEPENDENCIES[k].length) { - failed = true; - t+=k.match(/([\/\\].+)/)[1]+":" - for(var d of UNMET_DEPENDENCIES[k]) - t+='\n->\t'+d.name;//match(/([\/\\].+)/)[1]; - t+='\n'; - } - } - if(failed) { - clearTimeout(updateInterval) - updateProgress(); - console.log('\nNonexistent dependencies or loop discovered.') - console.log(t) - } else { - updateProgress() - console.log("\nSuccess!") - clearTimeout(updateInterval) - } - } - } + filesLeftInPass--; + if (filesLeftInPass == 0) { + if (filesWrittenInPass) { + //setTimeout(passDependencies,1000) + passDependencies(); + } else { + var t = ''; + var failed; + for (var k of Object.keys(UNMET_DEPENDENCIES)) { + if (UNMET_DEPENDENCIES[k].length) { + failed = true; + t += k.match(/([\/\\].+)/)[1] + ':'; + for (var d of UNMET_DEPENDENCIES[k]) + t += '\n->\t' + d.name; //match(/([\/\\].+)/)[1]; + t += '\n'; + } + } + if (failed) { + clearTimeout(updateInterval); + updateProgress(); + console.log( + '\nNonexistent dependencies or loop discovered.' + ); + console.log(t); + } else { + updateProgress(); + console.log('\nSuccess!'); + clearTimeout(updateInterval); + } + } + } } -var LAST_STATUS = null -function updateProgress(){ - var status = `\rWeaves: ${INTERPOLATED_COUNT} of ${DEPENDENCY_COUNT} | Written: ${WRITTEN_FILE_COUNT} of ${FILES.length} `; - if(status !=LAST_STATUS) { - LAST_STATUS = status; - process.stdout.write(status) - } - //console.log(`Weaves: ${INTERPOLATED_COUNT} of ${DEPENDENCY_COUNT}`) - if(WRITTEN_FILE_COUNT==FILES.length) { - //clearTimeout(updateInterval) - } +var LAST_STATUS = null; +function updateProgress() { + var status = `\rWeaves: ${INTERPOLATED_COUNT} of ${DEPENDENCY_COUNT} | Written: ${WRITTEN_FILE_COUNT} of ${FILES.length} `; + if (status != LAST_STATUS) { + LAST_STATUS = status; + process.stdout.write(status); + } + //console.log(`Weaves: ${INTERPOLATED_COUNT} of ${DEPENDENCY_COUNT}`) + if (WRITTEN_FILE_COUNT == FILES.length) { + //clearTimeout(updateInterval) + } } -var updateInterval = setInterval(updateProgress, 1) +var updateInterval = setInterval(updateProgress, 1);