diff --git a/clusterctl.js b/clusterctl.js index 7f1161f7..b1ae99bd 100644 --- a/clusterctl.js +++ b/clusterctl.js @@ -69,7 +69,7 @@ class Command { } async run(args, control) { - await this._handler.call(this, args, control); + await this._handler(args, control); } } diff --git a/lib/config/classes.js b/lib/config/classes.js index 7aaf1890..ca369270 100644 --- a/lib/config/classes.js +++ b/lib/config/classes.js @@ -395,7 +395,7 @@ class ConfigGroup { value = Number.parseFloat(value); } - } else if (def.type === "object" ) { + } else if (def.type === "object") { try { value = JSON.parse(value); } catch (err) { @@ -409,10 +409,8 @@ class ConfigGroup { throw new InvalidValue(`Field ${name} cannot be null`); } - } else { - if (basicType(value) !== def.type) { - throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`); - } + } else if (basicType(value) !== def.type) { + throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`); } let prev = this._fields.get(name); @@ -493,10 +491,9 @@ class ConfigGroup { if (value !== null && basicType(value) !== def.type) { continue; } - } else { - if (basicType(value) !== def.type) { - continue; - } + + } else if (basicType(value) !== def.type) { + continue; } if (def.enum && !def.enum.includes(value)) { @@ -655,10 +652,11 @@ class ConfigGroup { throw new Error(`Config field ${item.name} has already been defined`); } - let computed = Object.assign({ + let computed = { optional: false, fullName: `${this.groupName}.${item.name}`, - }, item); + ...item, + }; if (!computed.optional && computed.initial_value === undefined) { throw new Error(`Non-optional field ${item.name} needs an initial_value`); diff --git a/lib/database.js b/lib/database.js index 76394c3a..74b59853 100644 --- a/lib/database.js +++ b/lib/database.js @@ -144,7 +144,6 @@ async function saveMapAsJsonArray(filePath, map) { } - function checkName(name) { if (typeof name !== "string") { throw new Error("name must be a string"); diff --git a/lib/factorio/export.js b/lib/factorio/export.js index 8f6e72c6..c1ac3da5 100644 --- a/lib/factorio/export.js +++ b/lib/factorio/export.js @@ -196,6 +196,7 @@ async function exportItems(server, modVersions, items) { iconLayer.scale(realScale); } + // eslint-disable-next-line no-loop-func iconLayer.scan(0, 0, iconLayer.bitmap.width, iconLayer.bitmap.height, function(x, y, sidx) { x += xs; y += ys; diff --git a/lib/factorio/server.js b/lib/factorio/server.js index 0ca12a86..9b2a033b 100644 --- a/lib/factorio/server.js +++ b/lib/factorio/server.js @@ -167,9 +167,9 @@ function randomDynamicPort() { async function generatePassword(length) { function validChar(byte) { const ranges = ["az", "AZ", "09"]; - return ranges.some(range => + return ranges.some(range => ( range.codePointAt(0) <= byte && byte <= range.codePointAt(1) - ); + )); } let randomBytesAsync = util.promisify(crypto.randomBytes); @@ -559,9 +559,9 @@ class FactorioServer extends events.EventEmitter { let channel = line .slice(6, channelEnd) .toString("utf-8") - .replace(/\\x([0-9a-f]{2})/g, (match, p1) => + .replace(/\\x([0-9a-f]{2})/g, (match, p1) => ( String.fromCharCode(parseInt(p1, 16)) - ) + )) ; let type = line.slice(channelEnd + 1, channelEnd + 2).toString("utf-8"); @@ -619,10 +619,8 @@ class FactorioServer extends events.EventEmitter { if (!expected.includes(output[name])) { continue heuristicLoop; } - } else { - if (expected !== output[name]) { - continue heuristicLoop; - } + } else if (expected !== output[name]) { + continue heuristicLoop; } } @@ -651,7 +649,7 @@ class FactorioServer extends events.EventEmitter { }; this._rconClient = new rconClient.Rcon(config); - this._rconClient.on("error", err => { /* Ignore */ }); + this._rconClient.on("error", () => { /* Ignore */ }); this._rconClient.on("authenticated", () => { this._rconReady = true; this.emit("rcon-ready"); }); this._rconClient.on("end", () => { this._rconClient = null; diff --git a/lib/fileOps/index.js b/lib/fileOps/index.js index 58f925fe..0e9bcbe8 100644 --- a/lib/fileOps/index.js +++ b/lib/fileOps/index.js @@ -1,3 +1,3 @@ "use strict"; const fileOps = require("./fileOps"); -module.exports = fileOps; \ No newline at end of file +module.exports = fileOps; diff --git a/lib/link/connectors.js b/lib/link/connectors.js index 75682dd6..a7997f0a 100644 --- a/lib/link/connectors.js +++ b/lib/link/connectors.js @@ -310,18 +310,6 @@ class WebSocketClientConnector extends WebSocketBaseConnector { console.error("SOCKET | Error:", err); }); - /* - this._socket.on("unexpected-response", (req, res) => { - let data = ""; - res.on('data', (chunk) => { data += chunk; }); - res.on('end', () => { - console.error(`SOCKET | Unexpeced Response ${res.statusCode}`); - console.error(data); - this._socket.emit("error", new Error(`Unexpected Response ${res.statusCode}`)); - }); - }); - */ - this._socket.on("open", () => { console.log("SOCKET | Open"); }); diff --git a/lib/link/messages.js b/lib/link/messages.js index 85c0e9d3..fd0d0876 100644 --- a/lib/link/messages.js +++ b/lib/link/messages.js @@ -11,8 +11,8 @@ const errors = require("lib/errors"); class Message { /** * Name of the plugin this message belongs to, or null. - * @returns {?string} - **/ + * @returns {?string} - plugin name or null if not from a plugin. + */ get plugin() { if (this._plugin === undefined) { let index = this.type.indexOf(":"); @@ -78,9 +78,10 @@ class Request extends Message { } if (forwardTo === "instance") { - requestProperties = Object.assign( - { "instance_id": { type: "integer" }}, requestProperties - ); + requestProperties = { + "instance_id": { type: "integer" }, + ...requestProperties, + }; } else if (forwardTo !== "master" && forwardTo !== null) { throw new Error(`Invalid forwardTo value ${forwardTo}`); @@ -635,9 +636,10 @@ class Event extends Message { this.broadcastTo = broadcastTo; if (forwardTo === "instance") { - eventProperties = Object.assign( - { "instance_id": { type: "integer" }}, eventProperties - ); + eventProperties = { + "instance_id": { type: "integer" }, + ...eventProperties, + }; } else if (forwardTo !== "master" && forwardTo !== null) { throw new Error(`Invalid forwardTo value ${forwardTo}`); diff --git a/lib/manager/modManager.js b/lib/manager/modManager.js index 8dc0fabb..19fb28ac 100644 --- a/lib/manager/modManager.js +++ b/lib/manager/modManager.js @@ -1,3 +1,5 @@ +// This file will be rewritten from scratch +/* eslint-disable */ /** Provides tools to manage mods in a clusterio install @module diff --git a/lib/npmPostinstall.js b/lib/npmPostinstall.js index 4c88a1b2..cc23a327 100644 --- a/lib/npmPostinstall.js +++ b/lib/npmPostinstall.js @@ -26,7 +26,7 @@ function download(url, file, callback){ // this might be an invalid path! fs.stat(pathArray.join("/"), (err, stat) => { if(err){ - makeDirectory(pathArray.join("/")).then(()=>{ + makeDirectory(pathArray.join("/")).then(() => { doDownload(url, file, callback); }); } else { @@ -82,7 +82,7 @@ let downloadList = [ // initiate folder creations and downloads function processMkdirRecursive(callback){ let item = directories.shift(); - makeDirectory(item).then(()=>{ + makeDirectory(item).then(() => { if(directories.length == 0){ if(callback) callback(); } else { @@ -92,7 +92,7 @@ function processMkdirRecursive(callback){ } function processDownloadRecursive(callback){ let item = downloadList.shift(); - download(item.url, item.file, item.callback).then(()=>{ + download(item.url, item.file, item.callback).then(() => { if(downloadList.length == 0){ if(callback) callback(); } else { diff --git a/lib/objectOps.js b/lib/objectOps.js index 5968d543..1fe093cc 100644 --- a/lib/objectOps.js +++ b/lib/objectOps.js @@ -1,35 +1,36 @@ /** -Helper functions related to objects -@module -*/ + * Helper functions related to objects + * @module + */ "use strict"; /** -Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner. -@param {object} obj to clone -@returns {object} The cloned object. - -@example -a = {"thingy":"with a value"}; -b = a; -a == b; // true -c = objectOps.deepclone(a); -a == c; // false -*/ + * Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner. + * @param {object} obj to clone + * @returns {object} The cloned object. + * + * @example + * a = {"thingy":"with a value"}; + * b = a; + * a == b; // true + * c = objectOps.deepclone(a); + * a == c; // false + */ module.exports.deepclone = function(obj){ return JSON.parse(JSON.stringify(obj)); }; -/** -Checks if a string is valid JSON using try/catch. If passed an object it will always return true. -@param {string} string to verify -@returns {boolean} true if valid JSON. -@example -objectOps.isJSON("99 bottles of beer"); // false -objectOps.isJSON("99"); // true -objectOps.isJSON({"thingy":"that is an object"}); // true -objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true -*/ +/** + * Checks if a string is valid JSON using try/catch. If passed an object it will always return true. + * @param {string} string to verify + * @returns {boolean} true if valid JSON. + * + * @example + * objectOps.isJSON("99 bottles of beer"); // false + * objectOps.isJSON("99"); // true + * objectOps.isJSON({"thingy":"that is an object"}); // true + * objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true + */ module.exports.isJSON = function(string){ let stringIsJson = false; let x; diff --git a/lib/prometheus.js b/lib/prometheus.js index 236a0d82..b461d60d 100644 --- a/lib/prometheus.js +++ b/lib/prometheus.js @@ -167,9 +167,9 @@ class ValueCollector extends Collector { function removeMatchingLabels(mapping, labels) { for (let key of mapping.keys()) { let candidate = keyToLabels(key); - let hasLabels = Object.entries(labels).every(([name, value]) => { - return candidate.get(name) === value; - }); + let hasLabels = Object.entries(labels).every(([name, value]) => ( + candidate.get(name) === value + )); if (hasLabels) { mapping.delete(key); } diff --git a/lib/schema.js b/lib/schema.js index 867f2497..66f038bd 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -74,7 +74,7 @@ const serverHandshake = ajv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "Server Handshake", description: "Message sent from the server to a client during the handshake", - allOf: [ messageSchema ], + allOf: [messageSchema], anyOf: [ { properties: { @@ -137,7 +137,7 @@ const clientHandshake = ajv.compile({ $schema: "http://json-schema.org/draft-07/schema#", title: "Client Message", description: "Message sent from a client to the server", - allOf: [ messageSchema ], + allOf: [messageSchema], anyOf: [ { properties: { diff --git a/master.js b/master.js index 1b8bc7c1..234bd8bc 100644 --- a/master.js +++ b/master.js @@ -535,7 +535,7 @@ class BaseConnection extends link.Link { } } -let controlConnections = new Array(); +let controlConnections = []; class ControlConnection extends BaseConnection { constructor(registerData, connector, user) { super("control", connector); @@ -560,7 +560,7 @@ class ControlConnection extends BaseConnection { this.ws_dumper = null; this.connector.on("connect", () => { - this.connector._socket.clusterio_ignore_dump = !!this.ws_dumper; + this.connector._socket.clusterio_ignore_dump = Boolean(this.ws_dumper); }); this.connector.on("close", () => { if (this.ws_dumper) { @@ -880,6 +880,7 @@ class SlaveConnection extends BaseConnection { }); for (let event of ["connect", "drop", "close"]) { + // eslint-disable-next-line no-loop-func this.connector.on(event, () => { for (let masterPlugin of masterPlugins.values()) { masterPlugin.onSlaveConnectionEvent(this, event); @@ -991,7 +992,7 @@ const wss = new WebSocket.Server({ * 231-1. */ function isInteger(value) { - return value | 0 === value; + return (value | 0) === value; } diff --git a/plugins/research_sync/master.js b/plugins/research_sync/master.js index 060b19e6..a6f0cbd4 100644 --- a/plugins/research_sync/master.js +++ b/plugins/research_sync/master.js @@ -112,7 +112,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin { } for (let instanceTech of message.data.technologies) { - let [name, level, progress, researched] = instanceTech; + let [name, level, progress, researched] = instanceTech; let tech = this.technologies.get(name); if (!tech) { this.technologies.set(name, { level, progress, researched }); @@ -152,7 +152,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin { let technologies = []; for (let [name, tech] of this.technologies) { - technologies.push([ name, tech.level, tech.progress, tech.researched ]); + technologies.push([name, tech.level, tech.progress, tech.researched]); } return { technologies }; diff --git a/plugins/subspace_storage/dole.js b/plugins/subspace_storage/dole.js index 60db186b..fe06bb3a 100644 --- a/plugins/subspace_storage/dole.js +++ b/plugins/subspace_storage/dole.js @@ -16,7 +16,7 @@ const prometheusDoleFactorGauge = new prometheus.Gauge( ); class neuralDole { - + getRequestStats(itemname,samples) { var sum=0; @@ -28,7 +28,7 @@ class neuralDole { if (sum==0) return 0.1; return sum/samples; } - + constructor({ items, }){ @@ -41,6 +41,7 @@ class neuralDole { this.stats=[]; this.debt= {}; } + doMagic() { for (let [name, count] of this.items._items) { let magicData = doleNN.Tick( @@ -50,7 +51,7 @@ class neuralDole { this.getRequestStats(name,5) ); this.stats[name]=this.stats[name] || []; - this.stats[name].unshift({ req:0,given:0 });//stats[name][0] is the one we currently collect + this.stats[name].unshift({ req: 0, given: 0 });//stats[name][0] is the one we currently collect if (this.stats[name].length>10) this.stats[name].pop();//remove if too many samples in stats this.dole[name] = magicData[0]; @@ -59,6 +60,7 @@ class neuralDole { } this.itemsLastTick = new Map(this.items._items); } + divider(object) { let magicData = doleNN.Dose( object.count, // numReq @@ -100,7 +102,7 @@ function doleDivider({ let itemCount = items.getItemCount(object.name); const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings const maxDoleDivision = 250; //a higher cap will divide the store more ways, but will take longer to recover as supplies increase - + const originalCount = Number(object.count) || 0; object.count /= ((_doleDivisionFactor[object.name]||0)+doleDivisionRetardation)/doleDivisionRetardation; object.count = Math.round(object.count); @@ -128,4 +130,4 @@ function doleDivider({ module.exports = { doleDivider, neuralDole, -}; \ No newline at end of file +}; diff --git a/plugins/subspace_storage/dole_nn_base.js b/plugins/subspace_storage/dole_nn_base.js index 314b1931..dc978ebc 100644 --- a/plugins/subspace_storage/dole_nn_base.js +++ b/plugins/subspace_storage/dole_nn_base.js @@ -47,7 +47,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad instore=Number(instore); var instore_adj=instore; if (instore_adj==0) instore_adj=0.1; - + var b=Math.trunc(prev_req/instore_adj*numreq); var inp1=[numreq,instore_adj,store_last_tick/numreq,dole,carry];//0..4 var inp2=[prev_req/numreq,numreq/numreq_total_adj,store_last_tick/numreq_total_adj,prev_req/instore_adj,b,numreq_total_adj,store_last_tick,debt];//5..12 @@ -55,7 +55,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad var internal=new Array(20).fill(0); var outputs=[0,0,0,0]; //NN: Please don't touch :), code is generated - + outputs[0]=inputs[7]*0.8058582544; outputs[0]=sigmoid2(outputs[0]); outputs[1]=sigmoid0(outputs[1]); @@ -65,20 +65,20 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad debt=debt || 0; if (outputs[0]>0.99) outputs[0]=1.0; - + var res1=Number(outputs[0])*numreq+outputs[3]+debt; var res_capped=Math.round(res1); - + if (res_capped>numreq) res_capped=numreq; if (res_capped>instore) res_capped=instore; if (res_capped<0) res_capped=0; - + res1=res1 || 0; res_capped=res_capped || 0;//Safeguard against wrong values debt=res1-res_capped; debt_cap=Math.round(numreq*1.5)+5; if (debt>debt_cap) debt=debt_cap; - + carry=sigmoid0(outputs[2]*carry+outputs[0]) || 0; return [res_capped,dole+outputs[1],carry,debt]; } @@ -102,9 +102,9 @@ function Tick(instore,dole,store_last_tick,numreq_total_adj) var internal=new Array(10).fill(0); var outputs=[0,0]; //NN: Please don't touch :), code is generated - + outputs[0]=inputs[3]*0.9364774823; - outputs[0]=outputs[0]*1.0*0.4590721726; + outputs[0]=outputs[0]*0.4590721726; outputs[0]=sigmoid2(outputs[0]); outputs[1]=outputs[0]*1.828422785; outputs[1]=sigmoid3(outputs[1]); @@ -113,8 +113,8 @@ function Tick(instore,dole,store_last_tick,numreq_total_adj) if (numreq_total_adj<0.11) avg=1;//When no item's are requested, result is 0.1 ; In that case there is no deficit, so return 1 = 100% demand fulfilled if (avg>1) avg=1; if (avg<0) avg=0; - + return [sigmoid0(outputs[0]),avg]; } -module.exports = { Dose,Tick }; \ No newline at end of file +module.exports = { Dose,Tick }; diff --git a/plugins/subspace_storage/static/storage.js b/plugins/subspace_storage/static/storage.js index f20f1bac..a2f9157d 100644 --- a/plugins/subspace_storage/static/storage.js +++ b/plugins/subspace_storage/static/storage.js @@ -13,24 +13,24 @@ function drawcontents(data) { data = data.filter(function(item) { return search.test(item.name); }); - + sortByKey(data, "count"); - + const table = document.querySelector("#contents tbody"); //tables have tbody inserted automatically const rows = table.children; - + //update existing rows or create new ones data.forEach(function(item, i) { // format count to have .s in it for large number readability (1,000,000) item.count = item.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); - + let row = rows[i]; if(!row) { row = document.createElement("tr"); row.innerHTML = "
"; table.appendChild(row); } - + const itemIcon = row.querySelector("div"); const iconClass = getItemIconClass(item.name); if (itemIcon.getAttribute("class") !== iconClass) { @@ -56,13 +56,13 @@ function drawcontents(data) { if(name.textContent !== localeName) { name.textContent = localeName; } - + const count = row.querySelector(".count"); - if(count.textContent !== ""+item.count) { + if(count.textContent !== String(item.count)) { count.textContent = item.count; } }); - + //remove excess rows, for example, after filtering while (data.length < rows.length) { table.removeChild(rows[data.length]); diff --git a/routes.js b/routes.js index 92c37c02..1b3c7c92 100644 --- a/routes.js +++ b/routes.js @@ -12,4 +12,4 @@ module.exports = function(app) { app.get("/nodeDetails", function(req, res) { res.render("nodeDetails"); }); -}; \ No newline at end of file +}; diff --git a/slave.js b/slave.js index 62b199eb..41466a2f 100644 --- a/slave.js +++ b/slave.js @@ -23,7 +23,6 @@ const version = require("./package").version; // internal libraries const fileOps = require("lib/fileOps"); -const hashFile = require("lib/hash").hashFile; const factorio = require("lib/factorio"); const link = require("lib/link"); const plugin = require("lib/plugin"); @@ -88,7 +87,7 @@ const serverSettingsActions = { "game_password": applyAsConfig("password"), "require_user_verification": applyAsConfig("require-user-verification"), "tags": applyAsConfig("tags"), - "visibility": async function action(server, value) { + "visibility": async (server, value) => { for (let scope of ["lan", "public", "steam"]) { try { let enabled = Boolean(value[scope]); @@ -352,13 +351,14 @@ class Instance extends link.Link{ throw new Error(`Expected name of module for plugin ${pluginName} to match the plugin name`); } - module = Object.assign({ + module = { version: plugin.info.version, dependencies: { "clusterio": "*" }, path: modulePath, load: [], require: [], - }, module); + ...module, + }; modules.set(module.name, module); } @@ -380,12 +380,13 @@ class Instance extends link.Link{ throw new Error(`Expected name of module ${entry.name} to match the directory name`); } - module = Object.assign({ + module = { path: path.join("modules", entry.name), dependencies: { "clusterio": "*" }, load: [], require: [], - }, module); + ...module, + }; modules.set(module.name, module); } } @@ -754,7 +755,7 @@ class Slave extends link.Link { console.error(err); process.exit(1); }); - });; + }); }); this.connector.on("close", () => { @@ -874,10 +875,10 @@ class Slave extends link.Link { // save a copy of the instance config - let warnedOutput = Object.assign( - { _warning: "Changes to this file will be overwritten by the master server's copy." }, - instanceInfo.config.serialize() - ); + let warnedOutput = { + _warning: "Changes to this file will be overwritten by the master server's copy.", + ...instanceInfo.config.serialize(), + }; await fs.outputFile( path.join(instanceInfo.path, "instance.json"), JSON.stringify(warnedOutput, null, 4) @@ -1237,37 +1238,6 @@ async function startSlave() { }); await slaveConnector.connect(); - - /* - } else if (command == "manage"){ - await manage(config, instance); - // process.exit(0); - */ -} - -// string, function -// returns [{modName:string,hash:string}, ... ] -function hashMods(instance, callback) { - if(!callback) { - throw new Error("ERROR in function hashMods NO CALLBACK"); - } - - function hashMod(name) { - if (path.extname(name) != ".zip") { - // Can't hash unzipped mods, return null that's filtered out later - return null; - } else { - return hashFile(instance.path("mods", name)).then(hash => ( - { modName: name, hash: hash } - )); - } - } - - let promises = fs.readdirSync(instance.path("mods")).map(hashMod); - Promise.all(promises).then(hashes => { - // Remove null entries from hashMod - callback(hashes.filter(entry => entry !== null)); - }); } module.exports = { diff --git a/test/integration/clusterio.js b/test/integration/clusterio.js index fccc15bf..73b5ee4e 100644 --- a/test/integration/clusterio.js +++ b/test/integration/clusterio.js @@ -156,7 +156,7 @@ describe("Integration of Clusterio", function() { ], ]; - for (let [prop, value, , ] of testConfigs) { + for (let [prop, value, ,] of testConfigs) { value = `"'${JSON.stringify(value).replace(/"/g, process.platform === "win32" ? '""' : '\\"')}'"`; let args = `--instance test --field factorio.settings --prop ${prop} --value ${value}`; await exec(`node clusterctl --config ${controlConfigPath} set-instance-config-prop ${args}`); diff --git a/test/integration/index.js b/test/integration/index.js index 88777a2e..c7305c0a 100644 --- a/test/integration/index.js +++ b/test/integration/index.js @@ -23,6 +23,7 @@ class TestControl extends link.Link { } async debugWsMessageEventHandler() { } + async instanceOutputEventHandler() { } } @@ -35,6 +36,7 @@ class TestControlConnector extends link.WebSocketClientConnector { // Mark that this test takes a lot of time, or depeneds on a test // that takes a lot of time. function slowTest(test) { + // eslint-disable-next-line no-process-env if (process.env.FAST_TEST) { test.skip(); } diff --git a/test/integration/server.js b/test/integration/server.js index 93c71a88..810570c1 100644 --- a/test/integration/server.js +++ b/test/integration/server.js @@ -27,7 +27,7 @@ describe("Integration of lib/factorio/server", function() { before(async function() { // Delete result from previous run of these tests - if (fs.existsSync(writePath)) { + if (await fs.pathExists(writePath)) { await fs.remove(writePath); } diff --git a/test/lib/config/classes.js b/test/lib/config/classes.js index fa4b0e24..802a8860 100644 --- a/test/lib/config/classes.js +++ b/test/lib/config/classes.js @@ -287,7 +287,7 @@ describe("lib/config/classes", function() { }); it("should work if field is in enum", function() { - testInstance.set("enum", "c"), + testInstance.set("enum", "c"); assert.equal(testInstance.get("enum"), "c"); }); @@ -299,7 +299,7 @@ describe("lib/config/classes", function() { }); it("should work if field is optional", function() { - testInstance.set("test", "spam"), + testInstance.set("test", "spam"); assert.equal(testInstance.get("test"), "spam"); }); @@ -311,7 +311,7 @@ describe("lib/config/classes", function() { }); it("should treat empty string as null", function() { - testInstance.set("test", ""), + testInstance.set("test", ""); assert.equal(testInstance.get("test"), null); }); @@ -451,7 +451,8 @@ describe("lib/config/classes", function() { }); it("should construct a finalized class", function() { TestConfig.finalize(); - new TestConfig(); + let config = new TestConfig(); + assert(config); }); }); diff --git a/test/lib/database.js b/test/lib/database.js index ec0bd781..2b4670bc 100644 --- a/test/lib/database.js +++ b/test/lib/database.js @@ -13,7 +13,7 @@ describe("lib/database", function() { new Error("Expected all keys to be string but got number") ); assert.throws( - () => database.mapToObject(new Map([[Symbol(), 1]])), + () => database.mapToObject(new Map([[Symbol("test"), 1]])), new Error("Expected all keys to be string but got symbol") ); }); diff --git a/test/lib/factorio/export.js b/test/lib/factorio/export.js index 1e891ab7..d4ce5691 100644 --- a/test/lib/factorio/export.js +++ b/test/lib/factorio/export.js @@ -18,5 +18,5 @@ describe("lib/factorio/export", function() { let locale = await factorio._exportLocale(testServer, new Map(), ["base"], "en"); assert.deepEqual(locale, new Map([["test.key-a", "1"], ["test.key-b", "2"]])); }); - });; + }); }); diff --git a/test/lib/factorio/server.js b/test/lib/factorio/server.js index e0b8a1b7..f42438e0 100644 --- a/test/lib/factorio/server.js +++ b/test/lib/factorio/server.js @@ -93,7 +93,7 @@ describe("lib/factorio/server", function() { it("should return a port number in the dynamic range", function() { function validate(port) { - return 49152 <= port && port <= 65535; + return (49152 <= port && port <= 65535); } for (let i=0; i < 20; i++) { assert(validate(factorio._randomDynamicPort())); diff --git a/test/lib/generateSSLcert.js b/test/lib/generateSSLcert.js index 76e63d27..e64e6b43 100644 --- a/test/lib/generateSSLcert.js +++ b/test/lib/generateSSLcert.js @@ -5,7 +5,7 @@ const path = require("path"); const generateSSLcert = require("lib/generateSSLcert"); -describe("generateSSLcert.js(options)", ()=>{ +describe("generateSSLcert.js(options)", function() { let testDir = path.join("temp", "test", "certTest"); before(async function() { await fs.remove(testDir); @@ -13,6 +13,7 @@ describe("generateSSLcert.js(options)", ()=>{ it("Creates a folder with a .crt and .key file in it", async function() { this.timeout(1000); + // eslint-disable-next-line no-process-env if (process.env.FAST_TEST) { this.skip(); } diff --git a/test/lib/link/connector.js b/test/lib/link/connector.js index eba33d4f..4d650d67 100644 --- a/test/lib/link/connector.js +++ b/test/lib/link/connector.js @@ -81,7 +81,7 @@ describe("lib/link/connectors", function() { describe(".processHandshake()", function() { it("should close on invalid message", function() { testConnector._socket.closeCalled = false; - testConnector._processHandshake({ data: "invalid message" }), + testConnector._processHandshake({ data: "invalid message" }); assert(testConnector._socket.closeCalled, "Close was not called on the socket"); }); it("should call register on hello", function() { diff --git a/test/lib/link/link.js b/test/lib/link/link.js index 56188406..9b860673 100644 --- a/test/lib/link/link.js +++ b/test/lib/link/link.js @@ -56,7 +56,7 @@ describe("lib/link/link", function() { ); }); it("should set the handler", function() { - let handler = (message) => {}; + function handler(message) { } testLink.setHandler("handler_test", handler, (message) => true); assert.equal(testLink._handlers.get("handler_test"), handler); }); diff --git a/test/lib/link/messages.js b/test/lib/link/messages.js index 852ade02..25817638 100644 --- a/test/lib/link/messages.js +++ b/test/lib/link/messages.js @@ -45,7 +45,7 @@ describe("lib/link/messages", function() { let handlerResult; it("should attach handler to a target link", function() { - testRequest.attach(testTargetLink, async (message) => handlerResult ); + testRequest.attach(testTargetLink, async (message) => handlerResult); assert(testTargetLink._handlers.has("test_request"), "Handler was not set"); }); it("should send result of calling the handler", async function() { @@ -83,9 +83,7 @@ describe("lib/link/messages", function() { testSourceLink.connector.send = (type, data) => { request = { type, data }; }; - testSourceLink.waitFor = (type, condition) => { - return { data: { type, request }}; - }; + testSourceLink.waitFor = (type, condition) => ({ data: { type, request }}); assert.deepEqual( await testRequest.send(testSourceLink, { test: "request" }), { type: "test_response", request: { type: "test_request", data: { test: "request" }}} @@ -94,9 +92,7 @@ describe("lib/link/messages", function() { delete testSourceLink.waitFor; }); it("should throw error response", async function() { - testSourceLink.waitFor = (type, condition) => { - return { data: { error: "test error" }}; - }; + testSourceLink.waitFor = (type, condition) => ({ data: { error: "test error" }}); await assert.rejects( testRequest.send(testSourceLink, { test: "blah" }), new errors.RequestError("test error") diff --git a/test/lib/objectOps.js b/test/lib/objectOps.js index 72bdf161..8ce2a769 100644 --- a/test/lib/objectOps.js +++ b/test/lib/objectOps.js @@ -3,31 +3,12 @@ var assert = require("assert"); var objectOps = require("lib/objectOps"); describe("objectOps.js", function(){ - /*describe("objectOps.clone()", function(){ - it("clones javascript objects", function(){ - var object1 = {hello:"world", cat:{legs:4, name:"Kitty", colors:["brown", "yellow", "purple"]}}; - var object2 = {}; - object2 = objectOps.clone(object1); - - assert.equal(object2.cat.name, object1.cat.name) - assert.equal(object1.hello, object2.hello) - }); - it("does not deep clone objects", function(){ - var obj1 = {hello:"world", cat:{legs:4, name:"Kitty", colors:["brown", "yellow", "purple"]}}; - var obj2 = {}; - obj2 = objectOps.clone(obj1); - - obj1.cat.colors = "black"; - assert.equal(obj1.cat.colors, "black"); - assert.notEqual(obj2.cat.colors[1], "yellow"); - }); - });*/ describe("objectOps.deepclone()", function(){ it("deep clones javascript objects", function(){ - var obj1 = { hello:"world", cat:{ legs:4, name:"Kitty", colors:["brown", "yellow", "purple"] }}; + var obj1 = { hello: "world", cat: { legs: 4, name: "Kitty", colors: ["brown", "yellow", "purple"] }}; var obj2 = {}; obj2 = objectOps.deepclone(obj1); - + obj1.cat.colors = "black"; assert.equal(obj1.cat.colors, "black"); assert.equal(obj2.cat.colors[1], "yellow"); @@ -38,4 +19,4 @@ describe("objectOps.js", function(){ }); }); }); -}); \ No newline at end of file +}); diff --git a/test/lib/plugin.js b/test/lib/plugin.js index 8d4a7dcf..f1122edc 100644 --- a/test/lib/plugin.js +++ b/test/lib/plugin.js @@ -103,7 +103,7 @@ describe("lib/plugin", function() { plugin.attachPluginMessages(mockLink, {}, null); }); it("should attach handler for the given message", function() { - let mockEventEventHandler = function() {}; + function mockEventEventHandler() { }; plugin.attachPluginMessages(mockLink, { name: "test", messages: { mockEvent }}, { mockEventEventHandler }); assert(mockLink._handlers.get("test:test_event"), "handler was not registered"); }); diff --git a/test/lib/prometheus.js b/test/lib/prometheus.js index 9f5f96b9..d1602c47 100644 --- a/test/lib/prometheus.js +++ b/test/lib/prometheus.js @@ -523,7 +523,7 @@ describe("lib/prometheus", function() { let serializedResult = { metric: { type: "type", name: "name", help: "Help", labels: ["a", "b"] }, - samples: [ ['a="1",b="2"', 1], ['a="3",b="4"', 5] ], + samples: [['a="1",b="2"', 1], ['a="3",b="4"', 5]], }; let deserializedResult = { metric: new prometheus.Metric("type", "name", "Help", ["a", "b"]),