Skip to content
This repository has been archived by the owner on Jan 17, 2023. It is now read-only.

Commit

Permalink
Use prefer-const. (#3977)
Browse files Browse the repository at this point in the history
  • Loading branch information
chenba committed Feb 2, 2018
1 parent 6824d8b commit eefee3d
Show file tree
Hide file tree
Showing 91 changed files with 856 additions and 860 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ root: true
rules:
no-console: [error, {allow: [debug, error, info, trace, warn]}]
no-var: error
prefer-const: off # TODO: change to "error"
prefer-const: error
quotes: [off, double] # TODO: change to "error"

promise/always-return: off
Expand Down
38 changes: 19 additions & 19 deletions addon/bootstrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ const LibraryButton = {

init(webExtension) {
this._initialized = true;
let permissionPages = [...webExtension.extension.permissions].filter(p => (/^https?:\/\//i).test(p));
const permissionPages = [...webExtension.extension.permissions].filter(p => (/^https?:\/\//i).test(p));
if (permissionPages.length > 1) {
Cu.reportError(new Error("Should not have more than 1 permission page, but got: " + JSON.stringify(permissionPages)));
}
Expand All @@ -80,7 +80,7 @@ const LibraryButton = {
this.ICON_URL_2X = webExtension.extension.getURL("icons/icon-32-v2.svg");
this.LABEL = webExtension.extension.localizeMessage("libraryLabel");
CustomizableUI.addListener(this);
for (let win of CustomizableUI.windows) {
for (const win of CustomizableUI.windows) {
this.onWindowOpened(win);
}
},
Expand All @@ -89,8 +89,8 @@ const LibraryButton = {
if (!this._initialized) {
return;
}
for (let win of CustomizableUI.windows) {
let item = win.document.getElementById(this.ITEM_ID);
for (const win of CustomizableUI.windows) {
const item = win.document.getElementById(this.ITEM_ID);
if (item) {
item.remove();
}
Expand All @@ -100,19 +100,19 @@ const LibraryButton = {
},

onWindowOpened(win) {
let libraryViewInsertionPoint = win.document.getElementById("appMenu-library-remotetabs-button");
const libraryViewInsertionPoint = win.document.getElementById("appMenu-library-remotetabs-button");
// If the library view doesn't exist (on non-photon builds, for instance),
// this will be null, and we bail out early.
if (!libraryViewInsertionPoint) {
return;
}
let parent = libraryViewInsertionPoint.parentNode;
let {nextSibling} = libraryViewInsertionPoint;
let item = win.document.createElement("toolbarbutton");
const parent = libraryViewInsertionPoint.parentNode;
const {nextSibling} = libraryViewInsertionPoint;
const item = win.document.createElement("toolbarbutton");
item.className = "subviewbutton subviewbutton-iconic";
item.addEventListener("command", () => win.openUILinkIn(this.PAGE_TO_OPEN, "tab"));
item.id = this.ITEM_ID;
let iconURL = win.devicePixelRatio >= 1.1 ? this.ICON_URL_2X : this.ICON_URL;
const iconURL = win.devicePixelRatio >= 1.1 ? this.ICON_URL_2X : this.ICON_URL;
item.setAttribute("image", iconURL);
item.setAttribute("label", this.LABEL);

Expand Down Expand Up @@ -210,18 +210,18 @@ function handleMessage(msg, sender, sendReply) {
}

if (msg.funcName === "isTelemetryEnabled") {
let telemetryEnabled = getBoolPref(TELEMETRY_ENABLED_PREF);
const telemetryEnabled = getBoolPref(TELEMETRY_ENABLED_PREF);
sendReply({type: "success", value: telemetryEnabled});
} else if (msg.funcName === "isUploadDisabled") {
let isESR = AppConstants.MOZ_UPDATE_CHANNEL === 'esr';
let uploadDisabled = getBoolPref(UPLOAD_DISABLED_PREF);
const isESR = AppConstants.MOZ_UPDATE_CHANNEL === 'esr';
const uploadDisabled = getBoolPref(UPLOAD_DISABLED_PREF);
sendReply({type: "success", value: uploadDisabled || isESR});
} else if (msg.funcName === "isHistoryEnabled") {
let historyEnabled = getBoolPref(HISTORY_ENABLED_PREF);
const historyEnabled = getBoolPref(HISTORY_ENABLED_PREF);
sendReply({type: "success", value: historyEnabled});
} else if (msg.funcName === "incrementCount") {
let allowedScalars = ["download", "upload", "copy"];
let scalar = msg.args && msg.args[0] && msg.args[0].scalar;
const allowedScalars = ["download", "upload", "copy"];
const scalar = msg.args && msg.args[0] && msg.args[0].scalar;
if (!allowedScalars.includes(scalar)) {
sendReply({type: "error", name: `incrementCount passed an unrecognized scalar ${scalar}`});
} else {
Expand All @@ -238,10 +238,10 @@ let photonPageAction;
// Does nothing otherwise. Ideally, in the future, WebExtension page actions
// and Photon page actions would be one in the same, but they aren't right now.
function initPhotonPageAction(api, webExtension) {
let id = "screenshots";
const id = "screenshots";
let port = null;

let {tabManager} = webExtension.extension;
const {tabManager} = webExtension.extension;

// Make the page action.
photonPageAction = PageActions.actionForID(id) || PageActions.addAction(new PageActions.Action({
Expand All @@ -251,8 +251,8 @@ function initPhotonPageAction(api, webExtension) {
_insertBeforeActionID: null,
onCommand(event, buttonNode) {
if (port) {
let browserWin = buttonNode.ownerGlobal;
let tab = tabManager.getWrapper(browserWin.gBrowser.selectedTab);
const browserWin = buttonNode.ownerGlobal;
const tab = tabManager.getWrapper(browserWin.gBrowser.selectedTab);
port.postMessage({
type: "click",
tab: {id: tab.id, url: tab.url}
Expand Down
2 changes: 1 addition & 1 deletion addon/webextension/assertIsBlankDocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*/
this.assertIsBlankDocument = function assertIsBlankDocument(doc) {
if (doc.documentURI !== browser.extension.getURL("blank.html")) {
let exc = new Error('iframe URL does not match expected blank.html');
const exc = new Error('iframe URL does not match expected blank.html');
exc.foundURL = doc.documentURI;
throw exc;
}
Expand Down
4 changes: 2 additions & 2 deletions addon/webextension/assertIsTrusted.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
this.assertIsTrusted = function assertIsTrusted(handlerFunction) {
return function(event) {
if (!event) {
let exc = new Error("assertIsTrusted did not get an event");
const exc = new Error("assertIsTrusted did not get an event");
exc.noPopup = true;
throw exc;
}
if (!event.isTrusted) {
let exc = new Error(`Received untrusted event (type: ${event.type})`);
const exc = new Error(`Received untrusted event (type: ${event.type})`);
exc.noPopup = true;
throw exc;
}
Expand Down
38 changes: 19 additions & 19 deletions addon/webextension/background/analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"use strict";

this.analytics = (function() {
let exports = {};
const exports = {};

let telemetryPrefKnown = false;
let telemetryEnabled;
Expand All @@ -24,17 +24,17 @@ this.analytics = (function() {
return;
}

let eventsUrl = `${main.getBackend()}/event`;
let deviceId = auth.getDeviceId();
let sendTime = Date.now();
const eventsUrl = `${main.getBackend()}/event`;
const deviceId = auth.getDeviceId();
const sendTime = Date.now();

pendingEvents.forEach(event => {
event.queueTime = sendTime - event.eventTime
log.info(`sendEvent ${event.event}/${event.action}/${event.label || 'none'} ${JSON.stringify(event.options)}`);
});

let body = JSON.stringify({deviceId, events: pendingEvents});
let fetchRequest = fetch(eventsUrl, Object.assign({body}, fetchOptions));
const body = JSON.stringify({deviceId, events: pendingEvents});
const fetchRequest = fetch(eventsUrl, Object.assign({body}, fetchOptions));
fetchWatcher(fetchRequest);
pendingEvents = [];
}
Expand All @@ -44,10 +44,10 @@ this.analytics = (function() {
return;
}

let timingsUrl = `${main.getBackend()}/timing`;
let deviceId = auth.getDeviceId();
let body = JSON.stringify({deviceId, timings: pendingTimings});
let fetchRequest = fetch(timingsUrl, Object.assign({body}, fetchOptions));
const timingsUrl = `${main.getBackend()}/timing`;
const deviceId = auth.getDeviceId();
const body = JSON.stringify({deviceId, timings: pendingTimings});
const fetchRequest = fetch(timingsUrl, Object.assign({body}, fetchOptions));
fetchWatcher(fetchRequest);
pendingTimings.forEach(t => {
log.info(`sendTiming ${t.timingCategory}/${t.timingLabel}/${t.timingVar}: ${t.timingValue}`);
Expand All @@ -58,7 +58,7 @@ this.analytics = (function() {
function sendTiming(timingLabel, timingVar, timingValue) {
// sendTiming is only called in response to sendEvent, so no need to check
// the telemetry pref again here.
let timingCategory = "addon";
const timingCategory = "addon";
pendingTimings.push({
timingCategory,
timingLabel,
Expand All @@ -74,7 +74,7 @@ this.analytics = (function() {
}

exports.sendEvent = function(action, label, options) {
let eventCategory = "addon";
const eventCategory = "addon";
if (!telemetryPrefKnown) {
log.warn("sendEvent called before we were able to refresh");
return Promise.resolve();
Expand Down Expand Up @@ -103,11 +103,11 @@ this.analytics = (function() {
// Don't include in event data.
delete options.incognito;

let di = deviceInfo();
const di = deviceInfo();
options.applicationName = di.appName;
options.applicationVersion = di.addonVersion;
let abTests = auth.getAbTests();
for (let [gaField, value] of Object.entries(abTests)) {
const abTests = auth.getAbTests();
for (const [gaField, value] of Object.entries(abTests)) {
options[gaField] = value;
}
pendingEvents.push({
Expand Down Expand Up @@ -149,7 +149,7 @@ this.analytics = (function() {
return telemetryEnabled;
};

let timingData = new Map();
const timingData = new Map();

// Configuration for filtering the sendEvent stream on start/end events.
// When start or end events occur, the time is recorded.
Expand All @@ -158,7 +158,7 @@ this.analytics = (function() {
// and cd1 value is the elapsed time in milliseconds.
// If a cancel event happens between the start and end events, the start time
// is deleted.
let rules = [{
const rules = [{
name: 'page-action',
start: { action: 'start-shot', label: 'toolbar-button' },
end: { action: 'internal', label: 'unhide-preselection-frame' },
Expand Down Expand Up @@ -243,8 +243,8 @@ this.analytics = (function() {
} else if (match(r.start, action, label)) {
timingData[r.name] = Date.now();
} else if (timingData[r.name] && match(r.end, action, label)) {
let endTime = Date.now();
let elapsed = endTime - timingData[r.name];
const endTime = Date.now();
const elapsed = endTime - timingData[r.name];
sendTiming("perf-response-time", r.name, elapsed);
delete timingData[r.name];
}
Expand Down
28 changes: 14 additions & 14 deletions addon/webextension/background/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
"use strict";

this.auth = (function() {
let exports = {};
const exports = {};

let registrationInfo;
let initialized = false;
let authHeader = null;
let sentryPublicDSN = null;
let abTests = {};

let registrationInfoFetched = catcher.watchPromise(browser.storage.local.get(["registrationInfo", "abTests"]).then((result) => {
const registrationInfoFetched = catcher.watchPromise(browser.storage.local.get(["registrationInfo", "abTests"]).then((result) => {
if (result.abTests) {
abTests = result.abTests;
}
Expand All @@ -30,7 +30,7 @@ this.auth = (function() {
};

function generateRegistrationInfo() {
let info = {
const info = {
deviceId: `anon${makeUuid()}`,
secret: makeUuid(),
registered: false
Expand All @@ -40,9 +40,9 @@ this.auth = (function() {

function register() {
return new Promise((resolve, reject) => {
let registerUrl = main.getBackend() + "/api/register";
const registerUrl = main.getBackend() + "/api/register";
// TODO: replace xhr with Fetch #2261
let req = new XMLHttpRequest();
const req = new XMLHttpRequest();
req.open("POST", registerUrl);
req.setRequestHeader("content-type", "application/json");
req.onload = catcher.watchFunction(() => {
Expand All @@ -55,14 +55,14 @@ this.auth = (function() {
} else {
analytics.sendEvent("register-failed", `bad-response-${req.status}`);
log.warn("Error in response:", req.responseText);
let exc = new Error("Bad response: " + req.status);
const exc = new Error("Bad response: " + req.status);
exc.popupMessage = "LOGIN_ERROR";
reject(exc);
}
});
req.onerror = catcher.watchFunction(() => {
analytics.sendEvent("register-failed", "connection-error");
let exc = new Error("Error contacting server");
const exc = new Error("Error contacting server");
exc.popupMessage = "LOGIN_CONNECTION_ERROR";
reject(exc);
});
Expand All @@ -75,11 +75,11 @@ this.auth = (function() {
}

function login(options) {
let { ownershipCheck, noRegister } = options || {};
const { ownershipCheck, noRegister } = options || {};
return new Promise((resolve, reject) => {
let loginUrl = main.getBackend() + "/api/login";
const loginUrl = main.getBackend() + "/api/login";
// TODO: replace xhr with Fetch #2261
let req = new XMLHttpRequest();
const req = new XMLHttpRequest();
req.open("POST", loginUrl);
req.onload = catcher.watchFunction(() => {
if (req.status == 404) {
Expand All @@ -90,18 +90,18 @@ this.auth = (function() {
}
} else if (req.status >= 300) {
log.warn("Error in response:", req.responseText);
let exc = new Error("Could not log in: " + req.status);
const exc = new Error("Could not log in: " + req.status);
exc.popupMessage = "LOGIN_ERROR";
analytics.sendEvent("login-failed", `bad-response-${req.status}`);
reject(exc);
} else if (req.status === 0) {
let error = new Error("Could not log in, server unavailable");
const error = new Error("Could not log in, server unavailable");
error.popupMessage = "LOGIN_CONNECTION_ERROR";
analytics.sendEvent("login-failed", "connection-error");
reject(error);
} else {
initialized = true;
let jsonResponse = JSON.parse(req.responseText);
const jsonResponse = JSON.parse(req.responseText);
log.info("Screenshots logged in");
analytics.sendEvent("login");
saveAuthInfo(jsonResponse);
Expand All @@ -114,7 +114,7 @@ this.auth = (function() {
});
req.onerror = catcher.watchFunction(() => {
analytics.sendEvent("login-failed", "connection-error");
let exc = new Error("Connection failed");
const exc = new Error("Connection failed");
exc.url = loginUrl;
exc.popupMessage = "CONNECTION_ERROR";
reject(exc);
Expand Down
6 changes: 3 additions & 3 deletions addon/webextension/background/communication.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
"use strict";

this.communication = (function() {
let exports = {};
const exports = {};

let registeredFunctions = {};
const registeredFunctions = {};

exports.onMessage = catcher.watchFunction((req, sender, sendResponse) => {
if (!(req.funcName in registeredFunctions)) {
Expand All @@ -18,7 +18,7 @@ this.communication = (function() {
sendResponse({type: "error", name: "No .args"});
return;
}
let func = registeredFunctions[req.funcName];
const func = registeredFunctions[req.funcName];
let result;
try {
req.args.unshift(sender);
Expand Down
8 changes: 4 additions & 4 deletions addon/webextension/background/deviceInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"use strict";

this.deviceInfo = (function() {
let manifest = browser.runtime.getManifest();
const manifest = browser.runtime.getManifest();

let platformInfo = {};
catcher.watchPromise(browser.runtime.getPlatformInfo().then((info) => {
Expand All @@ -12,10 +12,10 @@ this.deviceInfo = (function() {

return function deviceInfo() {
let match = navigator.userAgent.match(/Chrom(?:e|ium)\/([0-9.]{1,1000})/);
let chromeVersion = match ? match[1] : null;
const chromeVersion = match ? match[1] : null;
match = navigator.userAgent.match(/Firefox\/([0-9.]{1,1000})/);
let firefoxVersion = match ? match[1] : null;
let appName = chromeVersion ? "chrome" : "firefox";
const firefoxVersion = match ? match[1] : null;
const appName = chromeVersion ? "chrome" : "firefox";

return {
addonVersion: manifest.version,
Expand Down
Loading

0 comments on commit eefee3d

Please sign in to comment.