Add eslint and fix reported issues

This commit is contained in:
Juanjo Diaz 2018-05-24 00:25:44 +03:00
parent cfe1e44ed7
commit 8727f598c2
36 changed files with 134 additions and 108 deletions

14
.eslintrc Normal file
View File

@ -0,0 +1,14 @@
{
"env": {
"browser": true,
"es6": true
},
"parserOptions": {
"sourceType": "module"
},
"extends": "eslint:recommended",
"rules": {
"no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": true }],
"no-constant-condition": ["error", { "checkLoops": false }]
}
}

View File

@ -48,7 +48,8 @@ Localizer.prototype = {
}
// First pass: perfect match
for (var j = 0;j < supportedLanguages.length;j++) {
var j;
for (j = 0; j < supportedLanguages.length; j++) {
var supLang = supportedLanguages[j];
supLang = supLang.toLowerCase();
supLang = supLang.replace("_", "-");
@ -64,7 +65,7 @@ Localizer.prototype = {
}
// Second pass: fallback
for (var j = 0;j < supportedLanguages.length;j++) {
for (j = 0;j < supportedLanguages.length;j++) {
supLang = supportedLanguages[j];
supLang = supLang.toLowerCase();
supLang = supLang.replace("_", "-");

View File

@ -16,7 +16,6 @@ import KeyTable from "../core/input/keysym.js";
import keysyms from "../core/input/keysymdef.js";
import Keyboard from "../core/input/keyboard.js";
import RFB from "../core/rfb.js";
import Display from "../core/display.js";
import * as WebUtil from "./webutil.js";
var UI = {
@ -1350,7 +1349,9 @@ var UI = {
var l = input.value.length;
// Move the caret to the end
input.setSelectionRange(l, l);
} catch (err) {} // setSelectionRange is undefined in Google Chrome
} catch (err) {
// setSelectionRange is undefined in Google Chrome
}
},
hideVirtualKeyboard: function() {

View File

@ -15,10 +15,10 @@ export function init_logging (level) {
if (typeof level !== "undefined") {
main_init_logging(level);
} else {
var param = document.location.href.match(/logging=([A-Za-z0-9\._\-]*)/);
var param = document.location.href.match(/logging=([A-Za-z0-9._-]*)/);
main_init_logging(param || undefined);
}
};
}
// Read a query string variable
export function getQueryVar (name, defVal) {
@ -31,7 +31,7 @@ export function getQueryVar (name, defVal) {
} else {
return defVal;
}
};
}
// Read a hash fragment variable
export function getHashVar (name, defVal) {
@ -44,7 +44,7 @@ export function getHashVar (name, defVal) {
} else {
return defVal;
}
};
}
// Read a variable from the fragment or the query string
// Fragment takes precedence
@ -55,7 +55,7 @@ export function getConfigVar (name, defVal) {
val = getQueryVar(name, defVal);
}
return val;
};
}
/*
* Cookie handling. Dervied from: http://www.quirksmode.org/js/cookies.html
@ -80,7 +80,7 @@ export function createCookie (name, value, days) {
secure = "";
}
document.cookie = name + "=" + value + expires + "; path=/" + secure;
};
}
export function readCookie (name, defaultValue) {
"use strict";
@ -93,12 +93,12 @@ export function readCookie (name, defaultValue) {
if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); }
}
return (typeof defaultValue !== 'undefined') ? defaultValue : null;
};
}
export function eraseCookie (name) {
"use strict";
createCookie(name, "", -1);
};
}
/*
* Setting handling.
@ -122,12 +122,12 @@ export function initSettings (callback /*, ...callbackArgs */) {
callback.apply(this, callbackArgs);
}
}
};
}
// Update the settings cache, but do not write to permanent storage
export function setSetting (name, value) {
settings[name] = value;
};
}
// No days means only for this browser session
export function writeSetting (name, value) {
@ -139,7 +139,7 @@ export function writeSetting (name, value) {
} else {
localStorage.setItem(name, value);
}
};
}
export function readSetting (name, defaultValue) {
"use strict";
@ -158,7 +158,7 @@ export function readSetting (name, defaultValue) {
} else {
return value;
}
};
}
export function eraseSetting (name) {
"use strict";
@ -173,7 +173,7 @@ export function eraseSetting (name) {
} else {
localStorage.removeItem(name);
}
};
}
export function injectParamIfMissing (path, param, value) {
// force pretend that we're dealing with a relative path
@ -203,7 +203,7 @@ export function injectParamIfMissing (path, param, value) {
} else {
return elem.pathname + elem.search + elem.hash;
}
};
}
// sadly, we can't use the Fetch API until we decide to drop
// IE11 support or polyfill promises and fetch in IE11.

View File

@ -100,7 +100,7 @@ export default {
// If there are any bits left, the base64 string was corrupted
if (leftbits) {
err = new Error('Corrupted base64 string');
var err = new Error('Corrupted base64 string');
err.name = 'Base64-Error';
throw err;
}

View File

@ -268,4 +268,4 @@ export default function DES(passwd) {
setKeys(passwd); // Setup keys
return {'encrypt': encrypt}; // Public interface
}; // function DES
}

View File

@ -68,7 +68,7 @@ export default function Display(target) {
this._tile16x16 = this._drawCtx.createImageData(16, 16);
Log.Debug("<< Display.constructor");
};
}
var SUPPORTS_IMAGEDATA_CONSTRUCTOR = false;
try {

View File

@ -35,4 +35,4 @@ export default function Inflate() {
this.windowBits = 5;
inflateInit(this.strm, this.windowBits);
};
}

View File

@ -31,7 +31,7 @@ export default function Keyboard(target) {
'blur': this._allKeysUp.bind(this),
'checkalt': this._checkAlt.bind(this),
};
};
}
Keyboard.prototype = {
// ===== EVENT HANDLERS =====
@ -296,7 +296,7 @@ Keyboard.prototype = {
Log.Debug(">> Keyboard.allKeysUp");
for (var code in this._keyDownList) {
this._sendKeyEvent(this._keyDownList[code], code, false);
};
}
Log.Debug("<< Keyboard.allKeysUp");
},

View File

@ -32,7 +32,7 @@ export default function Mouse(target) {
'mousewheel': this._handleMouseWheel.bind(this),
'mousedisable': this._handleMouseDisable.bind(this)
};
};
}
Mouse.prototype = {
// ===== PROPERTIES =====

View File

@ -1,4 +1,3 @@
import KeyTable from "./keysym.js";
import keysyms from "./keysymdef.js";
import vkeys from "./vkeys.js";
import fixedkeys from "./fixedkeys.js";

View File

@ -25,9 +25,6 @@ import Inflator from "./inflator.js";
import { encodings, encodingName } from "./encodings.js";
import "./util/polyfill.js";
/*jslint white: false, browser: true */
/*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
// How many seconds to wait for a disconnect to finish
var DISCONNECT_TIMEOUT = 3;
@ -251,7 +248,7 @@ export default function RFB(target, url, options) {
setTimeout(this._updateConnectionState.bind(this, 'connecting'));
Log.Debug("<< RFB.constructor");
};
}
RFB.prototype = {
// ===== PROPERTIES =====
@ -1063,7 +1060,7 @@ RFB.prototype = {
var serverSupportedTypes = [];
for (var i = 0; i < subAuthCount; i++) {
var capNum = this._sock.rQshift32();
this._sock.rQshift32(); // capNum
var capabilities = this._sock.rQshiftStr(12);
serverSupportedTypes.push(capabilities);
}
@ -2136,15 +2133,6 @@ RFB.encodingHandlers = {
this._FBU.bytes = 1; // compression-control byte
if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
var checksum = function (data) {
var sum = 0;
for (var i = 0; i < data.length; i++) {
sum += data[i];
if (sum > 65536) sum -= 65536;
}
return sum;
};
var resetStreams = 0;
var streamId = -1;
var decompress = function (data, expected) {
@ -2564,6 +2552,7 @@ RFB.encodingHandlers = {
this._qemuExtKeyEventSupported = true;
}
} catch (err) {
// Do nothing
}
},
};
}

View File

@ -42,7 +42,7 @@ export function supportsCursorURIs () {
}
return _cursor_uris_supported;
};
}
export function isMac() {
return navigator && !!(/mac/i).exec(navigator.platform);

View File

@ -12,12 +12,12 @@
export function getPointerEvent (e) {
return e.changedTouches ? e.changedTouches[0] : e.touches ? e.touches[0] : e;
};
}
export function stopEvent (e) {
e.stopPropagation();
e.preventDefault();
};
}
// Emulate Element.setCapture() when not supported
var _captureRecursion = false;
@ -45,13 +45,13 @@ function _captureProxy(e) {
if (e.type === "mouseup") {
releaseCapture();
}
};
}
// Follow cursor style of target element
function _captureElemChanged() {
var captureElem = document.getElementById("noVNC_mouse_capture_elem");
captureElem.style.cursor = window.getComputedStyle(_captureElem).cursor;
};
}
var _captureObserver = new MutationObserver(_captureElemChanged);
var _captureIndex = 0;
@ -105,7 +105,7 @@ export function setCapture (elem) {
window.addEventListener('mousemove', _captureProxy);
window.addEventListener('mouseup', _captureProxy);
}
};
}
export function releaseCapture () {
if (document.releaseCapture) {
@ -135,4 +135,4 @@ export function releaseCapture () {
window.removeEventListener('mousemove', _captureProxy);
window.removeEventListener('mouseup', _captureProxy);
}
};
}

View File

@ -25,7 +25,9 @@ export function init_logging (level) {
}
Debug = Info = Warn = Error = function (msg) {};
if (typeof window.console !== "undefined") {
/* eslint-disable no-console, no-fallthrough */
switch (level) {
case 'debug':
Debug = console.debug.bind(window.console);
@ -40,11 +42,14 @@ export function init_logging (level) {
default:
throw new Error("invalid logging type '" + level + "'");
}
/* eslint-enable no-console, no-fallthrough */
}
};
}
export function get_logging () {
return _log_level;
};
}
export { Debug, Info, Warn, Error };
// Initialize logging level

View File

@ -12,4 +12,4 @@
export function decodeUTF8 (utf8string) {
"use strict";
return decodeURIComponent(escape(utf8string));
};
}

View File

@ -37,7 +37,7 @@ export default function Websock() {
'close': function () {},
'error': function () {}
};
};
}
// this has performance issues in some versions Chromium, and
// doesn't gain a tremendous amount of performance increase in Firefox
@ -204,7 +204,6 @@ Websock.prototype = {
},
open: function (uri, protocols) {
var ws_schema = uri.match(/^([a-z]+):\/\//)[1];
this.init();
this._websocket = new WebSocket(uri, protocols);
@ -267,7 +266,7 @@ Websock.prototype = {
if (this._rQbufferSize > MAX_RQ_GROW_SIZE) {
this._rQbufferSize = MAX_RQ_GROW_SIZE;
if (this._rQbufferSize - this._rQlen - this._rQi < min_fit) {
throw new Exception("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
throw new Error("Receive Queue buffer exceeded " + MAX_RQ_GROW_SIZE + " bytes, and the new message could not fit");
}
}

View File

@ -7,7 +7,8 @@
"test": "tests"
},
"scripts": {
"test": "PATH=$PATH:node_modules/karma/bin karma start karma.conf.js",
"lint": "eslint app core po tests utils",
"test": "karma start karma.conf.js",
"prepare": "node ./utils/use_require.js --as commonjs --clean"
},
"repository": {
@ -40,6 +41,7 @@
"chai": "^3.5.0",
"commander": "^2.9.0",
"es-module-loader": "^2.1.0",
"eslint": "^4.16.0",
"fs-extra": "^1.0.0",
"jsdom": "*",
"karma": "^1.3.0",

9
tests/.eslintrc Normal file
View File

@ -0,0 +1,9 @@
{
"env": {
"node": true,
"mocha": true
},
"globals": {
"chai": true
}
}

View File

@ -20,6 +20,7 @@ chai.use(function (_chai, utils) {
}
}
if (!same) {
// eslint-disable-next-line no-console
console.log("expected data: %o, actual data: %o", target_data, data);
}
this.assert(same,
@ -50,6 +51,7 @@ chai.use(function (_chai, utils) {
}
}
if (!same) {
// eslint-disable-next-line no-console
console.log("expected data: %o, actual data: %o", target_data, data);
}
this.assert(same,

View File

@ -1,3 +1,5 @@
import Base64 from '../core/base64.js';
// PhantomJS can't create Event objects directly, so we need to use this
function make_event(name, props) {
var evt = document.createEvent('Event');
@ -27,7 +29,7 @@ export default function FakeWebSocket (uri, protocols) {
this.bufferedAmount = 0;
this.__is_fake = true;
};
}
FakeWebSocket.prototype = {
close: function (code, reason) {
@ -75,6 +77,7 @@ FakeWebSocket.__is_fake = true;
FakeWebSocket.replace = function () {
if (!WebSocket.__is_fake) {
var real_version = WebSocket;
// eslint-disable-next-line no-global-assign
WebSocket = FakeWebSocket;
FakeWebSocket.__real_version = real_version;
}
@ -82,6 +85,7 @@ FakeWebSocket.replace = function () {
FakeWebSocket.restore = function () {
if (WebSocket.__is_fake) {
// eslint-disable-next-line no-global-assign
WebSocket = WebSocket.__real_version;
}
};

View File

@ -1,3 +1,5 @@
/* global VNC_frame_data, VNC_frame_encoding */
import * as WebUtil from '../app/webutil.js';
import RecordingPlayer from './playback.js';
@ -5,7 +7,6 @@ var frames = null;
var encoding = null;
function message(str) {
console.log(str);
var cell = document.getElementById('messages');
cell.textContent += str + "\n";
cell.scrollTop = cell.scrollHeight;

View File

@ -155,11 +155,12 @@ RecordingPlayer.prototype = {
const frame = this._frames[this._frame_index];
var start = frame.indexOf('{', 1) + 1;
var u8;
if (this._encoding === 'base64') {
var u8 = Base64.decode(frame.slice(start));
u8 = Base64.decode(frame.slice(start));
start = 0;
} else {
var u8 = new Uint8Array(frame.length - start);
u8 = new Uint8Array(frame.length - start);
for (let i = 0; i < frame.length - start; i++) {
u8[i] = frame.charCodeAt(start + i);
}

View File

@ -1,4 +1,3 @@
var assert = chai.assert;
var expect = chai.expect;
import Base64 from '../core/base64.js';

View File

@ -1,5 +1,4 @@
var assert = chai.assert;
var expect = chai.expect;
var expect = chai.expect;
import keysyms from '../core/input/keysymdef.js';
import * as KeyboardUtil from "../core/input/util.js";

View File

@ -1,4 +1,3 @@
var assert = chai.assert;
var expect = chai.expect;
import sinon from '../vendor/sinon.js';
@ -19,7 +18,7 @@ describe('Key Event Handling', function() {
e.stopPropagation = sinon.spy();
e.preventDefault = sinon.spy();
return e;
};
}
describe('Decode Keyboard Events', function() {
it('should decode keydown events', function(done) {
@ -133,12 +132,12 @@ describe('Key Event Handling', function() {
});
it('should suppress anything with a valid key', function() {
var kbd = new Keyboard(document, {});
var evt = keyevent('keydown', {code: 'KeyA', key: 'a'});
kbd._handleKeyDown(evt);
expect(evt.preventDefault).to.have.been.called;
evt = keyevent('keyup', {code: 'KeyA', key: 'a'});
kbd._handleKeyUp(evt);
expect(evt.preventDefault).to.have.been.called;
var evt1 = keyevent('keydown', {code: 'KeyA', key: 'a'});
kbd._handleKeyDown(evt1);
expect(evt1.preventDefault).to.have.been.called;
var evt2 = keyevent('keyup', {code: 'KeyA', key: 'a'});
kbd._handleKeyUp(evt2);
expect(evt2.preventDefault).to.have.been.called;
});
it('should not suppress keys without key', function() {
var kbd = new Keyboard(document, {});
@ -148,11 +147,11 @@ describe('Key Event Handling', function() {
});
it('should suppress the following keypress event', function() {
var kbd = new Keyboard(document, {});
var evt = keyevent('keydown', {code: 'KeyA', keyCode: 0x41});
kbd._handleKeyDown(evt);
var evt = keyevent('keypress', {code: 'KeyA', charCode: 0x41});
kbd._handleKeyPress(evt);
expect(evt.preventDefault).to.have.been.called;
var evt1 = keyevent('keydown', {code: 'KeyA', keyCode: 0x41});
kbd._handleKeyDown(evt1);
var evt2 = keyevent('keypress', {code: 'KeyA', charCode: 0x41});
kbd._handleKeyPress(evt2);
expect(evt2.preventDefault).to.have.been.called;
});
});
});

View File

@ -1,7 +1,6 @@
var assert = chai.assert;
var expect = chai.expect;
import l10nGet, { l10n } from '../app/localization.js';
import { l10n } from '../app/localization.js';
describe('Localization', function() {
"use strict";

View File

@ -1,4 +1,3 @@
var assert = chai.assert;
var expect = chai.expect;
import sinon from '../vendor/sinon.js';

View File

@ -1,4 +1,3 @@
var assert = chai.assert;
var expect = chai.expect;
import RFB from '../core/rfb.js';
@ -658,16 +657,16 @@ describe('Remote Frame Buffer Protocol Client', function() {
it('should not resize until the container size is stable', function () {
container.style.width = '20px';
container.style.height = '30px';
var event = new UIEvent('resize');
window.dispatchEvent(event);
var event1 = new UIEvent('resize');
window.dispatchEvent(event1);
clock.tick(400);
expect(RFB.messages.setDesktopSize).to.not.have.been.called;
container.style.width = '40px';
container.style.height = '50px';
var event = new UIEvent('resize');
window.dispatchEvent(event);
var event2 = new UIEvent('resize');
window.dispatchEvent(event2);
clock.tick(400);
expect(RFB.messages.setDesktopSize).to.not.have.been.called;
@ -1894,7 +1893,6 @@ describe('Remote Frame Buffer Protocol Client', function() {
});
it('should handle the DesktopSize pseduo-encoding', function () {
var spy = sinon.spy();
sinon.spy(client._display, 'resize');
send_fbu_msg([{ x: 0, y: 0, width: 20, height: 50, encoding: -223 }], [[]], client);
@ -1906,15 +1904,12 @@ describe('Remote Frame Buffer Protocol Client', function() {
});
describe('the ExtendedDesktopSize pseudo-encoding handler', function () {
var resizeSpy;
beforeEach(function () {
// a really small frame
client._fb_width = 4;
client._fb_height = 4;
client._display.resize(4, 4);
sinon.spy(client._display, 'resize');
resizeSpy = sinon.spy();
});
function make_screen_data (nr_of_screens) {
@ -2173,7 +2168,6 @@ describe('Remote Frame Buffer Protocol Client', function() {
describe('Keyboard Event Handlers', function () {
it('should send a key message on a key press', function () {
var keyevent = {};
client._handleKeyEvent(0x41, 'KeyA', true);
var key_msg = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}};
RFB.messages.keyEvent(key_msg, 0x41, 1);

View File

@ -1,4 +1,4 @@
var assert = chai.assert;
/* eslint-disable no-console */
var expect = chai.expect;
import * as Log from '../core/util/logging.js';
@ -68,3 +68,4 @@ describe('Utils', function() {
// (we can't really test them against the browsers, except for Gecko
// via PhantomJS, the default test driver)
});
/* eslint-enable no-console */

View File

@ -1,4 +1,3 @@
var assert = chai.assert;
var expect = chai.expect;
import Websock from '../core/websock.js';
@ -231,14 +230,15 @@ describe('Websock', function() {
var sock;
beforeEach(function () {
sock = new Websock();
WebSocket = sinon.spy();
WebSocket.OPEN = old_WS.OPEN;
WebSocket.CONNECTING = old_WS.CONNECTING;
WebSocket.CLOSING = old_WS.CLOSING;
WebSocket.CLOSED = old_WS.CLOSED;
sock = new Websock();
// eslint-disable-next-line no-global-assign
WebSocket = sinon.spy();
WebSocket.OPEN = old_WS.OPEN;
WebSocket.CONNECTING = old_WS.CONNECTING;
WebSocket.CLOSING = old_WS.CLOSING;
WebSocket.CLOSED = old_WS.CLOSED;
WebSocket.prototype.binaryType = 'arraybuffer';
WebSocket.prototype.binaryType = 'arraybuffer';
});
describe('opening', function () {
@ -327,6 +327,7 @@ describe('Websock', function() {
});
after(function () {
// eslint-disable-next-line no-global-assign
WebSocket = old_WS;
});
});

View File

@ -1,6 +1,5 @@
/* jshint expr: true */
var assert = chai.assert;
var expect = chai.expect;
import * as WebUtil from '../app/webutil.js';

8
utils/.eslintrc Normal file
View File

@ -0,0 +1,8 @@
{
"env": {
"node": true
},
"rules": {
"no-console": 0
}
}

View File

@ -13,7 +13,8 @@ var fs = require('fs');
var show_help = process.argv.length === 2;
var filename;
for (var i = 2; i < process.argv.length; ++i) {
var i;
for (i = 2; i < process.argv.length; ++i) {
switch (process.argv[i]) {
case "--help":
case "-h":
@ -36,19 +37,19 @@ if (show_help) {
console.log("Usage: node parse.js [options] filename:");
console.log(" -h [ --help ] Produce this help message");
console.log(" filename The keysymdef.h file to parse");
return;
process.exit(0);
}
var buf = fs.readFileSync(filename);
var str = buf.toString('utf8');
var re = /^\#define XK_([a-zA-Z_0-9]+)\s+0x([0-9a-fA-F]+)\s*(\/\*\s*(.*)\s*\*\/)?\s*$/m;
var re = /^#define XK_([a-zA-Z_0-9]+)\s+0x([0-9a-fA-F]+)\s*(\/\*\s*(.*)\s*\*\/)?\s*$/m;
var arr = str.split('\n');
var codepoints = {};
for (var i = 0; i < arr.length; ++i) {
for (i = 0; i < arr.length; ++i) {
var result = re.exec(arr[i]);
if (result){
var keyname = result[1];
@ -84,7 +85,7 @@ function toHex(num) {
s = ("0000" + s).slice(-4);
}
return "0x" + s;
};
}
for (var codepoint in codepoints) {
codepoint = parseInt(codepoint);

View File

@ -100,7 +100,7 @@ var transform_html = function (legacy_scripts, only_legacy) {
var start_ind = contents.indexOf(start_marker) + start_marker.length;
var end_ind = contents.indexOf(end_marker, start_ind);
new_script = '';
var new_script = '';
if (only_legacy) {
// Only legacy version, so include things directly
@ -161,11 +161,12 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le
}
var in_path;
var out_path_base;
if (with_app_dir) {
var out_path_base = paths.out_dir_base;
out_path_base = paths.out_dir_base;
in_path = paths.main;
} else {
var out_path_base = paths.lib_dir_base;
out_path_base = paths.lib_dir_base;
}
const legacy_path_base = only_legacy ? out_path_base : path.join(out_path_base, 'legacy');
@ -223,7 +224,7 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le
return babelTransformFile(filename, opts)
.then(res => {
console.log(`Writing ${legacy_path}`);
var {code, map, ast} = res;
var {code, map} = res;
if (source_maps === true) {
// append URL for external source map
code += `\n//# sourceMappingURL=${path.basename(legacy_path)}.map\n`;

View File

@ -1,6 +1,5 @@
// writes helpers require for vnc.html (they should output app.js)
var fs = require('fs');
var fse = require('fs-extra');
var path = require('path');
// util.promisify requires Node.js 8.x, so we have our own