Gerald 8 years ago
parent
commit
8e00f84eda

+ 12 - 8
.eslintrc.js

@@ -31,21 +31,25 @@ module.exports = {
     }],
     // allow debugger during development
     'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
-    'no-console': ['error', {
+    'no-console': ['warn', {
       allow: ['error', 'warn', 'info'],
     }],
     'no-param-reassign': ['error', {
       props: false,
     }],
-    'array-callback-return': ['off'],
-    'consistent-return': ['off'],
+    'consistent-return': 'off',
     'no-use-before-define': ['error', 'nofunc'],
     'object-shorthand': ['error', 'always'],
-    'no-mixed-operators': ['error', {allowSamePrecedence: true}],
-    'no-bitwise': ['error', {int32Hint: true}],
-    'no-underscore-dangle': ['off'],
-    'arrow-parens': 0,
-    'indent': ['error', 2, { MemberExpression: 0 }],
+    'no-mixed-operators': ['error', { allowSamePrecedence: true }],
+    'no-bitwise': ['error', { int32Hint: true }],
+    'no-underscore-dangle': 'off',
+    'arrow-parens': ['error', 'as-needed'],
+    'prefer-promise-reject-errors': 'off',
+    'prefer-destructuring': ['error', { array: false }],
+    indent: ['error', 2, {
+      MemberExpression: 0,
+      flatTernaryExpressions: true,
+    }],
   },
   globals: {
     browser: true,

+ 2 - 4
src/background/sync/onedrive.js

@@ -4,13 +4,11 @@ import { objectGet } from 'src/common/object';
 import { dumpQuery } from '../utils';
 import { BaseService, isScriptFile, register, getURI } from './base';
 
+const SECRET_KEY = JSON.parse(window.atob('eyJjbGllbnRfc2VjcmV0Ijoiajl4M09WRXRIdmhpSEtEV09HcXV5TWZaS2s5NjA0MEgifQ=='));
 const config = Object.assign({
   client_id: '000000004418358A',
   redirect_uri: 'https://violentmonkey.github.io/auth_onedrive.html',
-}, JSON.parse(
-  // assume this is secret
-  window.atob('eyJjbGllbnRfc2VjcmV0Ijoiajl4M09WRXRIdmhpSEtEV09HcXV5TWZaS2s5NjA0MEgifQ=='),
-));
+}, SECRET_KEY);
 
 const OneDrive = BaseService.extend({
   name: 'onedrive',

+ 4 - 1
src/background/utils/db.js

@@ -546,7 +546,9 @@ export function getExportData(ids, withValues) {
 }
 
 export function parseScript(data) {
-  const { id, code, message, isNew, config, custom } = data;
+  const {
+    id, code, message, isNew, config, custom,
+  } = data;
   const meta = parseMeta(code);
   if (!meta.name) return Promise.reject(i18n('msgInvalidScript'));
   const result = {
@@ -672,6 +674,7 @@ export function vacuum() {
           map[key.slice(prefix.length)] = -1;
           return true;
         }
+        return false;
       });
     });
   });

+ 1 - 1
src/background/utils/tester.js

@@ -138,7 +138,7 @@ export function resetBlacklist(list) {
   blacklistRules = (Array.isArray(rules) ? rules : (rules || '').split('\n'))
   .map(line => {
     const item = line.trim();
-    if (!item || item.startsWith('#')) return;
+    if (!item || item.startsWith('#')) return null;
 
     /**
      * @include and @match rules are added for people who need a whitelist.

+ 3 - 1
src/common/cache.js

@@ -5,7 +5,9 @@ const defaults = {
 export default function initCache(options) {
   const cache = {};
   const { lifetime: defaultLifetime } = options || defaults;
-  return { get, put, del, has, hit, destroy };
+  return {
+    get, put, del, has, hit, destroy,
+  };
   function get(key, def) {
     const item = cache[key];
     return item ? item.value : def;

+ 2 - 2
src/common/index.js

@@ -13,7 +13,7 @@ export function initHooks() {
   const hooks = [];
 
   function fire(data) {
-    hooks.slice().forEach((cb) => {
+    hooks.slice().forEach(cb => {
       cb(data);
     });
   }
@@ -36,7 +36,7 @@ export function sendMessage(payload) {
     if (error) return Promise.reject(error);
     return data;
   });
-  promise.catch((err) => {
+  promise.catch(err => {
     if (process.env.DEBUG) console.warn(err);
   });
   return promise;

+ 4 - 4
src/common/object.js

@@ -3,13 +3,13 @@ import { normalizeKeys } from '.';
 export function objectGet(obj, rawKey, def) {
   const keys = normalizeKeys(rawKey);
   let res = obj;
-  keys.some((key) => {
+  keys.every(key => {
     if (res && typeof res === 'object' && (key in res)) {
       res = res[key];
-    } else {
-      res = def;
       return true;
     }
+    res = def;
+    return false;
   });
   return res;
 }
@@ -20,7 +20,7 @@ export function objectSet(obj, rawKey, val) {
   const root = obj || {};
   let sub = root;
   const lastKey = keys.pop();
-  keys.forEach((key) => {
+  keys.forEach(key => {
     let child = sub[key];
     if (!child) {
       child = {};

+ 1 - 1
src/common/options.js

@@ -22,7 +22,7 @@ function setOption(key, value) {
 }
 
 function updateOptions(data) {
-  Object.keys(data).forEach((key) => {
+  Object.keys(data).forEach(key => {
     objectSet(options, key, data[key]);
   });
   hooks.fire(data);

+ 1 - 1
src/common/pathinfo.js

@@ -11,5 +11,5 @@ function parseLocation(pathInfo) {
 }
 
 export default function getPathInfo() {
-  return parseLocation(location.hash.slice(1));
+  return parseLocation(window.location.hash.slice(1));
 }

+ 13 - 9
src/common/ui/code.vue

@@ -55,7 +55,7 @@ import { debounce } from 'src/common';
 import Tooltip from './tooltip';
 
 function getHandler(key) {
-  return (cm) => {
+  return cm => {
     const { commands } = cm.state;
     const handle = commands && commands[key];
     return handle && handle();
@@ -67,13 +67,15 @@ function indentWithTab(cm) {
   } else {
     cm.replaceSelection(
       cm.getOption('indentWithTabs') ? '\t' : ' '.repeat(cm.getOption('indentUnit')),
-      'end', '+input');
+      'end',
+      '+input',
+    );
   }
 }
 
 [
   'save', 'cancel', 'find', 'findNext', 'findPrev', 'replace', 'replaceAll', 'close',
-].forEach((key) => {
+].forEach(key => {
   CodeMirror.commands[key] = getHandler(key);
 });
 
@@ -96,8 +98,10 @@ function findNext(cm, state, reversed) {
     const query = state.query || '';
     let cursor = cm.getSearchCursor(query, reversed ? state.posFrom : state.posTo);
     if (!cursor.find(reversed)) {
-      cursor = cm.getSearchCursor(query,
-        reversed ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
+      cursor = cm.getSearchCursor(
+        query,
+        reversed ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0),
+      );
       if (!cursor.find(reversed)) return;
     }
     cm.setSelection(cursor.from(), cursor.to());
@@ -212,10 +216,10 @@ export default {
       [
         cm.options.extraKeys,
         cm.options.keyMap,
-      ].some((keyMap) => {
+      ].some(keyMap => {
         let stop = false;
         if (keyMap) {
-          CodeMirror.lookupKey(name, keyMap, (b) => {
+          CodeMirror.lookupKey(name, keyMap, b => {
             if (cm.state.commands[b]) {
               e.preventDefault();
               e.stopPropagation();
@@ -271,9 +275,9 @@ export default {
       (all ? replaceAll : replaceOne)(cm, state);
     },
     goToLine() {
-      const line = this.search.line - 1;
       const { cm } = this;
-      if (!isNaN(line)) cm.setCursor(line, 0);
+      const line = +this.search.line;
+      if (line > 0) cm.setCursor(line - 1, 0);
       cm.focus();
     },
   },

+ 1 - 1
src/confirm/views/app.vue

@@ -212,7 +212,7 @@ export default {
       });
     },
     trackLocalFile() {
-      new Promise((resolve) => {
+      new Promise(resolve => {
         setTimeout(resolve, 2000);
       })
       .then(() => this.loadData(true))

+ 6 - 4
src/injected/content/index.js

@@ -4,6 +4,8 @@ import { tabOpen, tabClose, tabClosed } from './tabs';
 import { onNotificationCreate, onNotificationClick, onNotificationClose } from './notifications';
 import { getRequestId, httpRequest, abortRequest, httpRequested } from './requests';
 
+const IS_TOP = window.top === window;
+
 const ids = [];
 const menus = [];
 
@@ -21,7 +23,7 @@ function getBadge() {
 function setBadge() {
   if (badge.ready && badge.willSet) {
     // XXX: only scripts run in top level window are counted
-    if (top === window) sendMessage({ cmd: 'SetBadge', data: badge.number });
+    if (IS_TOP) sendMessage({ cmd: 'SetBadge', data: badge.number });
   }
 }
 
@@ -49,7 +51,7 @@ export default function initialize(contentId, webId) {
     if (handle) handle(req.data, src);
   });
 
-  sendMessage({ cmd: 'GetInjected', data: location.href })
+  sendMessage({ cmd: 'GetInjected', data: window.location.href })
   .then(data => {
     if (data.scripts) {
       data.scripts.forEach(script => {
@@ -75,7 +77,7 @@ const handlers = {
     sendMessage({ cmd: 'SetValue', data });
   },
   RegisterMenu(data) {
-    if (window.top === window) menus.push(data);
+    if (IS_TOP) menus.push(data);
     getPopup();
   },
   AddStyle(css) {
@@ -104,7 +106,7 @@ function onHandle(req) {
 
 function getPopup() {
   // XXX: only scripts run in top level window are counted
-  if (top === window) {
+  if (IS_TOP) {
     sendMessage({
       cmd: 'SetPopup',
       data: { ids, menus },

+ 1 - 1
src/injected/content/tabs.js

@@ -6,7 +6,7 @@ const tabIds = {};
 const tabKeys = {};
 
 export function tabOpen({ key, data }) {
-  data.url = getFullUrl(data.url, location.href);
+  data.url = getFullUrl(data.url, window.location.href);
   sendMessage({ cmd: 'TabOpen', data })
   .then(({ id }) => {
     tabIds[key] = id;

+ 3 - 3
src/injected/index.js

@@ -36,17 +36,17 @@ import initialize from './content';
         cmd: 'ConfirmInstall',
         data: {
           code: document.body.textContent,
-          url: location.href,
+          url: window.location.href,
           from: document.referrer,
         },
       })
       .then(() => {
-        if (history.length > 1) history.go(-1);
+        if (window.history.length > 1) window.history.go(-1);
         else sendMessage({ cmd: 'TabClose' });
       });
     }
   }
-  if (/\.user\.js$/.test(location.pathname)) {
+  if (/\.user\.js$/.test(window.location.pathname)) {
     if (document.readyState === 'complete') checkJS();
     else window.addEventListener('load', checkJS, false);
   }

+ 1 - 1
src/injected/web/index.js

@@ -57,7 +57,7 @@ function onLoadScripts(data) {
   bridge.version = data.version;
   if (includes([
     'greasyfork.org',
-  ], location.host)) {
+  ], window.location.host)) {
     exposeVM();
   }
   // reset load and checkLoad

+ 1 - 1
src/injected/web/requests.js

@@ -68,7 +68,7 @@ function callback(req, res) {
   if (cb) {
     if (res.data.response) {
       if (!req.data) req.data = [parseData(res, req.details)];
-      res.data.response = req.data[0];
+      [res.data.response] = req.data;
     }
     res.data.context = req.details.context;
     cb(res.data);

+ 1 - 1
src/options/app.js

@@ -57,7 +57,7 @@ function loadData() {
       'cache',
       'scripts',
       'sync',
-    ].forEach((key) => {
+    ].forEach(key => {
       Vue.set(store, key, data[key]);
     });
     if (store.scripts) {

+ 13 - 9
src/options/views/edit/index.vue

@@ -83,15 +83,19 @@ export default {
   },
   mounted() {
     const id = objectGet(this.script, 'props.id');
-    (id ? sendMessage({
-      cmd: 'GetScriptCode',
-      data: id,
-    }) : sendMessage({
-      cmd: 'NewScript',
-    }).then(({ script, code }) => {
-      this.script = script;
-      return code;
-    }))
+    (id
+      ? sendMessage({
+        cmd: 'GetScriptCode',
+        data: id,
+      })
+      : sendMessage({
+        cmd: 'NewScript',
+      })
+      .then(({ script, code }) => {
+        this.script = script;
+        return code;
+      })
+    )
     .then(code => {
       this.code = code;
       const settings = {};

+ 7 - 6
src/options/views/script-item.vue

@@ -129,7 +129,7 @@ export default {
     const { icon } = this.script.meta;
     if (icon && icon !== this.safeIcon) {
       loadImage(icon)
-      .then((url) => {
+      .then(url => {
         this.safeIcon = url;
       }, () => {
         this.safeIcon = DEFAULT_ICON;
@@ -201,12 +201,13 @@ export default {
     },
     onDragMouseMove(e) {
       const { dragging } = this;
-      const { el, dragged, offset, elements, lastIndex } = dragging;
+      const {
+        el, dragged, offset, elements, lastIndex,
+      } = dragging;
       dragged.style.left = `${e.clientX - offset.x}px`;
       dragged.style.top = `${e.clientY - offset.y}px`;
-      let hoveredIndex = elements.findIndex((item) => {
-        if (!item) return;
-        if (item.classList.contains('dragging-moving')) return;
+      let hoveredIndex = elements.findIndex(item => {
+        if (!item || item.classList.contains('dragging-moving')) return false;
         const rect = item.getBoundingClientRect();
         return (
           e.clientX >= rect.left + PADDING
@@ -247,7 +248,7 @@ export default {
       });
     },
     onDragAnimate(elements, delta) {
-      elements.forEach((el) => {
+      elements.forEach(el => {
         if (!el) return;
         el.classList.add('dragging-moving');
         el.style.transition = 'none';

+ 6 - 6
src/options/views/tab-settings/vm-export.vue

@@ -67,7 +67,7 @@ export default {
       this.exporting = true;
       Promise.resolve(exportData(this.selectedIds))
       .then(downloadBlob)
-      .catch((err) => {
+      .catch(err => {
         console.error(err);
       })
       .then(() => {
@@ -81,15 +81,15 @@ export default {
 };
 
 function getWriter() {
-  return new Promise((resolve) => {
-    zip.createWriter(new zip.BlobWriter(), (writer) => {
+  return new Promise(resolve => {
+    zip.createWriter(new zip.BlobWriter(), writer => {
       resolve(writer);
     });
   });
 }
 
 function addFile(writer, file) {
-  return new Promise((resolve) => {
+  return new Promise(resolve => {
     writer.add(file.name, new zip.TextReader(file.content), () => {
       resolve(writer);
     });
@@ -176,8 +176,8 @@ function exportData(selectedIds) {
   .then(files => files.reduce((result, file) => (
     result.then(writer => addFile(writer, file))
   ), getWriter()))
-  .then(writer => new Promise((resolve) => {
-    writer.close((blob) => {
+  .then(writer => new Promise(resolve => {
+    writer.close(blob => {
       resolve(blob);
     });
   }));

+ 8 - 8
src/options/views/tab-settings/vm-import.vue

@@ -52,7 +52,7 @@ export default {
 
 function forEachItem(obj, cb) {
   if (obj) {
-    Object.keys(obj).forEach((key) => {
+    Object.keys(obj).forEach(key => {
       cb(obj[key], key);
     });
   }
@@ -71,9 +71,9 @@ function getVMConfig(text) {
 function getVMFile(entry, vmFile) {
   if (!entry.filename.endsWith('.user.js')) return;
   const vm = vmFile || {};
-  return new Promise((resolve) => {
+  return new Promise(resolve => {
     const writer = new zip.TextWriter();
-    entry.getData(writer, (text) => {
+    entry.getData(writer, text => {
       const data = { code: text };
       if (vm.scripts) {
         const more = vm.scripts[entry.filename.slice(0, -8)];
@@ -99,9 +99,9 @@ function getVMFiles(entries) {
   if (i < 0) {
     return { entries };
   }
-  return new Promise((resolve) => {
+  return new Promise(resolve => {
     const writer = new zip.TextWriter();
-    entries[i].getData(writer, (text) => {
+    entries[i].getData(writer, text => {
       entries.splice(i, 1);
       resolve({
         entries,
@@ -113,11 +113,11 @@ function getVMFiles(entries) {
 
 function readZip(file) {
   return new Promise((resolve, reject) => {
-    zip.createReader(new zip.BlobReader(file), (res) => {
-      res.getEntries((entries) => {
+    zip.createReader(new zip.BlobReader(file), res => {
+      res.getEntries(entries => {
         resolve(entries);
       });
-    }, (err) => { reject(err); });
+    }, err => { reject(err); });
   });
 }
 

+ 1 - 1
src/options/views/tab-settings/vm-sync.vue

@@ -36,7 +36,7 @@ const SYNC_CURRENT = 'sync.current';
 const syncConfig = {
   current: '',
 };
-options.hook((data) => {
+options.hook(data => {
   if (SYNC_CURRENT in data) {
     syncConfig.current = data[SYNC_CURRENT] || '';
   }