--- a/browser/base/content/aboutaccounts/aboutaccounts.js
+++ b/browser/base/content/aboutaccounts/aboutaccounts.js
@@ -265,17 +265,17 @@ var wrapper = {
fxAccounts.signOut().then(
() => this.injectData("message", { status: "sign_out" }),
(err) => this.injectData("message", { status: "error", error: err })
);
},
handleRemoteCommand(evt) {
- log('command: ' + evt.detail.command);
+ log("command: " + evt.detail.command);
let data = evt.detail.data;
switch (evt.detail.command) {
case "login":
this.onLogin(data);
break;
case "can_link_account":
this.onCanLinkAccount(data);
@@ -415,29 +415,29 @@ function setErrorPage(errorType) {
// Causes the "top-level" element with |id| to be shown - all other top-level
// elements are hidden. Optionally, ensures that only 1 "second-level" element
// inside the top-level one is shown.
function show(id, childId) {
// top-level items are either <div> or <iframe>
let allTop = document.querySelectorAll("body > div, iframe");
for (let elt of allTop) {
if (elt.getAttribute("id") == id) {
- elt.style.display = 'block';
+ elt.style.display = "block";
} else {
- elt.style.display = 'none';
+ elt.style.display = "none";
}
}
if (childId) {
// child items are all <div>
let allSecond = document.querySelectorAll("#" + id + " > div");
for (let elt of allSecond) {
if (elt.getAttribute("id") == childId) {
- elt.style.display = 'block';
+ elt.style.display = "block";
} else {
- elt.style.display = 'none';
+ elt.style.display = "none";
}
}
}
}
// Migrate sync data from the default profile to the dev-edition profile.
// Returns a promise of a true value if migration succeeded, or false if it
// failed.
@@ -495,27 +495,27 @@ function getDefaultProfilePath() {
.getService(Ci.nsIToolkitProfileService)
.defaultProfile;
return defaultProfile.rootDir.path;
}
document.addEventListener("DOMContentLoaded", function onload() {
document.removeEventListener("DOMContentLoaded", onload, true);
init();
- var buttonGetStarted = document.getElementById('buttonGetStarted');
- buttonGetStarted.addEventListener('click', getStarted);
+ var buttonGetStarted = document.getElementById("buttonGetStarted");
+ buttonGetStarted.addEventListener("click", getStarted);
- var buttonRetry = document.getElementById('buttonRetry');
- buttonRetry.addEventListener('click', retry);
+ var buttonRetry = document.getElementById("buttonRetry");
+ buttonRetry.addEventListener("click", retry);
- var oldsync = document.getElementById('oldsync');
- oldsync.addEventListener('click', handleOldSync);
+ var oldsync = document.getElementById("oldsync");
+ oldsync.addEventListener("click", handleOldSync);
- var buttonOpenPrefs = document.getElementById('buttonOpenPrefs')
- buttonOpenPrefs.addEventListener('click', openPrefs);
+ var buttonOpenPrefs = document.getElementById("buttonOpenPrefs")
+ buttonOpenPrefs.addEventListener("click", openPrefs);
}, true);
function initObservers() {
function observe(subject, topic, data) {
log("about:accounts observed " + topic);
if (topic == fxAccountsCommon.ONLOGOUT_NOTIFICATION) {
// All about:account windows get changed to action=signin on logout.
window.location = "about:accounts?action=signin";
--- a/browser/base/content/browser-places.js
+++ b/browser/base/content/browser-places.js
@@ -1692,17 +1692,17 @@ var BookmarkingUI = {
let widthDiff = referenceRect.width - rectToPosition.width;
return [(leftDiff + .5 * widthDiff) + "px", (topDiff + .5 * heightDiff) + "px"];
}
if (this._notificationTimeout) {
clearTimeout(this._notificationTimeout);
}
- if (this.notifier.style.transform == '') {
+ if (this.notifier.style.transform == "") {
// Get all the relevant nodes and computed style objects
let dropmarker = document.getAnonymousElementByAttribute(this.button, "anonid", "dropmarker");
let dropmarkerIcon = document.getAnonymousElementByAttribute(dropmarker, "class", "dropmarker-icon");
let dropmarkerStyle = getComputedStyle(dropmarkerIcon);
// Check for RTL and get bounds
let isRTL = getComputedStyle(this.button).direction == "rtl";
let buttonRect = this.button.getBoundingClientRect();
@@ -1737,18 +1737,18 @@ var BookmarkingUI = {
this.dropmarkerNotifier.setAttribute("notification", "finish");
}
this._notificationTimeout = setTimeout( () => {
this.notifier.removeAttribute("notification");
this.dropmarkerNotifier.removeAttribute("notification");
this.button.removeAttribute("notification");
- this.dropmarkerNotifier.style.transform = '';
- this.notifier.style.transform = '';
+ this.dropmarkerNotifier.style.transform = "";
+ this.notifier.style.transform = "";
}, 1000);
},
_showSubview() {
let view = document.getElementById("PanelUI-bookmarks");
view.addEventListener("ViewShowing", this);
view.addEventListener("ViewHiding", this);
let anchor = document.getElementById(this.BOOKMARK_BUTTON_ID);
--- a/browser/base/content/browser-plugins.js
+++ b/browser/base/content/browser-plugins.js
@@ -413,17 +413,17 @@ var gPluginHandler = {
}
}
}
];
n = notificationBox.
appendNotification(message, "plugin-hidden", null,
notificationBox.PRIORITY_INFO_HIGH, buttons);
if (haveInsecure) {
- n.classList.add('pluginVulnerable');
+ n.classList.add("pluginVulnerable");
}
}
if (actions.length == 0) {
hideNotification();
} else {
let notificationPermission = Services.perms.testPermissionFromPrincipal(
principal, "plugin-hidden-notification");
--- a/browser/base/content/browser-syncui.js
+++ b/browser/base/content/browser-syncui.js
@@ -427,19 +427,19 @@ var gSyncUI = {
let sixDaysAgo = (() => {
let tempDate = new Date();
tempDate.setDate(tempDate.getDate() - 6);
tempDate.setHours(0, 0, 0, 0);
return tempDate;
})();
// It may be confusing for the user to see "Last Sync: Monday" when the last sync was a indeed a Monday but 3 weeks ago
if (date < sixDaysAgo) {
- dateFormat = {month: 'long', day: 'numeric'};
+ dateFormat = {month: "long", day: "numeric"};
} else {
- dateFormat = {weekday: 'long', hour: 'numeric', minute: 'numeric'};
+ dateFormat = {weekday: "long", hour: "numeric", minute: "numeric"};
}
let lastSyncDateString = date.toLocaleDateString(undefined, dateFormat);
return this._stringBundle.formatStringFromName("lastSync2.label", [lastSyncDateString], 1);
},
onClientsSynced() {
let broadcaster = document.getElementById("sync-syncnow-state");
if (broadcaster) {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -113,17 +113,17 @@ if (AppConstants.MOZ_CRASHREPORTER) {
XPCOMUtils.defineLazyGetter(this, "BrowserToolboxProcess", function() {
let tmp = {};
Cu.import("resource://devtools/client/framework/ToolboxProcess.jsm", tmp);
return tmp.BrowserToolboxProcess;
});
XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
- return Services.strings.createBundle('chrome://browser/locale/browser.properties');
+ return Services.strings.createBundle("chrome://browser/locale/browser.properties");
});
XPCOMUtils.defineLazyGetter(this, "gCustomizeMode", function() {
let scope = {};
Cu.import("resource:///modules/CustomizeMode.jsm", scope);
return new scope.CustomizeMode(window);
});
@@ -748,17 +748,17 @@ function gKeywordURIFixup({ target: brow
// Additionally, we need the host of the parsed url
let hostName = alternativeURI.host;
// and the ascii-only host for the pref:
let asciiHost = alternativeURI.asciiHost;
// Normalize out a single trailing dot - NB: not using endsWith/lastIndexOf
// because we need to be sure this last dot is the *only* dot, too.
// More generally, this is used for the pref and should stay in sync with
// the code in nsDefaultURIFixup::KeywordURIFixup .
- if (asciiHost.indexOf('.') == asciiHost.length - 1) {
+ if (asciiHost.indexOf(".") == asciiHost.length - 1) {
asciiHost = asciiHost.slice(0, -1);
}
let isIPv4Address = host => {
let parts = host.split(".");
if (parts.length != 4) {
return false;
}
@@ -844,17 +844,17 @@ function gKeywordURIFixup({ target: brow
// A shared function used by both remote and non-remote browser XBL bindings to
// load a URI or redirect it to the correct process.
function _loadURIWithFlags(browser, uri, params) {
if (!uri) {
uri = "about:blank";
}
let flags = params.flags || 0;
let referrer = params.referrerURI;
- let referrerPolicy = ('referrerPolicy' in params ? params.referrerPolicy :
+ let referrerPolicy = ("referrerPolicy" in params ? params.referrerPolicy :
Ci.nsIHttpChannel.REFERRER_POLICY_UNSET);
let postData = params.postData;
let currentRemoteType = browser.remoteType;
let requiredRemoteType =
E10SUtils.getRemoteTypeForURI(uri, gMultiProcessBrowser, currentRemoteType);
let mustChangeProcess = requiredRemoteType != currentRemoteType;
@@ -1587,34 +1587,34 @@ var gBrowserInit = {
};
if (AppConstants.platform == "macosx") {
// nonBrowserWindowStartup(), nonBrowserWindowDelayedStartup(), and
// nonBrowserWindowShutdown() are used for non-browser windows in
// macBrowserOverlay
gBrowserInit.nonBrowserWindowStartup = function() {
// Disable inappropriate commands / submenus
- var disabledItems = ['Browser:SavePage',
- 'Browser:SendLink', 'cmd_pageSetup', 'cmd_print', 'cmd_find', 'cmd_findAgain',
- 'viewToolbarsMenu', 'viewSidebarMenuMenu', 'Browser:Reload',
- 'viewFullZoomMenu', 'pageStyleMenu', 'charsetMenu', 'View:PageSource', 'View:FullScreen',
- 'viewHistorySidebar', 'Browser:AddBookmarkAs', 'Browser:BookmarkAllTabs',
- 'View:PageInfo'];
+ var disabledItems = ["Browser:SavePage",
+ "Browser:SendLink", "cmd_pageSetup", "cmd_print", "cmd_find", "cmd_findAgain",
+ "viewToolbarsMenu", "viewSidebarMenuMenu", "Browser:Reload",
+ "viewFullZoomMenu", "pageStyleMenu", "charsetMenu", "View:PageSource", "View:FullScreen",
+ "viewHistorySidebar", "Browser:AddBookmarkAs", "Browser:BookmarkAllTabs",
+ "View:PageInfo"];
var element;
for (let disabledItem of disabledItems) {
element = document.getElementById(disabledItem);
if (element)
element.setAttribute("disabled", "true");
}
// If no windows are active (i.e. we're the hidden window), disable the close, minimize
// and zoom menu commands as well
if (window.location.href == "chrome://browser/content/hiddenWindow.xul") {
- var hiddenWindowDisabledItems = ['cmd_close', 'minimizeWindow', 'zoomWindow'];
+ var hiddenWindowDisabledItems = ["cmd_close", "minimizeWindow", "zoomWindow"];
for (let hiddenWindowDisabledItem of hiddenWindowDisabledItems) {
element = document.getElementById(hiddenWindowDisabledItem);
if (element)
element.setAttribute("disabled", "true");
}
// also hide the window-list separator
element = document.getElementById("sep-window-list");
@@ -1717,17 +1717,17 @@ function HandleAppCommandEvent(evt) {
break;
case "Close":
BrowserCloseTabOrWindow();
break;
case "Find":
gFindBar.onFindCommand();
break;
case "Help":
- openHelpLink('firefox-help');
+ openHelpLink("firefox-help");
break;
case "Open":
BrowserOpenFileWindow();
break;
case "Print":
PrintUtils.printWindow(gBrowser.selectedBrowser.outerWindowID,
gBrowser.selectedBrowser);
break;
@@ -2926,18 +2926,18 @@ var BrowserOnClick = {
params.prefetchCert = true;
case 1 : // Pre-populate
params.location = location;
}
} catch (e) {
Components.utils.reportError("Couldn't get ssl_override pref: " + e);
}
- window.openDialog('chrome://pippki/content/exceptionDialog.xul',
- '', 'chrome,centerscreen,modal', params);
+ window.openDialog("chrome://pippki/content/exceptionDialog.xul",
+ "", "chrome,centerscreen,modal", params);
// If the user added the exception cert, attempt to reload the page
if (params.exceptionAdded) {
browser.reload();
}
break;
case "returnButton":
@@ -2995,23 +2995,23 @@ var BrowserOnClick = {
Services.obs.addObserver(tabCloser, "captive-portal-login-success", false);
},
onAboutBlocked(elementId, reason, isTopFrame, location) {
// Depending on what page we are displaying here (malware/phishing/unwanted)
// use the right strings and links for each.
let bucketName = "";
let sendTelemetry = false;
- if (reason === 'malware') {
+ if (reason === "malware") {
sendTelemetry = true;
bucketName = "WARNING_MALWARE_PAGE_";
- } else if (reason === 'phishing') {
+ } else if (reason === "phishing") {
sendTelemetry = true;
bucketName = "WARNING_PHISHING_PAGE_";
- } else if (reason === 'unwanted') {
+ } else if (reason === "unwanted") {
sendTelemetry = true;
bucketName = "WARNING_UNWANTED_PAGE_";
}
let secHistogram = Services.telemetry.getHistogramById("SECURITY_UI");
let nsISecTel = Ci.nsISecurityUITelemetry;
bucketName += isTopFrame ? "TOP_" : "FRAME_";
switch (elementId) {
case "getMeOutButton":
@@ -3080,35 +3080,35 @@ var BrowserOnClick = {
let buttons = [{
label: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.label"),
accessKey: gNavigatorBundle.getString("safebrowsing.getMeOutOfHereButton.accessKey"),
callback() { getMeOutOfHere(); }
}];
let title;
- if (reason === 'malware') {
+ if (reason === "malware") {
title = gNavigatorBundle.getString("safebrowsing.reportedAttackSite");
buttons[1] = {
label: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.label"),
accessKey: gNavigatorBundle.getString("safebrowsing.notAnAttackButton.accessKey"),
callback() {
- openUILinkIn(gSafeBrowsing.getReportURL('MalwareMistake'), 'tab');
+ openUILinkIn(gSafeBrowsing.getReportURL("MalwareMistake"), "tab");
}
};
- } else if (reason === 'phishing') {
+ } else if (reason === "phishing") {
title = gNavigatorBundle.getString("safebrowsing.deceptiveSite");
buttons[1] = {
label: gNavigatorBundle.getString("safebrowsing.notADeceptiveSiteButton.label"),
accessKey: gNavigatorBundle.getString("safebrowsing.notADeceptiveSiteButton.accessKey"),
callback() {
- openUILinkIn(gSafeBrowsing.getReportURL('PhishMistake'), 'tab');
+ openUILinkIn(gSafeBrowsing.getReportURL("PhishMistake"), "tab");
}
};
- } else if (reason === 'unwanted') {
+ } else if (reason === "unwanted") {
title = gNavigatorBundle.getString("safebrowsing.reportedUnwantedSite");
// There is no button for reporting errors since Google doesn't currently
// provide a URL endpoint for these reports.
}
let notificationBox = gBrowser.getNotificationBox();
let value = "blocked-badware-page";
@@ -3306,17 +3306,17 @@ function getDetailedCertErrorInfo(locati
return certErrorDetails;
}
// TODO: can we pull getDERString and getPEMString in from pippki.js instead of
// duplicating them here?
function getDERString(cert) {
var length = {};
var derArray = cert.getRawDER(length);
- var derString = '';
+ var derString = "";
for (var i = 0; i < derArray.length; i++) {
derString += String.fromCharCode(derArray[i]);
}
return derString;
}
function getPEMString(cert) {
var derb64 = btoa(getDERString(cert));
@@ -4042,17 +4042,17 @@ function OpenBrowserWindow(options) {
// is being closed right after it was opened to avoid leaking.
Services.obs.addObserver(newDocumentShown, "document-shown", false);
Services.obs.addObserver(windowClosed, "domwindowclosed", false);
var charsetArg = new String();
var handler = Components.classes["@mozilla.org/browser/clh;1"]
.getService(Components.interfaces.nsIBrowserHandler);
var defaultArgs = handler.defaultArgs;
- var wintype = document.documentElement.getAttribute('windowtype');
+ var wintype = document.documentElement.getAttribute("windowtype");
var extraFeatures = "";
if (options && options.private) {
extraFeatures = ",private";
if (!PrivateBrowsingUtils.permanentPrivateBrowsing) {
// Force the new window to load about:privatebrowsing instead of the default home page
defaultArgs = "about:privatebrowsing";
}
@@ -4153,17 +4153,17 @@ function updateEditUIVisibility() {
* sourceEvent. This attribute is propagated to the top level originAttributes
* living on the tab's docShell.
*
* @param event
* A click event on a userContext File Menu option
*/
function openNewUserContextTab(event) {
openUILinkIn(BROWSER_NEW_TAB_URL, "tab", {
- userContextId: parseInt(event.target.getAttribute('data-usercontextid')),
+ userContextId: parseInt(event.target.getAttribute("data-usercontextid")),
});
}
/**
* Updates File Menu User Context UI visibility depending on
* privacy.userContext.enabled pref state.
*/
function updateUserContextUIVisibility() {
@@ -4450,26 +4450,26 @@ var XULBrowserWindow = {
}
}
this.status = "";
this.setDefaultStatus(msg);
// Disable menu entries for images, enable otherwise
if (browser.documentContentType && BrowserUtils.mimeTypeIsTextBased(browser.documentContentType)) {
- this.isImage.removeAttribute('disabled');
+ this.isImage.removeAttribute("disabled");
} else {
canViewSource = false;
- this.isImage.setAttribute('disabled', 'true');
+ this.isImage.setAttribute("disabled", "true");
}
if (canViewSource) {
- this.canViewSource.removeAttribute('disabled');
+ this.canViewSource.removeAttribute("disabled");
} else {
- this.canViewSource.setAttribute('disabled', 'true');
+ this.canViewSource.setAttribute("disabled", "true");
}
}
this.isBusy = false;
if (this._busyUI) {
this._busyUI = false;
@@ -4502,19 +4502,19 @@ var XULBrowserWindow = {
}
}
}
let browser = gBrowser.selectedBrowser;
// Disable menu entries for images, enable otherwise
if (browser.documentContentType && BrowserUtils.mimeTypeIsTextBased(browser.documentContentType))
- this.isImage.removeAttribute('disabled');
+ this.isImage.removeAttribute("disabled");
else
- this.isImage.setAttribute('disabled', 'true');
+ this.isImage.setAttribute("disabled", "true");
this.hideOverLinkImmediately = true;
this.setOverLink("", null);
this.hideOverLinkImmediately = false;
// We should probably not do this if the value has changed since the user
// searched
// Update urlbar only if a new page was loaded on the primary content area
@@ -5322,17 +5322,17 @@ var gHomeButton = {
this.updateTooltip();
},
updateTooltip(homeButton) {
if (!homeButton)
homeButton = document.getElementById("home-button");
if (homeButton) {
var homePage = this.getHomePage();
- homePage = homePage.replace(/\|/g, ', ');
+ homePage = homePage.replace(/\|/g, ", ");
if (["about:home", "about:newtab"].includes(homePage.toLowerCase()))
homeButton.setAttribute("tooltiptext", homeButton.getAttribute("aboutHomeOverrideTooltip"));
else
homeButton.setAttribute("tooltiptext", homePage);
}
},
getHomePage() {
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -259,21 +259,21 @@ function getSerializedSecurityInfo(docSh
return serhelper.serializeToString(securityInfo);
}
var AboutNetAndCertErrorListener = {
init(chromeGlobal) {
addMessageListener("CertErrorDetails", this);
addMessageListener("Browser:CaptivePortalFreed", this);
- chromeGlobal.addEventListener('AboutNetErrorLoad', this, false, true);
- chromeGlobal.addEventListener('AboutNetErrorOpenCaptivePortal', this, false, true);
- chromeGlobal.addEventListener('AboutNetErrorSetAutomatic', this, false, true);
- chromeGlobal.addEventListener('AboutNetErrorOverride', this, false, true);
- chromeGlobal.addEventListener('AboutNetErrorResetPreferences', this, false, true);
+ chromeGlobal.addEventListener("AboutNetErrorLoad", this, false, true);
+ chromeGlobal.addEventListener("AboutNetErrorOpenCaptivePortal", this, false, true);
+ chromeGlobal.addEventListener("AboutNetErrorSetAutomatic", this, false, true);
+ chromeGlobal.addEventListener("AboutNetErrorOverride", this, false, true);
+ chromeGlobal.addEventListener("AboutNetErrorResetPreferences", this, false, true);
},
get isAboutNetError() {
return content.document.documentURI.startsWith("about:neterror");
},
get isAboutCertError() {
return content.document.documentURI.startsWith("about:certerror");
@@ -542,21 +542,21 @@ var ClickEventHandler = {
location: ownerDoc.location.href,
elementId: targetElement.getAttribute("id"),
isTopFrame: (ownerDoc.defaultView.parent === ownerDoc.defaultView),
securityInfoAsString: getSerializedSecurityInfo(docShell),
});
},
onAboutBlocked(targetElement, ownerDoc) {
- var reason = 'phishing';
+ var reason = "phishing";
if (/e=malwareBlocked/.test(ownerDoc.documentURI)) {
- reason = 'malware';
+ reason = "malware";
} else if (/e=unwantedBlocked/.test(ownerDoc.documentURI)) {
- reason = 'unwanted';
+ reason = "unwanted";
}
sendAsyncMessage("Browser:SiteBlockedError", {
location: ownerDoc.location.href,
reason,
elementId: targetElement.getAttribute("id"),
isTopFrame: (ownerDoc.defaultView.parent === ownerDoc.defaultView)
});
},
--- a/browser/base/content/contentSearchUI.js
+++ b/browser/base/content/contentSearchUI.js
@@ -618,17 +618,17 @@ ContentSearchUIController.prototype = {
_updateSearchWithHeader() {
if (!this._strings) {
return;
}
let searchWithHeader = document.getElementById("contentSearchSearchWithHeader");
if (this.input.value) {
searchWithHeader.innerHTML = this._strings.searchForSomethingWith;
- searchWithHeader.querySelector('.contentSearchSearchWithHeaderSearchText').textContent = this.input.value;
+ searchWithHeader.querySelector(".contentSearchSearchWithHeaderSearchText").textContent = this.input.value;
} else {
searchWithHeader.textContent = this._strings.searchWithHeader;
}
},
_speculativeConnect() {
if (this.defaultEngine) {
this._sendMsg("SpeculativeConnect", this.defaultEngine.name);
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -147,18 +147,18 @@ const COL_IMAGE_NODE = 5;
const COL_IMAGE_BG = 6;
// column number to copy from, second argument to pageInfoTreeView's constructor
const COPYCOL_NONE = -1;
const COPYCOL_META_CONTENT = 1;
const COPYCOL_IMAGE = COL_IMAGE_ADDRESS;
// one nsITreeView for each tree in the window
-var gMetaView = new pageInfoTreeView('metatree', COPYCOL_META_CONTENT);
-var gImageView = new pageInfoTreeView('imagetree', COPYCOL_IMAGE);
+var gMetaView = new pageInfoTreeView("metatree", COPYCOL_META_CONTENT);
+var gImageView = new pageInfoTreeView("imagetree", COPYCOL_IMAGE);
gImageView.getCellProperties = function(row, col) {
var data = gImageView.data[row];
var item = gImageView.data[row][COL_IMAGE_NODE];
var props = "";
if (!checkProtocol(data) ||
item instanceof HTMLEmbedElement ||
(item instanceof HTMLObjectElement && !item.type.startsWith("image/")))
@@ -1000,31 +1000,31 @@ function formatNumber(number) {
function formatDate(datestr, unknown) {
var date = new Date(datestr);
if (!date.valueOf())
return unknown;
const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
.getService(Components.interfaces.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric',
- hour: 'numeric', minute: 'numeric', second: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric",
+ hour: "numeric", minute: "numeric", second: "numeric" };
return date.toLocaleString(locale, dtOptions);
}
function doCopy() {
if (!gClipboardHelper)
return;
var elem = document.commandDispatcher.focusedElement;
if (elem && "treeBoxObject" in elem) {
var view = elem.view;
var selection = view.selection;
- var text = [], tmp = '';
+ var text = [], tmp = "";
var min = {}, max = {};
var count = selection.getRangeCount();
for (var i = 0; i < count; i++) {
selection.getRangeAt(i, min, max);
for (var row = min.value; row <= max.value; row++) {
--- a/browser/base/content/pageinfo/permissions.js
+++ b/browser/base/content/pageinfo/permissions.js
@@ -156,23 +156,23 @@ function onCheckboxClick(aPartId) {
setRadioState(aPartId, perm);
} else {
onRadioClick(aPartId);
command.removeAttribute("disabled");
}
}
function onPluginRadioClick(aEvent) {
- onRadioClick(aEvent.originalTarget.getAttribute("id").split('#')[0]);
+ onRadioClick(aEvent.originalTarget.getAttribute("id").split("#")[0]);
}
function onRadioClick(aPartId) {
var radioGroup = document.getElementById(aPartId + "RadioGroup");
var id = radioGroup.selectedItem.id;
- var permission = id.split('#')[1];
+ var permission = id.split("#")[1];
SitePermissions.set(gPermURI, aPartId, permission);
}
function setRadioState(aPartId, aValue) {
var radio = document.getElementById(aPartId + "#" + aValue);
if (radio) {
radio.radioGroup.selectedItem = radio;
}
--- a/browser/base/content/tab-content.js
+++ b/browser/base/content/tab-content.js
@@ -100,17 +100,17 @@ addMessageListener("SecondScreen:tab-mir
let height = content.innerHeight;
let viewport = {cssWidth: width, cssHeight: height, width, height};
app.mirror(function() {}, content, viewport, function() {}, content);
}
});
var AboutHomeListener = {
init(chromeGlobal) {
- chromeGlobal.addEventListener('AboutHomeLoad', this, false, true);
+ chromeGlobal.addEventListener("AboutHomeLoad", this, false, true);
},
get isAboutHome() {
return content.document.documentURI.toLowerCase() == "about:home";
},
handleEvent(aEvent) {
if (!this.isAboutHome) {
--- a/browser/base/content/test/general/browser_aboutCertError.js
+++ b/browser/base/content/test/general/browser_aboutCertError.js
@@ -374,17 +374,17 @@ function getCertChain(securityInfoAsStri
certChain += getPEMString(cert);
}
return certChain;
}
function getDERString(cert) {
var length = {};
var derArray = cert.getRawDER(length);
- var derString = '';
+ var derString = "";
for (var i = 0; i < derArray.length; i++) {
derString += String.fromCharCode(derArray[i]);
}
return derString;
}
function getPEMString(cert) {
var derb64 = btoa(getDERString(cert));
--- a/browser/base/content/test/general/browser_blob-channelname.js
+++ b/browser/base/content/test/general/browser_blob-channelname.js
@@ -1,11 +1,11 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://gre/modules/NetUtil.jsm");
function test() {
- var file = new File([new Blob(['test'], {type: 'text/plain'})], "test-name");
+ var file = new File([new Blob(["test"], {type: "text/plain"})], "test-name");
var url = URL.createObjectURL(file);
var channel = NetUtil.newChannel({uri: url, loadUsingSystemPrincipal: true});
- is(channel.contentDispositionFilename, 'test-name', "filename matches");
+ is(channel.contentDispositionFilename, "test-name", "filename matches");
}
--- a/browser/base/content/test/general/browser_bookmark_titles.js
+++ b/browser/base/content/test/general/browser_bookmark_titles.js
@@ -1,27 +1,27 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This file is tests for the default titles that new bookmarks get.
var tests = [
// Common page.
- ['http://example.com/browser/browser/base/content/test/general/dummy_page.html',
- 'Dummy test page'],
+ ["http://example.com/browser/browser/base/content/test/general/dummy_page.html",
+ "Dummy test page"],
// Data URI.
- ['data:text/html;charset=utf-8,<title>test%20data:%20url</title>',
- 'test data: url'],
+ ["data:text/html;charset=utf-8,<title>test%20data:%20url</title>",
+ "test data: url"],
// about:neterror
- ['data:application/vnd.mozilla.xul+xml,',
- 'data:application/vnd.mozilla.xul+xml,'],
+ ["data:application/vnd.mozilla.xul+xml,",
+ "data:application/vnd.mozilla.xul+xml,"],
// about:certerror
- ['https://untrusted.example.com/somepage.html',
- 'https://untrusted.example.com/somepage.html']
+ ["https://untrusted.example.com/somepage.html",
+ "https://untrusted.example.com/somepage.html"]
];
add_task(function* () {
gBrowser.selectedTab = gBrowser.addTab();
let browser = gBrowser.selectedBrowser;
browser.stop(); // stop the about:blank load.
// Test that a bookmark of each URI gets the corresponding default title.
@@ -35,35 +35,35 @@ add_task(function* () {
}
// Network failure test: now that dummy_page.html is in history, bookmarking
// it should give the last known page title as the default bookmark title.
// Simulate a network outage with offline mode. (Localhost is still
// accessible in offline mode, so disable the test proxy as well.)
BrowserOffline.toggleOfflineStatus();
- let proxy = Services.prefs.getIntPref('network.proxy.type');
- Services.prefs.setIntPref('network.proxy.type', 0);
+ let proxy = Services.prefs.getIntPref("network.proxy.type");
+ Services.prefs.setIntPref("network.proxy.type", 0);
registerCleanupFunction(function() {
BrowserOffline.toggleOfflineStatus();
- Services.prefs.setIntPref('network.proxy.type', proxy);
+ Services.prefs.setIntPref("network.proxy.type", proxy);
});
// LOAD_FLAGS_BYPASS_CACHE isn't good enough. So clear the cache.
Services.cache2.clear();
let [uri, title] = tests[0];
let promiseLoaded = promisePageLoaded(browser);
BrowserTestUtils.loadURI(browser, uri);
yield promiseLoaded;
// The offline mode test is only good if the page failed to load.
yield ContentTask.spawn(browser, null, function() {
- is(content.document.documentURI.substring(0, 14), 'about:neterror',
+ is(content.document.documentURI.substring(0, 14), "about:neterror",
"Offline mode successfully simulated network outage.");
});
yield checkBookmark(uri, title);
gBrowser.removeCurrentTab();
});
// Bookmark the current page and confirm that the new bookmark has the expected
--- a/browser/base/content/test/general/browser_bug1045809.js
+++ b/browser/base/content/test/general/browser_bug1045809.js
@@ -32,31 +32,31 @@ add_task(function* () {
// Test 3: mixed content must be blocked again
yield promiseTabLoadEvent(tab);
yield* test3(gBrowser.getBrowserForTab(tab));
});
function* test1(gTestBrowser) {
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
- var x = content.document.getElementsByTagName('iframe')[0].contentDocument.getElementById('mixedContentContainer');
+ var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
is(x, null, "Mixed Content is NOT to be found in Test1");
// Disable Mixed Content Protection for the page (and reload)
gIdentityHandler.disableMixedContentProtection();
}
function* test2(gTestBrowser) {
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
- var x = content.document.getElementsByTagName('iframe')[0].contentDocument.getElementById('mixedContentContainer');
+ var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
isnot(x, null, "Mixed Content is to be found in Test2");
// Re-enable Mixed Content Protection for the page (and reload)
gIdentityHandler.enableMixedContentProtection();
}
function* test3(gTestBrowser) {
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
- var x = content.document.getElementsByTagName('iframe')[0].contentDocument.getElementById('mixedContentContainer');
+ var x = content.document.getElementsByTagName("iframe")[0].contentDocument.getElementById("mixedContentContainer");
is(x, null, "Mixed Content is NOT to be found in Test3");
}
--- a/browser/base/content/test/general/browser_bug1261299.js
+++ b/browser/base/content/test/general/browser_bug1261299.js
@@ -6,17 +6,17 @@
/**
* Tests for Bug 1261299
* Test that the service menu code path is called properly and the
* current selection (transferable) is cached properly on the parent process.
*/
add_task(function* test_content_and_chrome_selection() {
let testPage =
- 'data:text/html,' +
+ "data:text/html," +
'<textarea id="textarea">Write something here</textarea>';
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
let selectedText;
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
{shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
@@ -35,20 +35,20 @@ add_task(function* test_content_and_chro
// Test switching active selection.
// Each tab has a content selection and when you switch to that tab, its selection becomes
// active aka the current selection.
// Expect: The active selection is what is being sent to OSX service menu.
add_task(function* test_active_selection_switches_properly() {
let testPage1 =
- 'data:text/html,' +
+ "data:text/html," +
'<textarea id="textarea">Write something here</textarea>';
let testPage2 =
- 'data:text/html,' +
+ "data:text/html," +
'<textarea id="textarea">Nothing available</textarea>';
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
let selectedText;
let tab1 = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage1);
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, gBrowser.selectedBrowser);
yield BrowserTestUtils.synthesizeKey("KEY_ArrowRight",
{shiftKey: true, ctrlKey: true, code: "ArrowRight"}, gBrowser.selectedBrowser);
--- a/browser/base/content/test/general/browser_bug1297539.js
+++ b/browser/base/content/test/general/browser_bug1297539.js
@@ -49,48 +49,48 @@ function* cutCurrentSelection(elementQue
`${contentElementQueryString} should be empty after cut (superkey + x)`);
});
}
// Test that you are able to pasteTransferable for plain text
// which is handled by TextEditor::PasteTransferable to paste into the editor.
add_task(function* test_paste_transferable_plain_text() {
let testPage =
- 'data:text/html,' +
+ "data:text/html," +
'<textarea id="textarea">Write something here</textarea>';
yield BrowserTestUtils.withNewTab(testPage, function* (browser) {
// Select all the content in your editor element.
yield BrowserTestUtils.synthesizeMouse("#textarea", 0, 0, {}, browser);
yield BrowserTestUtils.synthesizeKey("a", {accelKey: true}, browser);
yield* cutCurrentSelection("#textarea", "value", browser);
let trans = getTransferableFromClipboard(false);
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
DOMWindowUtils.sendContentCommandEvent("pasteTransferable", trans);
yield ContentTask.spawn(browser, null, function* () {
- let textArea = content.document.querySelector('#textarea');
+ let textArea = content.document.querySelector("#textarea");
is(textArea.value, "Write something here",
"Send content command pasteTransferable successful");
});
});
});
// Test that you are able to pasteTransferable for html
// which is handled by HTMLEditor::PasteTransferable to paste into the editor.
//
// On Linux,
// BrowserTestUtils.synthesizeKey("a", {accelKey: true}, browser);
// doesn't seem to trigger for contenteditable which is why we use
// Selection to select the contenteditable contents.
add_task(function* test_paste_transferable_html() {
let testPage =
- 'data:text/html,' +
+ "data:text/html," +
'<div contenteditable="true"><b>Bold Text</b><i>italics</i></div>';
yield BrowserTestUtils.withNewTab(testPage, function* (browser) {
// Select all the content in your editor element.
yield BrowserTestUtils.synthesizeMouse("div", 0, 0, {}, browser);
yield ContentTask.spawn(browser, {}, function* () {
let element = content.document.querySelector("div");
let selection = content.window.getSelection();
@@ -99,14 +99,14 @@ add_task(function* test_paste_transferab
yield* cutCurrentSelection("div", "textContent", browser);
let trans = getTransferableFromClipboard(true);
let DOMWindowUtils = EventUtils._getDOMWindowUtils(window);
DOMWindowUtils.sendContentCommandEvent("pasteTransferable", trans);
yield ContentTask.spawn(browser, null, function* () {
- let textArea = content.document.querySelector('div');
+ let textArea = content.document.querySelector("div");
is(textArea.innerHTML, "<b>Bold Text</b><i>italics</i>",
"Send content command pasteTransferable successful");
});
});
});
--- a/browser/base/content/test/general/browser_bug321000.js
+++ b/browser/base/content/test/general/browser_bug321000.js
@@ -5,22 +5,22 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const kTestString = " hello hello \n world\nworld ";
var gTests = [
{ desc: "Urlbar strips newlines and surrounding whitespace",
element: gURLBar,
- expected: kTestString.replace(/\s*\n\s*/g, '')
+ expected: kTestString.replace(/\s*\n\s*/g, "")
},
{ desc: "Searchbar replaces newlines with spaces",
- element: document.getElementById('searchbar'),
- expected: kTestString.replace(/\n/g, ' ')
+ element: document.getElementById("searchbar"),
+ expected: kTestString.replace(/\n/g, " ")
},
];
// Test for bug 23485 and bug 321000.
// Urlbar should strip newlines,
// search bar should replace newlines with spaces.
function test() {
--- a/browser/base/content/test/general/browser_bug423833.js
+++ b/browser/base/content/test/general/browser_bug423833.js
@@ -1,13 +1,13 @@
/* Tests for proper behaviour of "Show this frame" context menu options */
// Two frames, one with text content, the other an error page
-var invalidPage = 'http://127.0.0.1:55555/';
-var validPage = 'http://example.com/';
+var invalidPage = "http://127.0.0.1:55555/";
+var validPage = "http://example.com/";
var testPage = 'data:text/html,<frameset cols="400,400"><frame src="' + validPage + '"><frame src="' + invalidPage + '"></frameset>';
// Store the tab and window created in tests 2 and 3 respectively
var test2tab;
var test3window;
// We use setInterval instead of setTimeout to avoid race conditions on error doc loads
var intervalID;
--- a/browser/base/content/test/general/browser_bug427559.js
+++ b/browser/base/content/test/general/browser_bug427559.js
@@ -2,19 +2,19 @@
/*
* Test bug 427559 to make sure focused elements that are no longer on the page
* will have focus transferred to the window when changing tabs back to that
* tab with the now-gone element.
*/
// Default focus on a button and have it kill itself on blur.
-const URL = 'data:text/html;charset=utf-8,' +
+const URL = "data:text/html;charset=utf-8," +
'<body><button onblur="this.remove()">' +
- '<script>document.body.firstChild.focus()</script></body>';
+ "<script>document.body.firstChild.focus()</script></body>";
function getFocusedLocalName(browser) {
return ContentTask.spawn(browser, null, function* () {
return content.document.activeElement.localName;
});
}
add_task(function* () {
--- a/browser/base/content/test/general/browser_bug553455.js
+++ b/browser/base/content/test/general/browser_bug553455.js
@@ -8,23 +8,23 @@ const SECUREROOT = "https://example.com/
const XPINSTALL_URL = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul";
const PREF_INSTALL_REQUIREBUILTINCERTS = "extensions.install.requireBuiltInCerts";
const PROGRESS_NOTIFICATION = "addon-progress";
const { REQUIRE_SIGNING } = Cu.import("resource://gre/modules/addons/AddonConstants.jsm", {});
const { Task } = Cu.import("resource://gre/modules/Task.jsm", {});
var rootDir = getRootDirectory(gTestPath);
-var rootPath = rootDir.split('/');
-var chromeName = rootPath[0] + '//' + rootPath[2];
+var rootPath = rootDir.split("/");
+var chromeName = rootPath[0] + "//" + rootPath[2];
var croot = chromeName + "/content/browser/toolkit/mozapps/extensions/test/xpinstall/";
var jar = getJar(croot);
if (jar) {
var tmpdir = extractJarToTmp(jar);
- croot = 'file://' + tmpdir.path + '/';
+ croot = "file://" + tmpdir.path + "/";
}
const CHROMEROOT = croot;
var gApp = document.getElementById("bundle_brand").getString("brandShortName");
var gVersion = Services.appinfo.version;
function getObserverTopic(aNotificationId) {
let topic = aNotificationId;
--- a/browser/base/content/test/general/browser_bug561636.js
+++ b/browser/base/content/test/general/browser_bug561636.js
@@ -1,19 +1,19 @@
-var gInvalidFormPopup = document.getElementById('invalid-form-popup');
+var gInvalidFormPopup = document.getElementById("invalid-form-popup");
ok(gInvalidFormPopup,
"The browser should have a popup to show when a form is invalid");
function checkPopupShow() {
- ok(gInvalidFormPopup.state == 'showing' || gInvalidFormPopup.state == 'open',
+ ok(gInvalidFormPopup.state == "showing" || gInvalidFormPopup.state == "open",
"[Test " + testId + "] The invalid form popup should be shown");
}
function checkPopupHide() {
- ok(gInvalidFormPopup.state != 'showing' && gInvalidFormPopup.state != 'open',
+ ok(gInvalidFormPopup.state != "showing" && gInvalidFormPopup.state != "open",
"[Test " + testId + "] The invalid form popup should not be shown");
}
var gObserver = {
QueryInterface : XPCOMUtils.generateQI([Ci.nsIFormSubmitObserver]),
notifyInvalidSubmit(aFormElement, aInvalidElements) {
}
@@ -46,34 +46,34 @@ function* openNewTab(uri, background) {
gBrowser.selectedTab = tab;
}
yield promiseTabLoadEvent(tab, "data:text/html," + escape(uri));
return browser;
}
function* clickChildElement(browser) {
yield ContentTask.spawn(browser, {}, function* () {
- content.document.getElementById('s').click();
+ content.document.getElementById("s").click();
});
}
function* blurChildElement(browser) {
yield ContentTask.spawn(browser, {}, function* () {
- content.document.getElementById('i').blur();
+ content.document.getElementById("i").blur();
});
}
function* checkChildFocus(browser, message) {
yield ContentTask.spawn(browser, [message, testId], function* (args) {
let [msg, id] = args;
- var focused = content.document.activeElement == content.document.getElementById('i');
+ var focused = content.document.activeElement == content.document.getElementById("i");
var validMsg = true;
if (msg) {
- validMsg = (msg == content.document.getElementById('i').validationMessage);
+ validMsg = (msg == content.document.getElementById("i").validationMessage);
}
Assert.equal(focused, true, "Test " + id + " First invalid element should be focused");
Assert.equal(validMsg, true, "Test " + id + " The panel should show the message from validationMessage");
});
}
/**
@@ -280,17 +280,17 @@ add_task(function* () {
gObserver.notifyInvalidSubmit = function() {};
resolve();
});
};
Services.obs.addObserver(gObserver, "invalidformsubmit", false);
executeSoon(function() {
- browser.contentDocument.getElementById('s').click();
+ browser.contentDocument.getElementById("s").click();
});
});
yield notifierPromise;
gBrowser.removeTab(gBrowser.getTabForBrowser(browser));
});
@@ -325,18 +325,18 @@ add_task(function* () {
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield clickChildElement(browser);
yield popupShownPromise;
checkPopupShow();
yield checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
- let inputPromise = promiseWaitForEvent(gBrowser.contentDocument.getElementById('i'), "input");
- EventUtils.synthesizeKey('f', {});
+ let inputPromise = promiseWaitForEvent(gBrowser.contentDocument.getElementById("i"), "input");
+ EventUtils.synthesizeKey("f", {});
yield inputPromise;
// Now, the element suffers from another error, the message should have
// been updated.
yield new Promise((resolve, reject) => {
// XXXndeakin This isn't really going to work when the content is another process
executeSoon(function() {
checkChildFocus(browser, gInvalidFormPopup.firstChild.textContent);
--- a/browser/base/content/test/general/browser_bug595507.js
+++ b/browser/base/content/test/general/browser_bug595507.js
@@ -1,36 +1,36 @@
/**
* Make sure that the form validation error message shows even if the form is in an iframe.
*/
add_task(function* () {
let uri = "<iframe src=\"data:text/html,<iframe name='t'></iframe><form target='t' action='data:text/html,'><input required id='i'><input id='s' type='submit'></form>\"</iframe>";
- var gInvalidFormPopup = document.getElementById('invalid-form-popup');
+ var gInvalidFormPopup = document.getElementById("invalid-form-popup");
ok(gInvalidFormPopup,
"The browser should have a popup to show when a form is invalid");
let tab = gBrowser.addTab();
let browser = gBrowser.getBrowserForTab(tab);
gBrowser.selectedTab = tab;
yield promiseTabLoadEvent(tab, "data:text/html," + escape(uri));
let popupShownPromise = promiseWaitForEvent(gInvalidFormPopup, "popupshown");
yield ContentTask.spawn(browser, {}, function* () {
- content.document.getElementsByTagName('iframe')[0]
- .contentDocument.getElementById('s').click();
+ content.document.getElementsByTagName("iframe")[0]
+ .contentDocument.getElementById("s").click();
});
yield popupShownPromise;
yield ContentTask.spawn(browser, {}, function* () {
- let childdoc = content.document.getElementsByTagName('iframe')[0].contentDocument;
+ let childdoc = content.document.getElementsByTagName("iframe")[0].contentDocument;
Assert.equal(childdoc.activeElement, childdoc.getElementById("i"),
"First invalid element should be focused");
});
- ok(gInvalidFormPopup.state == 'showing' || gInvalidFormPopup.state == 'open',
+ ok(gInvalidFormPopup.state == "showing" || gInvalidFormPopup.state == "open",
"The invalid form popup should be shown");
gBrowser.removeCurrentTab();
});
--- a/browser/base/content/test/general/browser_bug633691.js
+++ b/browser/base/content/test/general/browser_bug633691.js
@@ -6,30 +6,30 @@ function test() {
waitForExplicitFinish();
gBrowser.selectedTab = gBrowser.addTab("data:text/html,<iframe width='700' height='700'></iframe>");
// Open a html page with about:certerror in an iframe
BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser).then(function() {
return ContentTask.spawn(gBrowser.selectedBrowser, "", function() {
return new Promise(resolve => {
info("Running content task");
let listener = e => {
- removeEventListener('AboutNetErrorLoad', listener, false, true);
+ removeEventListener("AboutNetErrorLoad", listener, false, true);
resolve();
};
- addEventListener('AboutNetErrorLoad', listener, false, true);
+ addEventListener("AboutNetErrorLoad", listener, false, true);
let iframe = content.document.querySelector("iframe");
iframe.src = "https://expired.example.com/";
});
}).then(testIframeCert);
});
}
function testIframeCert(e) {
// Confirm that the expert section is hidden
- var doc = gBrowser.contentDocument.getElementsByTagName('iframe')[0].contentDocument;
+ var doc = gBrowser.contentDocument.getElementsByTagName("iframe")[0].contentDocument;
var aP = doc.getElementById("badCertAdvancedPanel");
ok(aP, "Advanced content should exist");
is_element_hidden(aP, "Advanced content should not be visible by default")
// Clean up
gBrowser.removeCurrentTab();
finish();
--- a/browser/base/content/test/general/browser_bug822367.js
+++ b/browser/base/content/test/general/browser_bug822367.js
@@ -47,20 +47,20 @@ function MixedTest1A() {
gTestBrowser.addEventListener("load", MixedTest1B, true);
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
let {gIdentityHandler} = gTestBrowser.ownerGlobal;
gIdentityHandler.disableMixedContentProtection();
}
function MixedTest1B() {
- waitForCondition(() => content.document.getElementById('p1').innerHTML == "hello", MixedTest1C, "Waited too long for mixed script to run in Test 1");
+ waitForCondition(() => content.document.getElementById("p1").innerHTML == "hello", MixedTest1C, "Waited too long for mixed script to run in Test 1");
}
function MixedTest1C() {
- ok(content.document.getElementById('p1').innerHTML == "hello", "Mixed script didn't load in Test 1");
+ ok(content.document.getElementById("p1").innerHTML == "hello", "Mixed script didn't load in Test 1");
gTestBrowser.removeEventListener("load", MixedTest1B, true);
MixedTest2();
}
// Mixed Display Test - Doorhanger should not appear
function MixedTest2() {
gTestBrowser.addEventListener("load", MixedTest2A, true);
var url = gHttpTestRoot2 + "file_bug822367_2.html";
@@ -84,24 +84,24 @@ function MixedTest3A() {
gTestBrowser.addEventListener("load", MixedTest3B, true);
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
let {gIdentityHandler} = gTestBrowser.ownerGlobal;
gIdentityHandler.disableMixedContentProtection();
}
function MixedTest3B() {
- waitForCondition(() => content.document.getElementById('p1').innerHTML == "hello", MixedTest3C, "Waited too long for mixed script to run in Test 3");
+ waitForCondition(() => content.document.getElementById("p1").innerHTML == "hello", MixedTest3C, "Waited too long for mixed script to run in Test 3");
}
function MixedTest3C() {
- waitForCondition(() => content.document.getElementById('p2').innerHTML == "bye", MixedTest3D, "Waited too long for mixed image to load in Test 3");
+ waitForCondition(() => content.document.getElementById("p2").innerHTML == "bye", MixedTest3D, "Waited too long for mixed image to load in Test 3");
}
function MixedTest3D() {
- ok(content.document.getElementById('p1').innerHTML == "hello", "Mixed script didn't load in Test 3");
- ok(content.document.getElementById('p2').innerHTML == "bye", "Mixed image didn't load in Test 3");
+ ok(content.document.getElementById("p1").innerHTML == "hello", "Mixed script didn't load in Test 3");
+ ok(content.document.getElementById("p2").innerHTML == "bye", "Mixed image didn't load in Test 3");
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: true});
MixedTest4();
}
// Location change - User override on one page doesn't propogate to another page after location change.
function MixedTest4() {
gTestBrowser.removeEventListener("load", MixedTest3B, true);
gTestBrowser.addEventListener("load", MixedTest4A, true);
@@ -120,20 +120,20 @@ function MixedTest4A() {
function MixedTest4B() {
waitForCondition(() => content.document.location == gHttpTestRoot + "file_bug822367_4B.html", MixedTest4C, "Waited too long for mixed script to run in Test 4");
}
function MixedTest4C() {
ok(content.document.location == gHttpTestRoot + "file_bug822367_4B.html", "Location didn't change in test 4");
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
- waitForCondition(() => content.document.getElementById('p1').innerHTML == "", MixedTest4D, "Mixed script loaded in test 4 after location change!");
+ waitForCondition(() => content.document.getElementById("p1").innerHTML == "", MixedTest4D, "Mixed script loaded in test 4 after location change!");
}
function MixedTest4D() {
- ok(content.document.getElementById('p1').innerHTML == "", "p1.innerHTML changed; mixed script loaded after location change in Test 4");
+ ok(content.document.getElementById("p1").innerHTML == "", "p1.innerHTML changed; mixed script loaded after location change in Test 4");
MixedTest5();
}
// Mixed script attempts to load in a document.open()
function MixedTest5() {
gTestBrowser.removeEventListener("load", MixedTest4B, true);
gTestBrowser.addEventListener("load", MixedTest5A, true);
var url = gHttpTestRoot + "file_bug822367_5.html";
@@ -144,20 +144,20 @@ function MixedTest5A() {
gTestBrowser.addEventListener("load", MixedTest5B, true);
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
let {gIdentityHandler} = gTestBrowser.ownerGlobal;
gIdentityHandler.disableMixedContentProtection();
}
function MixedTest5B() {
- waitForCondition(() => content.document.getElementById('p1').innerHTML == "hello", MixedTest5C, "Waited too long for mixed script to run in Test 5");
+ waitForCondition(() => content.document.getElementById("p1").innerHTML == "hello", MixedTest5C, "Waited too long for mixed script to run in Test 5");
}
function MixedTest5C() {
- ok(content.document.getElementById('p1').innerHTML == "hello", "Mixed script didn't load in Test 5");
+ ok(content.document.getElementById("p1").innerHTML == "hello", "Mixed script didn't load in Test 5");
MixedTest6();
}
// Mixed script attempts to load in a document.open() that is within an iframe.
function MixedTest6() {
gTestBrowser.removeEventListener("load", MixedTest5B, true);
gTestBrowser.addEventListener("load", MixedTest6A, true);
var url = gHttpTestRoot2 + "file_bug822367_6.html";
@@ -177,19 +177,19 @@ function MixedTest6B() {
let {gIdentityHandler} = gTestBrowser.ownerGlobal;
gIdentityHandler.disableMixedContentProtection();
}
function MixedTest6C() {
gTestBrowser.removeEventListener("load", MixedTest6C, true);
waitForCondition(function() {
try {
- return content.document.getElementById('f1').contentDocument.getElementById('p1').innerHTML == "hello";
+ return content.document.getElementById("f1").contentDocument.getElementById("p1").innerHTML == "hello";
} catch (e) {
return false;
}
}, MixedTest6D, "Waited too long for mixed script to run in Test 6");
}
function MixedTest6D() {
- ok(content.document.getElementById('f1').contentDocument.getElementById('p1').innerHTML == "hello", "Mixed script didn't load in Test 6");
+ ok(content.document.getElementById("f1").contentDocument.getElementById("p1").innerHTML == "hello", "Mixed script didn't load in Test 6");
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
MixedTestsCompleted();
}
--- a/browser/base/content/test/general/browser_bug839103.js
+++ b/browser/base/content/test/general/browser_bug839103.js
@@ -41,20 +41,20 @@ function continueTest() {
let doc = gBrowser.contentDocument;
doc.styleSheetChangeEventsEnabled = true;
doc.addEventListener("StyleSheetAdded", unexpectedContentEvent);
doc.addEventListener("StyleSheetRemoved", unexpectedContentEvent);
doc.addEventListener("StyleSheetApplicableStateChanged", unexpectedContentEvent);
doc.defaultView.addEventListener("StyleSheetAdded", unexpectedContentEvent);
doc.defaultView.addEventListener("StyleSheetRemoved", unexpectedContentEvent);
doc.defaultView.addEventListener("StyleSheetApplicableStateChanged", unexpectedContentEvent);
- let link = doc.createElement('link');
- link.setAttribute('rel', 'stylesheet');
- link.setAttribute('type', 'text/css');
- link.setAttribute('href', gTestRoot + gStyleSheet);
+ let link = doc.createElement("link");
+ link.setAttribute("rel", "stylesheet");
+ link.setAttribute("type", "text/css");
+ link.setAttribute("href", gTestRoot + gStyleSheet);
gLinkElement = link;
gBrowser.addEventListener("StyleSheetAdded", dynamicStylesheetAdded, true);
gBrowser.addEventListener("StyleSheetApplicableStateChanged", dynamicStylesheetApplicableStateChanged, true);
doc.body.appendChild(link);
}
function dynamicStylesheetAdded(evt) {
--- a/browser/base/content/test/general/browser_bug902156.js
+++ b/browser/base/content/test/general/browser_bug902156.js
@@ -52,38 +52,38 @@ function test1A() {
// Disable Mixed Content Protection for the page (and reload)
let {gIdentityHandler} = gTestBrowser.ownerGlobal;
gIdentityHandler.disableMixedContentProtection();
}
function test1B() {
var expected = "Mixed Content Blocker disabled";
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test1C, "Error: Waited too long for mixed script to run in Test 1B");
}
function test1C() {
- var actual = content.document.getElementById('mctestdiv').innerHTML;
+ var actual = content.document.getElementById("mctestdiv").innerHTML;
is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 1C");
// The Script loaded after we disabled the page, now we are going to reload the
// page and see if our decision is persistent
BrowserTestUtils.browserLoaded(gTestBrowser).then(test1D);
var url = gHttpTestRoot1 + "file_bug902156_2.html";
gTestBrowser.loadURI(url);
}
function test1D() {
// The Control Center button should appear but isMixedContentBlocked should be NOT true,
// because our decision of disabling the mixed content blocker is persistent.
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
- var actual = content.document.getElementById('mctestdiv').innerHTML;
+ var actual = content.document.getElementById("mctestdiv").innerHTML;
is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 1D");
// move on to Test 2
test2();
}
// ------------------------ Test 2 ------------------------------
@@ -101,39 +101,39 @@ function test2A() {
// Disable Mixed Content Protection for the page (and reload)
let {gIdentityHandler} = gTestBrowser.ownerGlobal;
gIdentityHandler.disableMixedContentProtection();
}
function test2B() {
var expected = "Mixed Content Blocker disabled";
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test2C, "Error: Waited too long for mixed script to run in Test 2B");
}
function test2C() {
- var actual = content.document.getElementById('mctestdiv').innerHTML;
+ var actual = content.document.getElementById("mctestdiv").innerHTML;
is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 2C");
// The Script loaded after we disabled the page, now we are going to reload the
// page and see if our decision is persistent
BrowserTestUtils.browserLoaded(gTestBrowser).then(test2D);
// reload the page using the provided link in the html file
var mctestlink = content.document.getElementById("mctestlink");
mctestlink.click();
}
function test2D() {
// The Control Center button should appear but isMixedContentBlocked should be NOT true,
// because our decision of disabling the mixed content blocker is persistent.
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: true, activeBlocked: false, passiveLoaded: false});
- var actual = content.document.getElementById('mctestdiv').innerHTML;
+ var actual = content.document.getElementById("mctestdiv").innerHTML;
is(actual, "Mixed Content Blocker disabled", "OK: Executed mixed script in Test 2D");
// move on to Test 3
test3();
}
// ------------------------ Test 3 ------------------------------
--- a/browser/base/content/test/general/browser_bug906190.js
+++ b/browser/base/content/test/general/browser_bug906190.js
@@ -29,17 +29,17 @@ function* doTest(parentTabSpec, childTab
});
// Disable the Mixed Content Blocker for the page, which reloads it.
let promiseReloaded = BrowserTestUtils.browserLoaded(browser);
gIdentityHandler.disableMixedContentProtection();
yield promiseReloaded;
// Wait for the script in the page to update the contents of the test div.
- let testDiv = content.document.getElementById('mctestdiv');
+ let testDiv = content.document.getElementById("mctestdiv");
yield promiseWaitForCondition(
() => testDiv.innerHTML == "Mixed Content Blocker disabled");
// Add the link for the child tab to the page.
let mainDiv = content.document.createElement("div");
mainDiv.innerHTML =
'<p><a id="linkToOpenInNewTab" href="' + childTabSpec + '">Link</a></p>';
content.document.body.appendChild(mainDiv);
@@ -115,17 +115,17 @@ add_task(function* test_same_origin() {
gHttpTestRoot1 + "file_bug906190_2.html", function* () {
// The doorhanger should appear but activeBlocked should be >> NOT << true,
// because our decision of disabling the mixed content blocker is persistent
// across tabs.
yield assertMixedContentBlockingState(gBrowser, {
activeLoaded: true, activeBlocked: false, passiveLoaded: false,
});
- is(content.document.getElementById('mctestdiv').innerHTML,
+ is(content.document.getElementById("mctestdiv").innerHTML,
"Mixed Content Blocker disabled", "OK: Executed mixed script");
});
});
/**
* 2. - Load a html page which has mixed content
* - Doorhanger to disable protection appears - we disable it
* - Load a new page from a different origin in a new tab simulating a click
@@ -136,17 +136,17 @@ add_task(function* test_different_origin
gHttpTestRoot2 + "file_bug906190_2.html", function* () {
// The doorhanger should appear and activeBlocked should be >> TRUE <<,
// because our decision of disabling the mixed content blocker should only
// persist if pages are from the same domain.
yield assertMixedContentBlockingState(gBrowser, {
activeLoaded: false, activeBlocked: true, passiveLoaded: false,
});
- is(content.document.getElementById('mctestdiv').innerHTML,
+ is(content.document.getElementById("mctestdiv").innerHTML,
"Mixed Content Blocker enabled", "OK: Blocked mixed script");
});
});
/**
* 3. - Load a html page which has mixed content
* - Doorhanger to disable protection appears - we disable it
* - Load a new page from the same origin in a new tab simulating a click
@@ -157,17 +157,17 @@ add_task(function* test_same_origin_meta
// file_bug906190_3_4.html redirects to page test1.example.com/* using meta-refresh
yield doTest(gHttpTestRoot1 + "file_bug906190_1.html",
gHttpTestRoot1 + "file_bug906190_3_4.html", function* () {
// The doorhanger should appear but activeBlocked should be >> NOT << true!
yield assertMixedContentBlockingState(gBrowser, {
activeLoaded: true, activeBlocked: false, passiveLoaded: false,
});
- is(content.document.getElementById('mctestdiv').innerHTML,
+ is(content.document.getElementById("mctestdiv").innerHTML,
"Mixed Content Blocker disabled", "OK: Executed mixed script");
}, true);
});
/**
* 4. - Load a html page which has mixed content
* - Doorhanger to disable protection appears - we disable it
* - Load a new page from the same origin in a new tab simulating a click
@@ -177,17 +177,17 @@ add_task(function* test_same_origin_meta
add_task(function* test_same_origin_metarefresh_different_origin() {
yield doTest(gHttpTestRoot2 + "file_bug906190_1.html",
gHttpTestRoot2 + "file_bug906190_3_4.html", function* () {
// The doorhanger should appear and activeBlocked should be >> TRUE <<.
yield assertMixedContentBlockingState(gBrowser, {
activeLoaded: false, activeBlocked: true, passiveLoaded: false,
});
- is(content.document.getElementById('mctestdiv').innerHTML,
+ is(content.document.getElementById("mctestdiv").innerHTML,
"Mixed Content Blocker enabled", "OK: Blocked mixed script");
}, true);
});
/**
* 5. - Load a html page which has mixed content
* - Doorhanger to disable protection appears - we disable it
* - Load a new page from the same origin in a new tab simulating a click
@@ -197,17 +197,17 @@ add_task(function* test_same_origin_302r
// the sjs files returns a 302 redirect- note, same origins
yield doTest(gHttpTestRoot1 + "file_bug906190_1.html",
gHttpTestRoot1 + "file_bug906190.sjs", function* () {
// The doorhanger should appear but activeBlocked should be >> NOT << true.
// Currently it is >> TRUE << - see follow up bug 914860
ok(!gIdentityHandler._identityBox.classList.contains("mixedActiveBlocked"),
"OK: Mixed Content is NOT being blocked");
- is(content.document.getElementById('mctestdiv').innerHTML,
+ is(content.document.getElementById("mctestdiv").innerHTML,
"Mixed Content Blocker disabled", "OK: Executed mixed script");
});
});
/**
* 6. - Load a html page which has mixed content
* - Doorhanger to disable protection appears - we disable it
* - Load a new page from the same origin in a new tab simulating a click
@@ -217,17 +217,17 @@ add_task(function* test_same_origin_302r
// the sjs files returns a 302 redirect - note, different origins
yield doTest(gHttpTestRoot2 + "file_bug906190_1.html",
gHttpTestRoot2 + "file_bug906190.sjs", function* () {
// The doorhanger should appear and activeBlocked should be >> TRUE <<.
yield assertMixedContentBlockingState(gBrowser, {
activeLoaded: false, activeBlocked: true, passiveLoaded: false,
});
- is(content.document.getElementById('mctestdiv').innerHTML,
+ is(content.document.getElementById("mctestdiv").innerHTML,
"Mixed Content Blocker enabled", "OK: Blocked mixed script");
});
});
/**
* 7. - Test memory leak issue on redirection error. See Bug 1269426.
*/
add_task(function* test_bad_redirection() {
--- a/browser/base/content/test/general/browser_clipboard.js
+++ b/browser/base/content/test/general/browser_clipboard.js
@@ -144,31 +144,31 @@ add_task(function*() {
removeEventListener("paste", copyEvent, true);
let clipboardData = event.clipboardData;
// DataTransfer doesn't support the image types yet, so only text/html
// will be present.
if (clipboardData.getData("text/html") !== arg.htmlPrefix +
'<img id="img" tabindex="1" src="http://example.org/browser/browser/base/content/test/general/moz.png">' +
arg.htmlPostfix) {
- reject('Clipboard Data did not contain an image, was ' + clipboardData.getData("text/html"));
+ reject("Clipboard Data did not contain an image, was " + clipboardData.getData("text/html"));
}
resolve();
}, true)
const utils = content.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindowUtils);
if (utils.sendKeyEvent("keydown", "v", 0, arg.modifier)) {
utils.sendKeyEvent("keypress", "v", "v".charCodeAt(0), arg.modifier);
}
utils.sendKeyEvent("keyup", "v", 0, arg.modifier);
});
// The new content should now include an image.
Assert.equal(main.innerHTML, '<i>Italic</i> <img id="img" tabindex="1" ' +
'src="http://example.org/browser/browser/base/content/test/general/moz.png">' +
- 'Test <b>Bold</b> After<b></b>', "Paste after copy image");
+ "Test <b>Bold</b> After<b></b>", "Paste after copy image");
});
gBrowser.removeCurrentTab();
});
--- a/browser/base/content/test/general/browser_contentAltClick.js
+++ b/browser/base/content/test/general/browser_contentAltClick.js
@@ -16,17 +16,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/Downloads.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesTestUtils",
"resource://testing-common/PlacesTestUtils.jsm");
function setup() {
gPrefService.setBoolPref("browser.altClickSave", true);
let testPage =
- 'data:text/html,' +
+ "data:text/html," +
'<p><a id="commonlink" href="http://mochi.test/moz/">Common link</a></p>' +
'<p><math id="mathxlink" xmlns="http://www.w3.org/1998/Math/MathML" xlink:type="simple" xlink:href="http://mochi.test/moz/"><mtext>MathML XLink</mtext></math></p>' +
'<p><svg id="svgxlink" xmlns="http://www.w3.org/2000/svg" width="100px" height="50px" version="1.1"><a xlink:type="simple" xlink:href="http://mochi.test/moz/"><text transform="translate(10, 25)">SVG XLink</text></a></svg></p>';
return BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
}
function* clean_up() {
--- a/browser/base/content/test/general/browser_csp_block_all_mixedcontent.js
+++ b/browser/base/content/test/general/browser_csp_block_all_mixedcontent.js
@@ -44,12 +44,12 @@ function runTests() {
}
// ------------------------------------------------------
function test() {
// Performing async calls, e.g. 'onload', we have to wait till all of them finished
waitForExplicitFinish();
SpecialPowers.pushPrefEnv(
- { 'set': [["security.mixed_content.block_active_content", true]] },
+ { "set": [["security.mixed_content.block_active_content", true]] },
function() { runTests(); }
);
}
--- a/browser/base/content/test/general/browser_discovery.js
+++ b/browser/base/content/test/general/browser_discovery.js
@@ -39,17 +39,17 @@ function runIconDiscoveryTest() {
var testCase = iconDiscoveryTests[0];
var head = doc().getElementById("linkparent");
var hasSrc = gBrowser.getIcon() != null;
if (testCase.pass)
ok(hasSrc, testCase.text);
else
ok(!hasSrc, testCase.text);
- head.removeChild(head.getElementsByTagName('link')[0]);
+ head.removeChild(head.getElementsByTagName("link")[0]);
iconDiscoveryTests.shift();
iconDiscovery(); // Run the next test.
}
function iconDiscovery() {
if (iconDiscoveryTests.length) {
setHandlerFunc(runIconDiscoveryTest);
gBrowser.setIcon(gBrowser.selectedTab, null,
--- a/browser/base/content/test/general/browser_documentnavigation.js
+++ b/browser/base/content/test/general/browser_documentnavigation.js
@@ -142,17 +142,17 @@ add_task(function* () {
false, "back focus content page urlbar");
});
// Open the sidebar and navigate between the sidebar, content and top-level window
add_task(function* () {
let sidebar = document.getElementById("sidebar");
let loadPromise = BrowserTestUtils.waitForEvent(sidebar, "load", true);
- SidebarUI.toggle('viewBookmarksSidebar');
+ SidebarUI.toggle("viewBookmarksSidebar");
yield loadPromise;
gURLBar.focus();
yield* expectFocusOnF6(false, "bookmarksPanel",
sidebar.contentDocument.getElementById("search-box").inputField,
false, "focus with sidebar open sidebar");
yield* expectFocusOnF6(false, "html1", "html1",
@@ -164,17 +164,17 @@ add_task(function* () {
yield* expectFocusOnF6(true, "html1", "html1",
true, "back focus with sidebar open content");
yield* expectFocusOnF6(true, "bookmarksPanel",
sidebar.contentDocument.getElementById("search-box").inputField,
false, "back focus with sidebar open sidebar");
yield* expectFocusOnF6(true, "main-window", gURLBar.inputField,
false, "back focus with sidebar urlbar");
- SidebarUI.toggle('viewBookmarksSidebar');
+ SidebarUI.toggle("viewBookmarksSidebar");
});
// Navigate when the downloads panel is open
add_task(function* () {
yield pushPrefs(["accessibility.tabfocus", 7]);
let popupShownPromise = BrowserTestUtils.waitForEvent(document, "popupshown", true);
EventUtils.synthesizeMouseAtCenter(document.getElementById("downloads-button"), { });
--- a/browser/base/content/test/general/browser_fxa_oauth.js
+++ b/browser/base/content/test/general/browser_fxa_oauth.js
@@ -135,17 +135,17 @@ var gTests = [
return new Promise(function(resolve, reject) {
let tabOpened = false;
waitForTab(function(tab) {
Assert.ok("Tab successfully opened");
// It should have passed in the expected non-matching state value.
let queryString = gBrowser.currentURI.spec.split("?")[1];
- Assert.ok(queryString.indexOf('state=different-state') >= 0);
+ Assert.ok(queryString.indexOf("state=different-state") >= 0);
tabOpened = true;
});
let client = new FxAccountsOAuthClient({
parameters: {
state: "different-state",
client_id: "client_id",
@@ -172,18 +172,18 @@ var gTests = [
run() {
return new Promise(function(resolve, reject) {
let tabOpened = false;
waitForTab(function(tab) {
Assert.ok("Tab successfully opened");
// It should have asked for keys.
- let queryString = gBrowser.currentURI.spec.split('?')[1];
- Assert.ok(queryString.indexOf('keys=true') >= 0);
+ let queryString = gBrowser.currentURI.spec.split("?")[1];
+ Assert.ok(queryString.indexOf("keys=true") >= 0);
tabOpened = true;
});
let client = new FxAccountsOAuthClient({
parameters: {
state: "state",
client_id: "client_id",
@@ -214,18 +214,18 @@ var gTests = [
run() {
return new Promise(function(resolve, reject) {
let tabOpened = false;
waitForTab(function(tab) {
Assert.ok("Tab successfully opened");
// It should not have asked for keys.
- let queryString = gBrowser.currentURI.spec.split('?')[1];
- Assert.ok(queryString.indexOf('keys=true') == -1);
+ let queryString = gBrowser.currentURI.spec.split("?")[1];
+ Assert.ok(queryString.indexOf("keys=true") == -1);
tabOpened = true;
});
let client = new FxAccountsOAuthClient({
parameters: {
state: "state",
client_id: "client_id",
@@ -255,18 +255,18 @@ var gTests = [
run() {
return new Promise(function(resolve, reject) {
let tabOpened = false;
waitForTab(function(tab) {
Assert.ok("Tab successfully opened");
// It should have asked for keys.
- let queryString = gBrowser.currentURI.spec.split('?')[1];
- Assert.ok(queryString.indexOf('keys=true') >= 0);
+ let queryString = gBrowser.currentURI.spec.split("?")[1];
+ Assert.ok(queryString.indexOf("keys=true") >= 0);
tabOpened = true;
});
let client = new FxAccountsOAuthClient({
parameters: {
state: "state",
client_id: "client_id",
--- a/browser/base/content/test/general/browser_fxa_web_channel.js
+++ b/browser/base/content/test/general/browser_fxa_web_channel.js
@@ -45,22 +45,22 @@ var gTests = [
}
},
{
desc: "fxa web channel - login messages should notify the fxAccounts object",
*run() {
let promiseLogin = new Promise((resolve, reject) => {
let login = (accountData) => {
- Assert.equal(typeof accountData.authAt, 'number');
- Assert.equal(accountData.email, 'testuser@testuser.com');
- Assert.equal(accountData.keyFetchToken, 'key_fetch_token');
- Assert.equal(accountData.sessionToken, 'session_token');
- Assert.equal(accountData.uid, 'uid');
- Assert.equal(accountData.unwrapBKey, 'unwrap_b_key');
+ Assert.equal(typeof accountData.authAt, "number");
+ Assert.equal(accountData.email, "testuser@testuser.com");
+ Assert.equal(accountData.keyFetchToken, "key_fetch_token");
+ Assert.equal(accountData.sessionToken, "session_token");
+ Assert.equal(accountData.uid, "uid");
+ Assert.equal(accountData.unwrapBKey, "unwrap_b_key");
Assert.equal(accountData.verified, true);
client.tearDown();
resolve();
};
let client = new FxAccountsWebChannel({
content_uri: TEST_HTTP_PATH,
@@ -85,34 +85,34 @@ var gTests = [
let properUrl = TEST_BASE_URL + "?can_link_account";
let promiseEcho = new Promise((resolve, reject) => {
let webChannelOrigin = Services.io.newURI(properUrl);
// responses sent to content are echoed back over the
// `fxaccounts_webchannel_response_echo` channel. Ensure the
// fxaccounts:can_link_account message is responded to.
- let echoWebChannel = new WebChannel('fxaccounts_webchannel_response_echo', webChannelOrigin);
+ let echoWebChannel = new WebChannel("fxaccounts_webchannel_response_echo", webChannelOrigin);
echoWebChannel.listen((webChannelId, message, target) => {
- Assert.equal(message.command, 'fxaccounts:can_link_account');
+ Assert.equal(message.command, "fxaccounts:can_link_account");
Assert.equal(message.messageId, 2);
Assert.equal(message.data.ok, true);
client.tearDown();
echoWebChannel.stopListening();
resolve();
});
let client = new FxAccountsWebChannel({
content_uri: TEST_HTTP_PATH,
channel_id: TEST_CHANNEL_ID,
helpers: {
shouldAllowRelink(acctName) {
- return acctName === 'testuser@testuser.com';
+ return acctName === "testuser@testuser.com";
}
}
});
});
yield BrowserTestUtils.withNewTab({
gBrowser,
url: properUrl
@@ -121,17 +121,17 @@ var gTests = [
});
}
},
{
desc: "fxa web channel - logout messages should notify the fxAccounts object",
*run() {
let promiseLogout = new Promise((resolve, reject) => {
let logout = (uid) => {
- Assert.equal(uid, 'uid');
+ Assert.equal(uid, "uid");
client.tearDown();
resolve();
};
let client = new FxAccountsWebChannel({
content_uri: TEST_HTTP_PATH,
channel_id: TEST_CHANNEL_ID,
@@ -149,17 +149,17 @@ var gTests = [
});
}
},
{
desc: "fxa web channel - delete messages should notify the fxAccounts object",
*run() {
let promiseDelete = new Promise((resolve, reject) => {
let logout = (uid) => {
- Assert.equal(uid, 'uid');
+ Assert.equal(uid, "uid");
client.tearDown();
resolve();
};
let client = new FxAccountsWebChannel({
content_uri: TEST_HTTP_PATH,
channel_id: TEST_CHANNEL_ID,
--- a/browser/base/content/test/general/browser_fxaccounts.js
+++ b/browser/base/content/test/general/browser_fxaccounts.js
@@ -12,17 +12,17 @@ const TEST_ROOT = "http://example.com/br
// instrument gFxAccounts to send observer notifications when it's done
// what it does.
(function() {
let unstubs = {}; // The original functions we stub out.
// The stub functions.
let stubs = {
updateAppMenuItem() {
- return unstubs['updateAppMenuItem'].call(gFxAccounts).then(() => {
+ return unstubs["updateAppMenuItem"].call(gFxAccounts).then(() => {
Services.obs.notifyObservers(null, "test:browser_fxaccounts:updateAppMenuItem", null);
});
},
// Opening preferences is trickier than it should be as leaks are reported
// due to the promises it fires off at load time and there's no clear way to
// know when they are done.
// So just ensure openPreferences is called rather than whether it opens.
openPreferences() {
--- a/browser/base/content/test/general/browser_mcb_redirect.js
+++ b/browser/base/content/test/general/browser_mcb_redirect.js
@@ -107,17 +107,17 @@ function test1() {
function checkUIForTest1() {
gTestBrowser.removeEventListener("load", checkUIForTest1, true);
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: true, passiveLoaded: false});
var expected = "script blocked";
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test2, "Error: Waited too long for status in Test 1!",
"OK: Expected result in innerHTML for Test1!");
}
// ------------------------ Test 2 ------------------------------
function test2() {
gTestBrowser.addEventListener("load", checkUIForTest2, true);
@@ -127,17 +127,17 @@ function test2() {
function checkUIForTest2() {
gTestBrowser.removeEventListener("load", checkUIForTest2, true);
assertMixedContentBlockingState(gTestBrowser, {activeLoaded: false, activeBlocked: false, passiveLoaded: false});
var expected = "script executed";
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test3, "Error: Waited too long for status in Test 2!",
"OK: Expected result in innerHTML for Test2!");
}
// ------------------------ Test 3 ------------------------------
// HTTPS page loading insecure image
function test3() {
gTestBrowser.addEventListener("load", checkLoadEventForTest3, true);
@@ -145,17 +145,17 @@ function test3() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest3() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest3, true);
var expected = "image blocked"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test4, "Error: Waited too long for status in Test 3!",
"OK: Expected result in innerHTML for Test3!");
}
// ------------------------ Test 4 ------------------------------
// HTTP page loading insecure image
function test4() {
gTestBrowser.addEventListener("load", checkLoadEventForTest4, true);
@@ -163,17 +163,17 @@ function test4() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest4() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest4, true);
var expected = "image loaded"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test5, "Error: Waited too long for status in Test 4!",
"OK: Expected result in innerHTML for Test4!");
}
// ------------------------ Test 5 ------------------------------
// HTTP page laoding insecure cached image
// Assuming test 4 succeeded, the image has already been loaded once
// and hence should be cached per the sjs cache-control header
@@ -186,17 +186,17 @@ function test5() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest5() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest5, true);
var expected = "image loaded"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test6, "Error: Waited too long for status in Test 5!",
"OK: Expected result in innerHTML for Test5!");
// Go back online
Services.io.offline = false;
}
// ------------------------ Test 6 ------------------------------
// HTTPS page loading insecure cached image
@@ -211,17 +211,17 @@ function test6() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest6() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest6, true);
var expected = "image blocked"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test7, "Error: Waited too long for status in Test 6!",
"OK: Expected result in innerHTML for Test6!");
// Go back online
Services.io.offline = false;
}
// ------------------------ Test 7 ------------------------------
// HTTP page loading insecure image that went through a double redirect
@@ -231,17 +231,17 @@ function test7() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest7() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest7, true);
var expected = "image loaded"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test8, "Error: Waited too long for status in Test 7!",
"OK: Expected result in innerHTML for Test7!");
}
// ------------------------ Test 8 ------------------------------
// HTTP page loading insecure cached image that went through a double redirect
// Assuming test 7 succeeded, the image has already been loaded once
// and hence should be cached per the sjs cache-control header
@@ -254,17 +254,17 @@ function test8() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest8() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest8, true);
var expected = "image loaded"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
test9, "Error: Waited too long for status in Test 8!",
"OK: Expected result in innerHTML for Test8!");
// Go back online
Services.io.offline = false;
}
// ------------------------ Test 9 ------------------------------
// HTTPS page loading insecure cached image that went through a double redirect
@@ -279,17 +279,17 @@ function test9() {
gTestBrowser.contentWindow.location = url;
}
function checkLoadEventForTest9() {
gTestBrowser.removeEventListener("load", checkLoadEventForTest9, true);
var expected = "image blocked"
waitForCondition(
- () => content.document.getElementById('mctestdiv').innerHTML == expected,
+ () => content.document.getElementById("mctestdiv").innerHTML == expected,
cleanUpAfterTests, "Error: Waited too long for status in Test 9!",
"OK: Expected result in innerHTML for Test9!");
// Go back online
Services.io.offline = false;
}
// ------------------------ SETUP ------------------------------
--- a/browser/base/content/test/general/browser_no_mcb_on_http_site.js
+++ b/browser/base/content/test/general/browser_no_mcb_on_http_site.js
@@ -64,17 +64,17 @@ function waitForCondition(condition, nex
// ------------- TEST 1 -----------------------------------------
function test1A() {
gTestBrowser.removeEventListener("load", test1A, true);
var expected = "Verifying MCB does not trigger warning/error for an http page ";
expected += "with https css that includes http image";
waitForCondition(
- () => content.document.getElementById('testDiv').innerHTML == expected,
+ () => content.document.getElementById("testDiv").innerHTML == expected,
test1B, "Error: Waited too long for status in Test 1!",
"OK: Expected result in innerHTML!");
}
function test1B() {
// set up test 2
gTestBrowser.addEventListener("load", test2A, true);
var url = gHttpTestRoot + "test_no_mcb_on_http_site_font.html";
@@ -84,17 +84,17 @@ function test1B() {
// ------------- TEST 2 -----------------------------------------
function test2A() {
gTestBrowser.removeEventListener("load", test2A, true);
var expected = "Verifying MCB does not trigger warning/error for an http page ";
expected += "with https css that includes http font";
waitForCondition(
- () => content.document.getElementById('testDiv').innerHTML == expected,
+ () => content.document.getElementById("testDiv").innerHTML == expected,
test2B, "Error: Waited too long for status in Test 2!",
"OK: Expected result in innerHTML!");
}
function test2B() {
// set up test 3
gTestBrowser.addEventListener("load", test3, true);
var url = gHttpTestRoot + "test_no_mcb_on_http_site_font2.html";
@@ -104,17 +104,17 @@ function test2B() {
// ------------- TEST 3 -----------------------------------------
function test3() {
gTestBrowser.removeEventListener("load", test3, true);
var expected = "Verifying MCB does not trigger warning/error for an http page "
expected += "with https css that imports another http css which includes http font";
waitForCondition(
- () => content.document.getElementById('testDiv').innerHTML == expected,
+ () => content.document.getElementById("testDiv").innerHTML == expected,
cleanUpAfterTests, "Error: Waited too long for status in Test 3!",
"OK: Expected result in innerHTML!");
}
// ------------------------------------------------------
function test() {
// Performing async calls, e.g. 'onload', we have to wait till all of them finished
--- a/browser/base/content/test/general/browser_offlineQuotaNotification.js
+++ b/browser/base/content/test/general/browser_offlineQuotaNotification.js
@@ -57,17 +57,17 @@ function test() {
content.window.applicationCache.oncached = function() {
setTimeout(resolve, 0);
};
sendAsyncMessage("Test:OnCachedAttached");
});
});
gotCached.then(function() {
// We got cached - now we should have provoked the quota warning.
- let notification = PopupNotifications.getNotification('offline-app-usage');
+ let notification = PopupNotifications.getNotification("offline-app-usage");
ok(notification, "have offline-app-usage notification");
// select the default action - this should cause the preferences
// tab to open - which we track via an "Initialized" event.
PopupNotifications.panel.firstElementChild.button.click();
let newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
newTabBrowser.addEventListener("Initialized", function PrefInit() {
newTabBrowser.removeEventListener("Initialized", PrefInit, true);
executeSoon(function() {
--- a/browser/base/content/test/general/browser_page_style_menu_update.js
+++ b/browser/base/content/test/general/browser_page_style_menu_update.js
@@ -49,17 +49,17 @@ add_task(function*() {
target.click();
// Now we need to wait for the content process to send its stylesheet
// update for the selected tab to the parent. Because messages are
// guaranteed to be sent in order, we'll make sure we do the check
// after the parent has been updated by yielding until the child
// has finished running a ContentTask for us.
yield ContentTask.spawn(browser, {}, function*() {
- dump('\nJust wasting some time.\n');
+ dump("\nJust wasting some time.\n");
});
gPageStyleMenu.fillPopup(menupopup);
// gPageStyleMenu empties out the menu between opens, so we need
// to get a new reference to the selected menuitem
selected = menupopup.querySelector("menuitem[checked='true']");
is(selected.getAttribute("label"), "1", "Should now have stylesheet 1 selected");
--- a/browser/base/content/test/general/browser_parsable_css.js
+++ b/browser/base/content/test/general/browser_parsable_css.js
@@ -134,17 +134,17 @@ function getBaseUriForChromeUri(chromeUr
let chromeFile = chromeUri + "gobbledygooknonexistentfile.reallynothere";
let uri = Services.io.newURI(chromeFile);
let fileUri = gChromeReg.convertChromeURL(uri);
return fileUri.resolve(".");
}
function parseManifest(manifestUri) {
return fetchFile(manifestUri.spec).then(data => {
- for (let line of data.split('\n')) {
+ for (let line of data.split("\n")) {
let [type, ...argv] = line.split(/\s+/);
let component;
if (type == "content" || type == "skin") {
[component] = argv;
} else {
// skip unrelated lines
continue;
}
@@ -256,17 +256,17 @@ add_task(function* checkAllTheCSS() {
let uris = yield generateURIsFromDirTree(appDir, [".css", ".manifest"]);
// Create a clean iframe to load all the files into. This needs to live at a
// chrome URI so that it's allowed to load and parse any styles.
let testFile = getRootDirectory(gTestPath) + "dummy_page.html";
let windowless = Services.appShell.createWindowlessBrowser();
let iframe = windowless.document.createElementNS("http://www.w3.org/1999/xhtml", "html:iframe");
windowless.document.documentElement.appendChild(iframe);
- let iframeLoaded = once(iframe, 'load');
+ let iframeLoaded = once(iframe, "load");
iframe.contentWindow.location = testFile;
yield iframeLoaded;
let doc = iframe.contentWindow.document;
// Parse and remove all manifests from the list.
// NOTE that this must be done before filtering out devtools paths
// so that all chrome paths can be recorded.
let manifestPromises = [];
@@ -359,15 +359,15 @@ add_task(function* checkAllTheCSS() {
ok(false, "Unused file whitelist item. " +
" file: " + item.file +
" from: " + item.from);
}
}
// Clean up to avoid leaks:
iframe.remove();
- doc.head.innerHTML = '';
+ doc.head.innerHTML = "";
doc = null;
iframe = null;
windowless.close();
windowless = null;
imageURIsToReferencesMap = null;
});
--- a/browser/base/content/test/general/browser_remoteTroubleshoot.js
+++ b/browser/base/content/test/general/browser_remoteTroubleshoot.js
@@ -59,17 +59,17 @@ add_task(function*() {
Assert.equal(got.message.application.buildID, Services.appinfo.appBuildID,
"should have correct build ID");
let updateChannel = null;
try {
updateChannel = Cu.import("resource://gre/modules/UpdateUtils.jsm", {}).UpdateUtils.UpdateChannel;
} catch (ex) {}
if (!updateChannel) {
- Assert.ok(!('updateChannel' in got.message.application),
+ Assert.ok(!("updateChannel" in got.message.application),
"should not have update channel where not available.");
} else {
Assert.equal(got.message.application.updateChannel, updateChannel,
"should have correct update channel.");
}
// And check some keys we know we decline to return.
--- a/browser/base/content/test/general/browser_restore_isAppTab.js
+++ b/browser/base/content/test/general/browser_restore_isAppTab.js
@@ -1,56 +1,56 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
const {TabStateFlusher} = Cu.import("resource:///modules/sessionstore/TabStateFlusher.jsm", {});
const DUMMY = "http://example.com/browser/browser/base/content/test/general/dummy_page.html";
function getMinidumpDirectory() {
- let dir = Services.dirsvc.get('ProfD', Ci.nsIFile);
+ let dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
dir.append("minidumps");
return dir;
}
// This observer is needed so we can clean up all evidence of the crash so
// the testrunner thinks things are peachy.
var CrashObserver = {
observe(subject, topic, data) {
- is(topic, 'ipc:content-shutdown', 'Received correct observer topic.');
+ is(topic, "ipc:content-shutdown", "Received correct observer topic.");
ok(subject instanceof Ci.nsIPropertyBag2,
- 'Subject implements nsIPropertyBag2.');
+ "Subject implements nsIPropertyBag2.");
// we might see this called as the process terminates due to previous tests.
// We are only looking for "abnormal" exits...
if (!subject.hasKey("abnormal")) {
info("This is a normal termination and isn't the one we are looking for...");
return;
}
let dumpID;
- if ('nsICrashReporter' in Ci) {
- dumpID = subject.getPropertyAsAString('dumpID');
+ if ("nsICrashReporter" in Ci) {
+ dumpID = subject.getPropertyAsAString("dumpID");
ok(dumpID, "dumpID is present and not an empty string");
}
if (dumpID) {
let minidumpDirectory = getMinidumpDirectory();
let file = minidumpDirectory.clone();
- file.append(dumpID + '.dmp');
+ file.append(dumpID + ".dmp");
file.remove(true);
file = minidumpDirectory.clone();
- file.append(dumpID + '.extra');
+ file.append(dumpID + ".extra");
file.remove(true);
}
}
}
-Services.obs.addObserver(CrashObserver, 'ipc:content-shutdown', false);
+Services.obs.addObserver(CrashObserver, "ipc:content-shutdown", false);
registerCleanupFunction(() => {
- Services.obs.removeObserver(CrashObserver, 'ipc:content-shutdown');
+ Services.obs.removeObserver(CrashObserver, "ipc:content-shutdown");
});
function frameScript() {
addMessageListener("Test:GetIsAppTab", function() {
sendAsyncMessage("Test:IsAppTab", { isAppTab: docShell.isAppTab });
});
addMessageListener("Test:Crash", function() {
--- a/browser/base/content/test/general/browser_save_link_when_window_navigates.js
+++ b/browser/base/content/test/general/browser_save_link_when_window_navigates.js
@@ -57,17 +57,17 @@ function triggerSave(aWindow, aCallback)
ok(!destDir.exists(), "Destination dir should be removed");
ok(!destFile.exists(), "Destination file should be removed");
mockTransferCallback = null;
info("done mockTransferCallback");
}
function onUCTDialog(dialog) {
function doLoad() {
- content.document.querySelector('iframe').remove();
+ content.document.querySelector("iframe").remove();
}
testBrowser.messageManager.loadFrameScript("data:,(" + doLoad.toString() + ")()", false);
executeSoon(continueDownloading);
}
function continueDownloading() {
let windows = Services.wm.getEnumerator("");
while (windows.hasMoreElements()) {
--- a/browser/base/content/test/general/browser_syncui.js
+++ b/browser/base/content/test/general/browser_syncui.js
@@ -177,24 +177,24 @@ add_task(function* testButtonActivitiesI
// check the button's functionality while the button is in the NavBar - which
// it already is.
yield doTestButtonActivities();
});
add_task(function* testFormatLastSyncDateNow() {
let now = new Date();
let nowString = gSyncUI.formatLastSyncDate(now);
- Assert.equal(nowString, "Last sync: " + now.toLocaleDateString(undefined, {weekday: 'long', hour: 'numeric', minute: 'numeric'}));
+ Assert.equal(nowString, "Last sync: " + now.toLocaleDateString(undefined, {weekday: "long", hour: "numeric", minute: "numeric"}));
});
add_task(function* testFormatLastSyncDateMonthAgo() {
let monthAgo = new Date();
monthAgo.setMonth(monthAgo.getMonth() - 1);
let monthAgoString = gSyncUI.formatLastSyncDate(monthAgo);
- Assert.equal(monthAgoString, "Last sync: " + monthAgo.toLocaleDateString(undefined, {month: 'long', day: 'numeric'}));
+ Assert.equal(monthAgoString, "Last sync: " + monthAgo.toLocaleDateString(undefined, {month: "long", day: "numeric"}));
});
add_task(function* testButtonActivitiesInPanel() {
// check the button's functionality while the button is in the panel - it's
// currently in the NavBar - move it to the panel and open it.
CustomizableUI.addWidgetToArea("sync-button", CustomizableUI.AREA_PANEL);
yield PanelUI.show();
try {
--- a/browser/base/content/test/general/browser_tabfocus.js
+++ b/browser/base/content/test/general/browser_tabfocus.js
@@ -325,17 +325,17 @@ add_task(function*() {
// now go back again
gURLBar.focus();
yield new Promise((resolve, reject) => {
window.addEventListener("pageshow", function navigationOccured(event) {
window.removeEventListener("pageshow", navigationOccured, true);
resolve();
}, true);
- document.getElementById('Browser:Back').doCommand();
+ document.getElementById("Browser:Back").doCommand();
});
is(window.document.activeElement, gURLBar.inputField, "urlbar still focused after navigating back");
// Document navigation with F6 does not yet work in mutli-process browsers.
if (!gMultiProcessBrowser) {
gURLBar.focus();
actualEvents = new EventStore();
--- a/browser/base/content/test/general/browser_trackingUI_6.js
+++ b/browser/base/content/test/general/browser_trackingUI_6.js
@@ -13,17 +13,17 @@ function waitForSecurityChange(numChange
}
}
};
gBrowser.addProgressListener(listener);
});
}
add_task(function* test_fetch() {
- yield SpecialPowers.pushPrefEnv({ set: [['privacy.trackingprotection.enabled', true]] });
+ yield SpecialPowers.pushPrefEnv({ set: [["privacy.trackingprotection.enabled", true]] });
yield BrowserTestUtils.withNewTab({ gBrowser, url: URL }, function* (newTabBrowser) {
let securityChange = waitForSecurityChange();
yield ContentTask.spawn(newTabBrowser, null, function* () {
yield content.wrappedJSObject.test_fetch()
.then(response => Assert.ok(false, "should have denied the request"))
.catch(e => Assert.ok(true, `Caught exception: ${e}`));
});
--- a/browser/base/content/test/general/content_aboutAccounts.js
+++ b/browser/base/content/test/general/content_aboutAccounts.js
@@ -47,19 +47,19 @@ addEventListener("DOMContentLoaded", fun
// Return the visibility state of a list of ids.
addMessageListener("test:check-visibilities", function(message) {
let result = {};
for (let id of message.data.ids) {
let elt = content.document.getElementById(id);
if (elt) {
let displayStyle = content.window.getComputedStyle(elt).display;
- if (displayStyle == 'none') {
+ if (displayStyle == "none") {
result[id] = false;
- } else if (displayStyle == 'block') {
+ } else if (displayStyle == "block") {
result[id] = true;
} else {
result[id] = "strange: " + displayStyle; // tests should fail!
}
} else {
result[id] = "doesn't exist: " + id;
}
}
--- a/browser/base/content/test/general/file_bug822367_1.js
+++ b/browser/base/content/test/general/file_bug822367_1.js
@@ -1,1 +1,1 @@
-document.getElementById('p1').innerHTML = "hello";
+document.getElementById("p1").innerHTML = "hello";
--- a/browser/base/content/test/general/head.js
+++ b/browser/base/content/test/general/head.js
@@ -99,17 +99,17 @@ function closeToolbarCustomizationUI(aCa
aBrowserWin.gNavToolbox.removeEventListener("aftercustomization", unloaded);
executeSoon(aCallback);
});
aBrowserWin.gCustomizeMode.exit();
}
function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
- retryTimes = typeof retryTimes !== 'undefined' ? retryTimes : 30;
+ retryTimes = typeof retryTimes !== "undefined" ? retryTimes : 30;
var tries = 0;
var interval = setInterval(function() {
if (tries >= retryTimes) {
ok(false, errorMsg);
moveOn();
}
var conditionPassed;
try {
--- a/browser/base/content/test/plugins/blocklist_proxy.js
+++ b/browser/base/content/test/plugins/blocklist_proxy.js
@@ -2,17 +2,17 @@ var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
var Cm = Components.manager;
const kBlocklistServiceUUID = "{66354bc9-7ed1-4692-ae1d-8da97d6b205e}";
const kBlocklistServiceContractID = "@mozilla.org/extensions/blocklist;1";
const kBlocklistServiceFactory = Cm.getClassObject(Cc[kBlocklistServiceContractID], Ci.nsIFactory);
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
/*
* A lightweight blocklist proxy for the testing purposes.
*/
var BlocklistProxy = {
_uuid: null,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
--- a/browser/base/content/test/plugins/browser_CTP_outsideScrollArea.js
+++ b/browser/base/content/test/plugins/browser_CTP_outsideScrollArea.js
@@ -33,24 +33,24 @@ add_task(function* () {
// Test that the click-to-play overlay is not hidden for elements
// partially or fully outside the viewport.
add_task(function* () {
yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_outsideScrollArea.html");
yield ContentTask.spawn(gTestBrowser, {}, function* () {
let doc = content.document;
- let p = doc.createElement('embed');
+ let p = doc.createElement("embed");
- p.setAttribute('id', 'test');
- p.setAttribute('type', 'application/x-test');
+ p.setAttribute("id", "test");
+ p.setAttribute("type", "application/x-test");
p.style.left = "0";
p.style.bottom = "200px";
- doc.getElementById('container').appendChild(p);
+ doc.getElementById("container").appendChild(p);
});
// Work around for delayed PluginBindingAttached
yield promiseUpdatePluginBindings(gTestBrowser);
yield promisePopupNotification("click-to-play-plugins");
yield ContentTask.spawn(gTestBrowser, {}, function* () {
@@ -62,24 +62,24 @@ add_task(function* () {
});
});
add_task(function* () {
yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_outsideScrollArea.html");
yield ContentTask.spawn(gTestBrowser, {}, function* () {
let doc = content.document;
- let p = doc.createElement('embed');
+ let p = doc.createElement("embed");
- p.setAttribute('id', 'test');
- p.setAttribute('type', 'application/x-test');
+ p.setAttribute("id", "test");
+ p.setAttribute("type", "application/x-test");
p.style.left = "0";
p.style.bottom = "-410px";
- doc.getElementById('container').appendChild(p);
+ doc.getElementById("container").appendChild(p);
});
// Work around for delayed PluginBindingAttached
yield promiseUpdatePluginBindings(gTestBrowser);
yield promisePopupNotification("click-to-play-plugins");
yield ContentTask.spawn(gTestBrowser, null, function* () {
@@ -91,24 +91,24 @@ add_task(function* () {
});
});
add_task(function* () {
yield promiseTabLoadEvent(gBrowser.selectedTab, gTestRoot + "plugin_outsideScrollArea.html");
yield ContentTask.spawn(gTestBrowser, {}, function* () {
let doc = content.document;
- let p = doc.createElement('embed');
+ let p = doc.createElement("embed");
- p.setAttribute('id', 'test');
- p.setAttribute('type', 'application/x-test');
+ p.setAttribute("id", "test");
+ p.setAttribute("type", "application/x-test");
p.style.left = "-600px";
p.style.bottom = "0";
- doc.getElementById('container').appendChild(p);
+ doc.getElementById("container").appendChild(p);
});
// Work around for delayed PluginBindingAttached
yield promiseUpdatePluginBindings(gTestBrowser);
yield promisePopupNotification("click-to-play-plugins");
yield ContentTask.spawn(gTestBrowser, null, function* () {
let plugin = content.document.getElementById("test");
--- a/browser/base/content/test/plugins/browser_bug787619.js
+++ b/browser/base/content/test/plugins/browser_bug787619.js
@@ -56,10 +56,10 @@ add_task(function* () {
PopupNotifications.panel.firstChild;
yield promiseForCondition(condition);
PopupNotifications.panel.firstChild._primaryButton.click();
// check plugin state
pluginInfo = yield promiseForPluginInfo("plugin");
ok(pluginInfo.activated, "plugin should be activated");
- is(gWrapperClickCount, 0, 'wrapper should not have received any clicks');
+ is(gWrapperClickCount, 0, "wrapper should not have received any clicks");
});
--- a/browser/base/content/test/plugins/head.js
+++ b/browser/base/content/test/plugins/head.js
@@ -219,17 +219,17 @@ function promiseReloadPlugin(aId, aBrows
}
// after a test is done using the plugin doorhanger, we should just clear
// any permissions that may have crept in
function clearAllPluginPermissions() {
let perms = Services.perms.enumerator;
while (perms.hasMoreElements()) {
let perm = perms.getNext();
- if (perm.type.startsWith('plugin')) {
+ if (perm.type.startsWith("plugin")) {
info("removing permission:" + perm.principal.origin + " " + perm.type + "\n");
Services.perms.removePermission(perm);
}
}
}
function updateBlocklist(aCallback) {
let blocklistNotifier = Cc["@mozilla.org/extensions/blocklist;1"]
@@ -383,17 +383,17 @@ function promiseForNotificationShown(not
* there is some sort of plugin in the page.
* @param browser
* The browser to force plugin bindings in.
* @return Promise
*/
function promiseUpdatePluginBindings(browser) {
return ContentTask.spawn(browser, {}, function* () {
let doc = content.document;
- let elems = doc.getElementsByTagName('embed');
+ let elems = doc.getElementsByTagName("embed");
if (!elems || elems.length < 1) {
- elems = doc.getElementsByTagName('object');
+ elems = doc.getElementsByTagName("object");
}
if (elems && elems.length > 0) {
elems[0].clientTop;
}
});
}
--- a/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js
+++ b/browser/base/content/test/popupNotifications/browser_popupNotification_checkbox.js
@@ -159,17 +159,17 @@ var tests = [
}
},
];
// Test checkbox disabling the main action in different combinations
["checkedState", "uncheckedState"].forEach(function(state) {
[true, false].forEach(function(checked) {
tests.push(
- { id: `checkbox_disableMainAction_${state}_${checked ? 'checked' : 'unchecked'}`,
+ { id: `checkbox_disableMainAction_${state}_${checked ? "checked" : "unchecked"}`,
run() {
this.notifyObj = new BasicNotification(this.id);
this.notifyObj.options.checkbox = {
label: "This is a checkbox",
checked,
[state]: {
disableMainAction: true,
warningLabel: "Testing disable",
--- a/browser/base/content/test/referrer/head.js
+++ b/browser/base/content/test/referrer/head.js
@@ -8,17 +8,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://testing-common/ContentTask.jsm");
const REFERRER_URL_BASE = "/browser/browser/base/content/test/referrer/";
const REFERRER_POLICYSERVER_URL =
"test1.example.com" + REFERRER_URL_BASE + "file_referrer_policyserver.sjs";
const REFERRER_POLICYSERVER_URL_ATTRIBUTE =
"test1.example.com" + REFERRER_URL_BASE + "file_referrer_policyserver_attr.sjs";
-SpecialPowers.pushPrefEnv({"set": [['network.http.enablePerElementReferrer', true]]});
+SpecialPowers.pushPrefEnv({"set": [["network.http.enablePerElementReferrer", true]]});
var gTestWindow = null;
var rounds = 0;
// We test that the UI code propagates three pieces of state - the referrer URI
// itself, the referrer policy, and the triggering principal. After that, we
// trust nsIWebNavigation to do the right thing with the info it's given, which
// is covered more exhaustively by dom/base/test/test_bug704320.html (which is
--- a/browser/base/content/test/social/browser_aboutHome_activation.js
+++ b/browser/base/content/test/social/browser_aboutHome_activation.js
@@ -5,58 +5,58 @@
var SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AboutHomeUtils",
"resource:///modules/AboutHome.jsm");
var snippet =
-' <script>' +
-' var manifest = {' +
+" <script>" +
+" var manifest = {" +
' "name": "Demo Social Service",' +
' "origin": "https://example.com",' +
' "iconURL": "chrome://branding/content/icon16.png",' +
' "icon32URL": "chrome://branding/content/icon32.png",' +
' "icon64URL": "chrome://branding/content/icon64.png",' +
' "shareURL": "https://example.com/browser/browser/base/content/test/social/social_share.html",' +
' "postActivationURL": "https://example.com/browser/browser/base/content/test/social/social_postActivation.html",' +
-' };' +
-' function activateProvider(node) {' +
+" };" +
+" function activateProvider(node) {" +
' node.setAttribute("data-service", JSON.stringify(manifest));' +
' var event = new CustomEvent("ActivateSocialFeature");' +
-' node.dispatchEvent(event);' +
-' }' +
-' </script>' +
+" node.dispatchEvent(event);" +
+" }" +
+" </script>" +
' <div id="activationSnippet" onclick="activateProvider(this)">' +
' <img src="chrome://branding/content/icon32.png"></img>' +
-' </div>';
+" </div>";
// enable one-click activation
var snippet2 =
-' <script>' +
-' var manifest = {' +
+" <script>" +
+" var manifest = {" +
' "name": "Demo Social Service",' +
' "origin": "https://example.com",' +
' "iconURL": "chrome://branding/content/icon16.png",' +
' "icon32URL": "chrome://branding/content/icon32.png",' +
' "icon64URL": "chrome://branding/content/icon64.png",' +
' "shareURL": "https://example.com/browser/browser/base/content/test/social/social_share.html",' +
' "postActivationURL": "https://example.com/browser/browser/base/content/test/social/social_postActivation.html",' +
' "oneclick": true' +
-' };' +
-' function activateProvider(node) {' +
+" };" +
+" function activateProvider(node) {" +
' node.setAttribute("data-service", JSON.stringify(manifest));' +
' var event = new CustomEvent("ActivateSocialFeature");' +
-' node.dispatchEvent(event);' +
-' }' +
-' </script>' +
+" node.dispatchEvent(event);" +
+" }" +
+" </script>" +
' <div id="activationSnippet" onclick="activateProvider(this)">' +
' <img src="chrome://branding/content/icon32.png"></img>' +
-' </div>';
+" </div>";
var gTests = [
{
desc: "Test activation with enable panel",
snippet,
panel: true
},
--- a/browser/base/content/test/social/browser_share.js
+++ b/browser/base/content/test/social/browser_share.js
@@ -32,17 +32,17 @@ function test() {
/* bug 1042991, ensure history is available by calling history.back on close */
addMessageListener("closeself", function(e) {
content.history.back();
content.close();
}, true);
/* if text is entered into field, onbeforeunload will cause a modal dialog
unless dialogs have been disabled for the iframe. */
content.onbeforeunload = function(e) {
- return 'FAIL.';
+ return "FAIL.";
};
}.toString() + ")();";
let mm = getGroupMessageManager("social");
mm.loadFrameScript(frameScript, true);
// Animation on the panel can cause intermittent failures such as bug 1115131.
SocialShare.panel.setAttribute("animate", "false");
registerCleanupFunction(function() {
--- a/browser/base/content/test/social/browser_social_activation.js
+++ b/browser/base/content/test/social/browser_social_activation.js
@@ -236,17 +236,17 @@ var tests = {
});
});
},
testAddonManagerDoubleInstall(next) {
// Create a new tab and load about:addons
let addonsTab = gBrowser.addTab();
gBrowser.selectedTab = addonsTab;
- BrowserOpenAddonsMgr('addons://list/service');
+ BrowserOpenAddonsMgr("addons://list/service");
gBrowser.selectedBrowser.addEventListener("load", function tabLoad() {
gBrowser.selectedBrowser.removeEventListener("load", tabLoad, true);
is(addonsTab.linkedBrowser.currentURI.spec, "about:addons", "about:addons should load into blank tab.");
activateOneProvider(gProviders[0], true, function() {
info("first activation completed");
is(gBrowser.contentDocument.location.href, gProviders[0].origin + "/browser/browser/base/content/test/social/social_postActivation.html", "postActivationURL loaded");
BrowserTestUtils.removeTab(gBrowser.selectedTab).then(() => {
--- a/browser/base/content/test/social/head.js
+++ b/browser/base/content/test/social/head.js
@@ -59,17 +59,17 @@ function runSocialTestWithProvider(manif
let SocialService = Cu.import("resource:///modules/SocialService.jsm", {}).SocialService;
let manifests = Array.isArray(manifest) ? manifest : [manifest];
// Check that none of the provider's content ends up in history.
function* finishCleanUp() {
for (let i = 0; i < manifests.length; i++) {
let m = manifests[i];
- for (let what of ['iconURL', 'shareURL']) {
+ for (let what of ["iconURL", "shareURL"]) {
if (m[what]) {
yield promiseSocialUrlNotRemembered(m[what]);
}
}
}
for (let i = 0; i < gURLsNotRemembered.length; i++) {
yield promiseSocialUrlNotRemembered(gURLsNotRemembered[i]);
}
@@ -207,17 +207,17 @@ function setManifestPref(name, manifest)
createInstance(Ci.nsISupportsString);
string.data = JSON.stringify(manifest);
Services.prefs.setComplexValue(name, Ci.nsISupportsString, string);
}
function getManifestPrefname(aManifest) {
// is same as the generated name in SocialServiceInternal.getManifestPrefname
let originUri = Services.io.newURI(aManifest.origin);
- return "social.manifest." + originUri.hostPort.replace('.', '-');
+ return "social.manifest." + originUri.hostPort.replace(".", "-");
}
function ensureFrameLoaded(frame, uri) {
return new Promise(resolve => {
if (frame.contentDocument && frame.contentDocument.readyState == "complete" &&
(!uri || frame.contentDocument.location.href == uri)) {
resolve();
} else {
@@ -228,39 +228,39 @@ function ensureFrameLoaded(frame, uri) {
resolve()
}, true);
}
});
}
// Support for going on and offline.
// (via browser/base/content/test/browser_bookmark_titles.js)
-var origProxyType = Services.prefs.getIntPref('network.proxy.type');
+var origProxyType = Services.prefs.getIntPref("network.proxy.type");
function toggleOfflineStatus(goOfflineState) {
// Bug 968887 fix. when going on/offline, wait for notification before continuing
return new Promise(resolve => {
if (!goOfflineState) {
- Services.prefs.setIntPref('network.proxy.type', origProxyType);
+ Services.prefs.setIntPref("network.proxy.type", origProxyType);
}
if (goOfflineState != Services.io.offline) {
info("initial offline state " + Services.io.offline);
let expect = !Services.io.offline;
Services.obs.addObserver(function offlineChange(subject, topic, data) {
Services.obs.removeObserver(offlineChange, "network:offline-status-changed");
info("offline state changed to " + Services.io.offline);
is(expect, Services.io.offline, "network:offline-status-changed successful toggle");
resolve();
}, "network:offline-status-changed", false);
BrowserOffline.toggleOfflineStatus();
} else {
resolve();
}
if (goOfflineState) {
- Services.prefs.setIntPref('network.proxy.type', 0);
+ Services.prefs.setIntPref("network.proxy.type", 0);
// LOAD_FLAGS_BYPASS_CACHE isn't good enough. So clear the cache.
Services.cache2.clear();
}
});
}
function goOffline() {
// Simulate a network outage with offline mode. (Localhost is still
--- a/browser/base/content/test/urlbar/browser_bug304198.js
+++ b/browser/base/content/test/urlbar/browser_bug304198.js
@@ -25,61 +25,61 @@ add_task(function* () {
function cleanUp() {
gBrowser.removeTab(fullURLTab);
gBrowser.removeTab(partialURLTab);
gBrowser.removeTab(deletedURLTab);
}
function* cycleTabs() {
yield BrowserTestUtils.switchTab(gBrowser, fullURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after switching back to fullURLTab');
+ is(gURLBar.textValue, testURL, "gURLBar.textValue should be testURL after switching back to fullURLTab");
yield BrowserTestUtils.switchTab(gBrowser, partialURLTab);
- is(gURLBar.textValue, testPartialURL, 'gURLBar.textValue should be testPartialURL after switching back to partialURLTab');
+ is(gURLBar.textValue, testPartialURL, "gURLBar.textValue should be testPartialURL after switching back to partialURLTab");
yield BrowserTestUtils.switchTab(gBrowser, deletedURLTab);
- is(gURLBar.textValue, '', 'gURLBar.textValue should be "" after switching back to deletedURLTab');
+ is(gURLBar.textValue, "", 'gURLBar.textValue should be "" after switching back to deletedURLTab');
yield BrowserTestUtils.switchTab(gBrowser, fullURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after switching back to fullURLTab');
+ is(gURLBar.textValue, testURL, "gURLBar.textValue should be testURL after switching back to fullURLTab");
}
function urlbarBackspace() {
return new Promise((resolve, reject) => {
gBrowser.selectedBrowser.focus();
gURLBar.addEventListener("input", function() {
gURLBar.removeEventListener("input", arguments.callee);
resolve();
});
gURLBar.focus();
EventUtils.synthesizeKey("VK_BACK_SPACE", {});
});
}
function* prepareDeletedURLTab() {
yield BrowserTestUtils.switchTab(gBrowser, deletedURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after initial switch to deletedURLTab');
+ is(gURLBar.textValue, testURL, "gURLBar.textValue should be testURL after initial switch to deletedURLTab");
// simulate the user removing the whole url from the location bar
gPrefService.setBoolPref("browser.urlbar.clickSelectsAll", true);
yield urlbarBackspace();
is(gURLBar.textValue, "", 'gURLBar.textValue should be "" (just set)');
if (gPrefService.prefHasUserValue("browser.urlbar.clickSelectsAll")) {
gPrefService.clearUserPref("browser.urlbar.clickSelectsAll");
}
}
function* prepareFullURLTab() {
yield BrowserTestUtils.switchTab(gBrowser, fullURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after initial switch to fullURLTab');
+ is(gURLBar.textValue, testURL, "gURLBar.textValue should be testURL after initial switch to fullURLTab");
}
function* preparePartialURLTab() {
yield BrowserTestUtils.switchTab(gBrowser, partialURLTab);
- is(gURLBar.textValue, testURL, 'gURLBar.textValue should be testURL after initial switch to partialURLTab');
+ is(gURLBar.textValue, testURL, "gURLBar.textValue should be testURL after initial switch to partialURLTab");
// simulate the user removing part of the url from the location bar
gPrefService.setBoolPref("browser.urlbar.clickSelectsAll", false);
let deleted = 0;
while (deleted < charsToDelete) {
yield urlbarBackspace(arguments.callee);
deleted++;
--- a/browser/base/content/test/urlbar/browser_removeUnsafeProtocolsFromURLBarPaste.js
+++ b/browser/base/content/test/urlbar/browser_removeUnsafeProtocolsFromURLBarPaste.js
@@ -29,17 +29,17 @@ function paste(input, cb) {
cb();
}, function() {
ok(false, "Failed to copy string '" + input + "' to clipboard");
cb();
});
}
function testNext() {
- gURLBar.value = '';
+ gURLBar.value = "";
if (!pairs.length) {
finish();
return;
}
let [inputValue, expectedURL] = pairs.shift();
gURLBar.focus();
--- a/browser/base/content/test/urlbar/browser_urlbarDecode.js
+++ b/browser/base/content/test/urlbar/browser_urlbarDecode.js
@@ -3,20 +3,20 @@
// This test makes sure (1) you can't break the urlbar by typing particular JSON
// or JS fragments into it, (2) urlbar.textValue shows URLs unescaped, and (3)
// the urlbar also shows the URLs embedded in action URIs unescaped. See bug
// 1233672.
add_task(function* injectJSON() {
let inputStrs = [
'http://example.com/ ", "url": "bar',
- 'http://example.com/\\',
+ "http://example.com/\\",
'http://example.com/"',
'http://example.com/","url":"evil.com',
- 'http://mozilla.org/\\u0020',
+ "http://mozilla.org/\\u0020",
'http://www.mozilla.org/","url":1e6,"some-key":"foo',
'http://www.mozilla.org/","url":null,"some-key":"foo',
'http://www.mozilla.org/","url":["foo","bar"],"some-key":"foo',
];
for (let inputStr of inputStrs) {
yield checkInput(inputStr);
}
gURLBar.value = "";
--- a/browser/base/content/test/urlbar/browser_urlbar_blanking.js
+++ b/browser/base/content/test/urlbar/browser_urlbar_blanking.js
@@ -13,17 +13,17 @@ add_task(function*() {
});
add_task(function*() {
const URI = "http://www.example.com/browser/browser/base/content/test/urlbar/file_blank_but_not_blank.html";
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URI);
is(gURLBar.value, URI, "The URL bar should match the URI");
let browserLoaded = BrowserTestUtils.browserLoaded(tab.linkedBrowser);
ContentTask.spawn(tab.linkedBrowser, null, function() {
- content.document.querySelector('a').click();
+ content.document.querySelector("a").click();
});
yield browserLoaded;
ok(gURLBar.value.startsWith("javascript"), "The URL bar should have the JS URI");
// When reloading, the javascript: uri we're using will throw an exception.
// That's deliberate, so we need to tell mochitest to ignore it:
SimpleTest.expectUncaughtException(true);
yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
// This is sync, so by the time we return we should have changed the URL bar.
--- a/browser/base/content/test/webrtc/head.js
+++ b/browser/base/content/test/webrtc/head.js
@@ -3,17 +3,17 @@ Components.utils.import("resource:///mod
XPCOMUtils.defineLazyModuleGetter(this, "Promise",
"resource://gre/modules/Promise.jsm");
const PREF_PERMISSION_FAKE = "media.navigator.permission.fake";
const CONTENT_SCRIPT_HELPER = getRootDirectory(gTestPath) + "get_user_media_content_script.js";
function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
- retryTimes = typeof retryTimes !== 'undefined' ? retryTimes : 30;
+ retryTimes = typeof retryTimes !== "undefined" ? retryTimes : 30;
var tries = 0;
var interval = setInterval(function() {
if (tries >= retryTimes) {
ok(false, errorMsg);
moveOn();
}
var conditionPassed;
try {
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -200,17 +200,17 @@ function openLinkIn(url, where, params)
const Cc = Components.classes;
const Ci = Components.interfaces;
var aFromChrome = params.fromChrome;
var aAllowThirdPartyFixup = params.allowThirdPartyFixup;
var aPostData = params.postData;
var aCharset = params.charset;
var aReferrerURI = params.referrerURI;
- var aReferrerPolicy = ('referrerPolicy' in params ?
+ var aReferrerPolicy = ("referrerPolicy" in params ?
params.referrerPolicy : Ci.nsIHttpChannel.REFERRER_POLICY_UNSET);
var aRelatedToCurrent = params.relatedToCurrent;
var aAllowMixedContent = params.allowMixedContent;
var aInBackground = params.inBackground;
var aDisallowInheritPrincipal = params.disallowInheritPrincipal;
var aInitiatingDoc = params.initiatingDoc;
var aIsPrivate = params.private;
var aSkipTabAnimation = params.skipTabAnimation;
--- a/browser/base/content/web-panels.js
+++ b/browser/base/content/web-panels.js
@@ -22,20 +22,20 @@ var panelProgressListener = {
return;
// ignore local/resource:/chrome: files
if (aStatus == NS_NET_STATUS_READ_FROM || aStatus == NS_NET_STATUS_WROTE_TO)
return;
if (aStateFlags & Ci.nsIWebProgressListener.STATE_START &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
- window.parent.document.getElementById('sidebar-throbber').setAttribute("loading", "true");
+ window.parent.document.getElementById("sidebar-throbber").setAttribute("loading", "true");
} else if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK) {
- window.parent.document.getElementById('sidebar-throbber').removeAttribute("loading");
+ window.parent.document.getElementById("sidebar-throbber").removeAttribute("loading");
}
}
,
onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {
UpdateBackForwardCommands(getPanelBrowser().webNavigation);
},
--- a/browser/components/contextualidentity/test/browser/browser_blobUrl.js
+++ b/browser/components/contextualidentity/test/browser/browser_blobUrl.js
@@ -9,33 +9,33 @@ add_task(function* setup() {
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true]
]});
});
add_task(function* test() {
info("Creating a tab with UCI = 1...");
let tab1 = gBrowser.addTab(BASE_URI, {userContextId: 1});
- is(tab1.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
+ is(tab1.getAttribute("usercontextid"), 1, "New tab has UCI equal 1");
let browser1 = gBrowser.getBrowserForTab(tab1);
yield BrowserTestUtils.browserLoaded(browser1);
let blobURL;
info("Creating a blob URL...");
yield ContentTask.spawn(browser1, null, function() {
return Promise.resolve(content.window.URL.createObjectURL(new content.window.Blob([123])));
}).then(newURL => { blobURL = newURL });
info("Blob URL: " + blobURL);
info("Creating a tab with UCI = 2...");
let tab2 = gBrowser.addTab(BASE_URI, {userContextId: 2});
- is(tab2.getAttribute('usercontextid'), 2, "New tab has UCI equal 2");
+ is(tab2.getAttribute("usercontextid"), 2, "New tab has UCI equal 2");
let browser2 = gBrowser.getBrowserForTab(tab2);
yield BrowserTestUtils.browserLoaded(browser2);
yield ContentTask.spawn(browser2, blobURL, function(url) {
return new Promise(resolve => {
var xhr = new content.window.XMLHttpRequest();
xhr.onerror = function() { resolve("SendErrored"); }
@@ -44,17 +44,17 @@ add_task(function* test() {
xhr.send();
});
}).then(status => {
is(status, "SendErrored", "Using a blob URI from one user context id in another should not work");
});
info("Creating a tab with UCI = 1...");
let tab3 = gBrowser.addTab(BASE_URI, {userContextId: 1});
- is(tab3.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
+ is(tab3.getAttribute("usercontextid"), 1, "New tab has UCI equal 1");
let browser3 = gBrowser.getBrowserForTab(tab3);
yield BrowserTestUtils.browserLoaded(browser3);
yield ContentTask.spawn(browser3, blobURL, function(url) {
return new Promise(resolve => {
var xhr = new content.window.XMLHttpRequest();
xhr.open("GET", url);
--- a/browser/components/contextualidentity/test/browser/browser_eme.js
+++ b/browser/components/contextualidentity/test/browser/browser_eme.js
@@ -2,21 +2,21 @@
* Bug 1283325 - A test case to test the EME is originAttributes aware or not.
*/
const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
const TEST_HOST = "example.com";
const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
const TESTKEY = {
- initDataType: 'keyids',
+ initDataType: "keyids",
initData: '{"kids":["LwVHf8JLtPrv2GUXFW2v_A"], "type":"persistent-license"}',
kid: "LwVHf8JLtPrv2GUXFW2v_A",
key: "97b9ddc459c8d5ff23c1f2754c95abe8",
- sessionType: 'persistent-license',
+ sessionType: "persistent-license",
};
const USER_ID_DEFAULT = 0;
const USER_ID_PERSONAL = 1;
function* openTabInUserContext(uri, userContextId) {
// Open the tab in the correct userContextId.
let tab = gBrowser.addTab(uri, {userContextId});
@@ -55,17 +55,17 @@ function ByteArrayToHex(array) {
res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2);
}
return res;
}
function generateKeyObject(aKid, aKey) {
let keyObj = {
- kty: 'oct',
+ kty: "oct",
kid: aKid,
k: HexToBase64(aKey),
};
return new TextEncoder().encode(JSON.stringify({
keys: [keyObj]
}));
}
@@ -96,22 +96,22 @@ add_task(function* test() {
// Open a tab with the default container.
let defaultContainer = yield openTabInUserContext(TEST_URL + "empty_file.html", USER_ID_DEFAULT);
// Generate the key info for the default container.
let keyInfo = generateKeyInfo(TESTKEY);
// Update the media key for the default container.
let result = yield ContentTask.spawn(defaultContainer.browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
+ let access = yield content.navigator.requestMediaKeySystemAccess("org.w3.clearkey",
[{
initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
+ videoCapabilities: [{contentType: "video/webm"}],
+ sessionTypes: ["persistent-license"],
+ persistentState: "required",
}]);
let mediaKeys = yield access.createMediaKeys();
let session = mediaKeys.createSession(aKeyInfo.sessionType);
let res = {};
// Insert the media key.
yield new Promise(resolve => {
session.addEventListener("message", function(event) {
@@ -149,22 +149,22 @@ add_task(function* test() {
// Store the sessionId for the further checking.
keyInfo.sessionId = result.sessionId;
// Open a tab with personal container.
let personalContainer = yield openTabInUserContext(TEST_URL + "empty_file.html", USER_ID_PERSONAL);
yield ContentTask.spawn(personalContainer.browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
+ let access = yield content.navigator.requestMediaKeySystemAccess("org.w3.clearkey",
[{
initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
+ videoCapabilities: [{contentType: "video/webm"}],
+ sessionTypes: ["persistent-license"],
+ persistentState: "required",
}]);
let mediaKeys = yield access.createMediaKeys();
let session = mediaKeys.createSession(aKeyInfo.sessionType);
// First, load the session to check that mediakeys do not share with
// default container.
yield session.load(aKeyInfo.sessionId);
--- a/browser/components/contextualidentity/test/browser/browser_favicon.js
+++ b/browser/components/contextualidentity/test/browser/browser_favicon.js
@@ -79,18 +79,18 @@ add_task(function* setup() {
// Make sure userContext is enabled.
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true]
]});
// Create a http server for the image cache test.
if (!gHttpServer) {
gHttpServer = new HttpServer();
- gHttpServer.registerPathHandler('/', loadIndexHandler);
- gHttpServer.registerPathHandler('/favicon.png', loadFaviconHandler);
+ gHttpServer.registerPathHandler("/", loadIndexHandler);
+ gHttpServer.registerPathHandler("/favicon.png", loadFaviconHandler);
gHttpServer.start(-1);
}
});
registerCleanupFunction(() => {
gHttpServer.stop(() => {
gHttpServer = null;
});
--- a/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js
+++ b/browser/components/contextualidentity/test/browser/browser_forgetAPI_EME_forgetThisSite.js
@@ -8,21 +8,21 @@ const TEST_HOST = "example.com";
const TEST_URL = "http://" + TEST_HOST + "/browser/browser/components/contextualidentity/test/browser/";
const USER_CONTEXTS = [
"default",
"personal",
];
const TEST_EME_KEY = {
- initDataType: 'keyids',
+ initDataType: "keyids",
initData: '{"kids":["LwVHf8JLtPrv2GUXFW2v_A"], "type":"persistent-license"}',
kid: "LwVHf8JLtPrv2GUXFW2v_A",
key: "97b9ddc459c8d5ff23c1f2754c95abe8",
- sessionType: 'persistent-license',
+ sessionType: "persistent-license",
};
//
// Support functions.
//
function* openTabInUserContext(uri, userContextId) {
// Open the tab in the correct userContextId.
@@ -62,17 +62,17 @@ function ByteArrayToHex(array) {
res += ("0" + bin.charCodeAt(i).toString(16)).substr(-2);
}
return res;
}
function generateKeyObject(aKid, aKey) {
let keyObj = {
- kty: 'oct',
+ kty: "oct",
kid: aKid,
k: HexToBase64(aKey),
};
return new TextEncoder().encode(JSON.stringify({
keys: [keyObj]
}));
}
@@ -90,22 +90,22 @@ function generateKeyInfo(aData) {
// Setup a EME key for the given browser, and return the sessionId.
function* setupEMEKey(browser) {
// Generate the key info.
let keyInfo = generateKeyInfo(TEST_EME_KEY);
// Setup the EME key.
let result = yield ContentTask.spawn(browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
+ let access = yield content.navigator.requestMediaKeySystemAccess("org.w3.clearkey",
[{
initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
+ videoCapabilities: [{contentType: "video/webm"}],
+ sessionTypes: ["persistent-license"],
+ persistentState: "required",
}]);
let mediaKeys = yield access.createMediaKeys();
let session = mediaKeys.createSession(aKeyInfo.sessionType);
let res = {};
// Insert the EME key.
yield new Promise(resolve => {
session.addEventListener("message", function(event) {
@@ -145,22 +145,22 @@ function* setupEMEKey(browser) {
// Check whether the EME key has been cleared.
function* checkEMEKey(browser, emeSessionId) {
// Generate the key info.
let keyInfo = generateKeyInfo(TEST_EME_KEY);
keyInfo.sessionId = emeSessionId;
yield ContentTask.spawn(browser, keyInfo, function* (aKeyInfo) {
- let access = yield content.navigator.requestMediaKeySystemAccess('org.w3.clearkey',
+ let access = yield content.navigator.requestMediaKeySystemAccess("org.w3.clearkey",
[{
initDataTypes: [aKeyInfo.initDataType],
- videoCapabilities: [{contentType: 'video/webm'}],
- sessionTypes: ['persistent-license'],
- persistentState: 'required',
+ videoCapabilities: [{contentType: "video/webm"}],
+ sessionTypes: ["persistent-license"],
+ persistentState: "required",
}]);
let mediaKeys = yield access.createMediaKeys();
let session = mediaKeys.createSession(aKeyInfo.sessionType);
// First, load the session with the sessionId.
yield session.load(aKeyInfo.sessionId);
let map = session.keyStatuses;
--- a/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
+++ b/browser/components/contextualidentity/test/browser/browser_forgetaboutsite.js
@@ -198,17 +198,17 @@ function* test_cache_cleared() {
}
// Image Cache
function* test_image_cache_cleared() {
let tabs = [];
for (let userContextId of Object.keys(USER_CONTEXTS)) {
// Open our tab in the given user context to cache image.
- tabs[userContextId] = yield* openTabInUserContext('http://localhost:' + gHttpServer.identity.primaryPort + '/loadImage.html',
+ tabs[userContextId] = yield* openTabInUserContext("http://localhost:" + gHttpServer.identity.primaryPort + "/loadImage.html",
userContextId);
yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
}
let expectedHits = USER_CONTEXTS.length;
// Check that image cache works with the userContextId.
is(gHits, expectedHits, "The image should be loaded" + expectedHits + "times.");
@@ -217,17 +217,17 @@ function* test_image_cache_cleared() {
gHits = 0;
// Forget the site.
ForgetAboutSite.removeDataFromDomain("localhost:" + gHttpServer.identity.primaryPort + "/");
// Load again.
for (let userContextId of Object.keys(USER_CONTEXTS)) {
// Open our tab in the given user context to cache image.
- tabs[userContextId] = yield* openTabInUserContext('http://localhost:' + gHttpServer.identity.primaryPort + '/loadImage.html',
+ tabs[userContextId] = yield* openTabInUserContext("http://localhost:" + gHttpServer.identity.primaryPort + "/loadImage.html",
userContextId);
yield BrowserTestUtils.removeTab(tabs[userContextId].tab);
}
// Check that image cache was cleared and the server gets another two hits.
is(gHits, expectedHits, "The image should be loaded" + expectedHits + "times.");
}
@@ -317,18 +317,18 @@ add_task(function* setup() {
// Make sure userContext is enabled.
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true]
]});
// Create a http server for the image cache test.
if (!gHttpServer) {
gHttpServer = new HttpServer();
- gHttpServer.registerPathHandler('/image.png', imageHandler);
- gHttpServer.registerPathHandler('/loadImage.html', loadImagePageHandler);
+ gHttpServer.registerPathHandler("/image.png", imageHandler);
+ gHttpServer.registerPathHandler("/loadImage.html", loadImagePageHandler);
gHttpServer.start(-1);
}
});
let tests = [
test_cookie_cleared,
test_cache_cleared,
test_image_cache_cleared,
--- a/browser/components/contextualidentity/test/browser/browser_imageCache.js
+++ b/browser/components/contextualidentity/test/browser/browser_imageCache.js
@@ -1,23 +1,23 @@
let Cu = Components.utils;
let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
const NUM_USER_CONTEXTS = 3;
let gHits = 0;
let server = new HttpServer();
-server.registerPathHandler('/image.png', imageHandler);
-server.registerPathHandler('/file.html', fileHandler);
+server.registerPathHandler("/image.png", imageHandler);
+server.registerPathHandler("/file.html", fileHandler);
server.start(-1);
-let BASE_URI = 'http://localhost:' + server.identity.primaryPort;
-let IMAGE_URI = BASE_URI + '/image.png';
-let FILE_URI = BASE_URI + '/file.html';
+let BASE_URI = "http://localhost:" + server.identity.primaryPort;
+let IMAGE_URI = BASE_URI + "/image.png";
+let FILE_URI = BASE_URI + "/file.html";
function imageHandler(metadata, response) {
gHits++;
response.setHeader("Cache-Control", "max-age=10000", false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.setHeader("Content-Type", "image/png", false);
var body = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAEUlEQVQImWP4z8AAQTAamQkAhpcI+DeMzFcAAAAASUVORK5CYII=";
response.bodyOutputStream.write(body, body.length);
--- a/browser/components/contextualidentity/test/browser/browser_middleClick.js
+++ b/browser/components/contextualidentity/test/browser/browser_middleClick.js
@@ -12,17 +12,17 @@ add_task(function* () {
let browser = gBrowser.getBrowserForTab(tab);
yield BrowserTestUtils.browserLoaded(browser);
info("Create a HTMLAnchorElement...");
yield ContentTask.spawn(browser, URI,
function(uri) {
let anchor = content.document.createElement("a");
- anchor.setAttribute('id', 'clickMe');
+ anchor.setAttribute("id", "clickMe");
anchor.setAttribute("href", uri);
anchor.appendChild(content.document.createTextNode("click me!"));
content.document.body.appendChild(anchor);
}
);
info("Synthesize a mouse click and wait for a new tab...");
let newTab = yield new Promise((resolve, reject) => {
--- a/browser/components/contextualidentity/test/browser/browser_newtabButton.js
+++ b/browser/components/contextualidentity/test/browser/browser_newtabButton.js
@@ -4,17 +4,17 @@
// the correct context id is opened
add_task(function* test_menu_with_timeout() {
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true],
["privacy.userContext.longPressBehavior", 2]
]});
- let newTab = document.getElementById('tabbrowser-tabs');
+ let newTab = document.getElementById("tabbrowser-tabs");
let newTabButton = document.getAnonymousElementByAttribute(newTab, "anonid", "tabs-newtab-button");
ok(newTabButton, "New tab button exists");
ok(!newTabButton.hidden, "New tab button is visible");
yield BrowserTestUtils.waitForCondition(() => !!document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup"), "Wait for popup to exist");
let popup = document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup");
for (let i = 1; i <= 4; i++) {
let popupShownPromise = BrowserTestUtils.waitForEvent(popup, "popupshown");
@@ -25,28 +25,28 @@ add_task(function* test_menu_with_timeou
ok(contextIdItem, `User context id ${i} exists`);
let waitForTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
EventUtils.synthesizeMouseAtCenter(contextIdItem, {});
let tab = yield waitForTabPromise;
- is(tab.getAttribute('usercontextid'), i, `New tab has UCI equal ${i}`);
+ is(tab.getAttribute("usercontextid"), i, `New tab has UCI equal ${i}`);
yield BrowserTestUtils.removeTab(tab);
}
});
add_task(function* test_menu_without_timeout() {
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true],
["privacy.userContext.longPressBehavior", 1]
]});
- let newTab = document.getElementById('tabbrowser-tabs');
+ let newTab = document.getElementById("tabbrowser-tabs");
let newTabButton = document.getAnonymousElementByAttribute(newTab, "anonid", "tabs-newtab-button");
ok(newTabButton, "New tab button exists");
ok(!newTabButton.hidden, "New tab button is visible");
yield BrowserTestUtils.waitForCondition(() => !!document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup"), "Wait for popup to exist");
let popup = document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup");
for (let i = 1; i <= 4; i++) {
let popupShownPromise = BrowserTestUtils.waitForEvent(popup, "popupshown");
@@ -57,28 +57,28 @@ add_task(function* test_menu_without_tim
ok(contextIdItem, `User context id ${i} exists`);
let waitForTabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
EventUtils.synthesizeMouseAtCenter(contextIdItem, {});
let tab = yield waitForTabPromise;
- is(tab.getAttribute('usercontextid'), i, `New tab has UCI equal ${i}`);
+ is(tab.getAttribute("usercontextid"), i, `New tab has UCI equal ${i}`);
yield BrowserTestUtils.removeTab(tab);
}
});
add_task(function* test_no_menu() {
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true],
["privacy.userContext.longPressBehavior", 0]
]});
- let newTab = document.getElementById('tabbrowser-tabs');
+ let newTab = document.getElementById("tabbrowser-tabs");
let newTabButton = document.getAnonymousElementByAttribute(newTab, "anonid", "tabs-newtab-button");
ok(newTabButton, "New tab button exists");
ok(!newTabButton.hidden, "New tab button is visible");
let popup = document.getAnonymousElementByAttribute(newTab, "anonid", "newtab-popup");
ok(!popup, "new tab should not have a popup");
});
add_task(function* test_private_mode() {
--- a/browser/components/contextualidentity/test/browser/browser_relatedTab.js
+++ b/browser/components/contextualidentity/test/browser/browser_relatedTab.js
@@ -4,28 +4,28 @@
* Bug 1325014 - Adding tab related to current tab inherits current tab's container usercontextid unless otherwise specified
*/
add_task(function* () {
let tab = gBrowser.addTab("about:blank", {userContextId: 1});
gBrowser.selectedTab = tab;
let relatedTab = gBrowser.addTab("about:blank", {relatedToCurrent: true});
- is(relatedTab.getAttribute('usercontextid'), 1, "Related tab (relatedToCurrent) inherits current tab's usercontextid");
+ is(relatedTab.getAttribute("usercontextid"), 1, "Related tab (relatedToCurrent) inherits current tab's usercontextid");
yield BrowserTestUtils.removeTab(relatedTab);
gBrowser.selectedTab = tab;
relatedTab = gBrowser.addTab("about:blank", {relatedToCurrent: true, userContextId: 2});
- is(relatedTab.getAttribute('usercontextid'), 2, "Related tab (relatedToCurrent) with overridden usercontextid");
+ is(relatedTab.getAttribute("usercontextid"), 2, "Related tab (relatedToCurrent) with overridden usercontextid");
yield BrowserTestUtils.removeTab(relatedTab);
gBrowser.selectedTab = tab;
relatedTab = gBrowser.addTab("about:blank", {referrerURI: gBrowser.currentURI});
- is(relatedTab.getAttribute('usercontextid'), 1, "Related tab (referrer) inherits current tab's usercontextid");
+ is(relatedTab.getAttribute("usercontextid"), 1, "Related tab (referrer) inherits current tab's usercontextid");
yield BrowserTestUtils.removeTab(relatedTab);
gBrowser.selectedTab = tab;
relatedTab = gBrowser.addTab("about:blank", {referrerURI: gBrowser.currentURI, userContextId: 2});
- is(relatedTab.getAttribute('usercontextid'), 2, "Related tab (referrer) with overridden usercontextid");
+ is(relatedTab.getAttribute("usercontextid"), 2, "Related tab (referrer) with overridden usercontextid");
yield BrowserTestUtils.removeTab(relatedTab);
yield BrowserTestUtils.removeTab(tab);
});
--- a/browser/components/contextualidentity/test/browser/browser_windowName.js
+++ b/browser/components/contextualidentity/test/browser/browser_windowName.js
@@ -16,51 +16,51 @@ add_task(function* setup() {
yield SpecialPowers.pushPrefEnv({"set": [
["privacy.userContext.enabled", true],
["browser.link.open_newwindow", 3],
]});
});
add_task(function* test() {
info("Creating first tab...");
- let tab1 = gBrowser.addTab(BASE_URI + '?old', {userContextId: 1});
+ let tab1 = gBrowser.addTab(BASE_URI + "?old", {userContextId: 1});
let browser1 = gBrowser.getBrowserForTab(tab1);
yield BrowserTestUtils.browserLoaded(browser1);
yield ContentTask.spawn(browser1, null, function(opts) {
- content.window.name = 'tab-1';
+ content.window.name = "tab-1";
});
info("Creating second tab...");
- let tab2 = gBrowser.addTab(BASE_URI + '?old', {userContextId: 2});
+ let tab2 = gBrowser.addTab(BASE_URI + "?old", {userContextId: 2});
let browser2 = gBrowser.getBrowserForTab(tab2);
yield BrowserTestUtils.browserLoaded(browser2);
yield ContentTask.spawn(browser2, null, function(opts) {
- content.window.name = 'tab-2';
+ content.window.name = "tab-2";
});
// Let's try to open a window from tab1 with a name 'tab-2'.
info("Opening a window from the first tab...");
- yield ContentTask.spawn(browser1, { url: BASE_URI + '?new' }, function* (opts) {
+ yield ContentTask.spawn(browser1, { url: BASE_URI + "?new" }, function* (opts) {
yield (new content.window.wrappedJSObject.Promise(resolve => {
- let w = content.window.wrappedJSObject.open(opts.url, 'tab-2');
+ let w = content.window.wrappedJSObject.open(opts.url, "tab-2");
w.onload = function() { resolve(); }
}));
});
- is(browser1.contentTitle, '?old', "Tab1 title must be 'old'");
+ is(browser1.contentTitle, "?old", "Tab1 title must be 'old'");
is(browser1.contentPrincipal.userContextId, 1, "Tab1 UCI must be 1");
- is(browser2.contentTitle, '?old', "Tab2 title must be 'old'");
+ is(browser2.contentTitle, "?old", "Tab2 title must be 'old'");
is(browser2.contentPrincipal.userContextId, 2, "Tab2 UCI must be 2");
let found = false;
for (let i = 0; i < gBrowser.tabContainer.childNodes.length; ++i) {
let tab = gBrowser.tabContainer.childNodes[i];
let browser = gBrowser.getBrowserForTab(tab);
- if (browser.contentTitle == '?new') {
+ if (browser.contentTitle == "?new") {
is(browser.contentPrincipal.userContextId, 1, "Tab3 UCI must be 1");
isnot(browser, browser1, "Tab3 is not browser 1");
isnot(browser, browser2, "Tab3 is not browser 2");
gBrowser.removeTab(tab);
found = true;
break;
}
}
--- a/browser/components/contextualidentity/test/browser/browser_windowOpen.js
+++ b/browser/components/contextualidentity/test/browser/browser_windowOpen.js
@@ -12,28 +12,28 @@ add_task(function* setup() {
["browser.link.open_newwindow", 2],
]});
});
add_task(function* test() {
info("Creating a tab with UCI = 1...");
let tab = gBrowser.addTab(BASE_URI, {userContextId: 1});
- is(tab.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
+ is(tab.getAttribute("usercontextid"), 1, "New tab has UCI equal 1");
let browser = gBrowser.getBrowserForTab(tab);
yield BrowserTestUtils.browserLoaded(browser);
info("Opening a new window from this tab...");
ContentTask.spawn(browser, BASE_URI, function(url) {
content.window.newWindow = content.window.open(url, "_blank");
});
let newWin = yield BrowserTestUtils.waitForNewWindow();
let newTab = newWin.gBrowser.selectedTab;
yield BrowserTestUtils.browserLoaded(newTab.linkedBrowser);
- is(newTab.getAttribute('usercontextid'), 1, "New tab has UCI equal 1");
+ is(newTab.getAttribute("usercontextid"), 1, "New tab has UCI equal 1");
info("Closing the new window and tab...");
yield BrowserTestUtils.closeWindow(newWin);
yield BrowserTestUtils.removeTab(tab);
});
--- a/browser/components/customizableui/CustomizableUI.jsm
+++ b/browser/components/customizableui/CustomizableUI.jsm
@@ -613,17 +613,17 @@ var CustomizableUIInternal = {
gPendingBuildAreas.set(area, new Map());
}
let pendingNodes = gPendingBuildAreas.get(area);
pendingNodes.set(aToolbar, aExistingChildren);
return;
}
let props = {type: CustomizableUI.TYPE_TOOLBAR, legacy: true};
let defaultsetAttribute = aToolbar.getAttribute("defaultset") || "";
- props.defaultPlacements = defaultsetAttribute.split(',').filter(s => s);
+ props.defaultPlacements = defaultsetAttribute.split(",").filter(s => s);
this.registerArea(area, props);
areaProperties = gAreas.get(area);
}
this.beginBatchUpdate();
try {
let placements = gPlacements.get(area);
if (!placements && areaProperties.has("legacy")) {
@@ -976,17 +976,17 @@ var CustomizableUIInternal = {
if (gPalette.has(aWidgetId) || this.isSpecialWidget(aWidgetId)) {
container.removeChild(widgetNode);
} else {
areaNode.toolbox.palette.appendChild(widgetNode);
}
this.notifyListeners("onWidgetAfterDOMChange", widgetNode, null, container, true);
if (isToolbar) {
- areaNode.setAttribute("currentset", gPlacements.get(aArea).join(','));
+ areaNode.setAttribute("currentset", gPlacements.get(aArea).join(","));
}
let windowCache = gSingleWrapperCache.get(window);
if (windowCache) {
windowCache.delete(aWidgetId);
}
}
if (!gResetting) {
@@ -1148,17 +1148,17 @@ var CustomizableUIInternal = {
widgetNode.setAttribute("wrap", "true");
}
}
let [insertionContainer, nextNode] = this.findInsertionPoints(widgetNode, aAreaNode);
this.insertWidgetBefore(widgetNode, nextNode, insertionContainer, areaId);
if (gAreas.get(areaId).get("type") == CustomizableUI.TYPE_TOOLBAR) {
- aAreaNode.setAttribute("currentset", gPlacements.get(areaId).join(','));
+ aAreaNode.setAttribute("currentset", gPlacements.get(areaId).join(","));
}
},
findInsertionPoints(aNode, aAreaNode) {
let areaId = aAreaNode.id;
let props = gAreas.get(areaId);
// For overflowable toolbars, rely on them (because the work is more complicated):
@@ -2727,17 +2727,17 @@ var CustomizableUIInternal = {
let isRemovable = this.isWidgetRemovable(itemNodeOrItem);
let isInDefault = defaultPlacements.indexOf(item) != -1;
return isRemovable || isInDefault;
};
// Toolbars have a currentSet property which also deals correctly with overflown
// widgets (if any) - use that instead:
if (props.get("type") == CustomizableUI.TYPE_TOOLBAR) {
let currentSet = container.currentSet;
- currentPlacements = currentSet ? currentSet.split(',') : [];
+ currentPlacements = currentSet ? currentSet.split(",") : [];
currentPlacements = currentPlacements.filter(removableOrDefault);
} else {
// Clone the array so we don't modify the actual placements...
currentPlacements = [...currentPlacements];
currentPlacements = currentPlacements.filter((item) => {
let itemNode = container.getElementsByAttribute("id", item)[0];
return itemNode && removableOrDefault(itemNode || item);
});
@@ -4115,17 +4115,17 @@ OverflowableToolbar.prototype = {
show() {
if (this._panel.state == "open") {
return Promise.resolve();
}
return new Promise(resolve => {
let doc = this._panel.ownerDocument;
this._panel.hidden = false;
let contextMenu = doc.getElementById(this._panel.getAttribute("context"));
- gELS.addSystemEventListener(contextMenu, 'command', this, true);
+ gELS.addSystemEventListener(contextMenu, "command", this, true);
let anchor = doc.getAnonymousElementByAttribute(this._chevron, "class", "toolbarbutton-icon");
this._panel.openPopup(anchor || this._chevron);
this._chevron.open = true;
let overflowableToolbarInstance = this;
this._panel.addEventListener("popupshown", function onPopupShown(aEvent) {
this.removeEventListener("popupshown", onPopupShown);
this.addEventListener("dragover", overflowableToolbarInstance);
@@ -4145,17 +4145,17 @@ OverflowableToolbar.prototype = {
},
_onPanelHiding(aEvent) {
this._chevron.open = false;
this._panel.removeEventListener("dragover", this);
this._panel.removeEventListener("dragend", this);
let doc = aEvent.target.ownerDocument;
let contextMenu = doc.getElementById(this._panel.getAttribute("context"));
- gELS.removeSystemEventListener(contextMenu, 'command', this, true);
+ gELS.removeSystemEventListener(contextMenu, "command", this, true);
},
onOverflow(aEvent) {
// The rangeParent check is here because of bug 1111986 and ensuring that
// overflow events from the bookmarks toolbar items or similar things that
// manage their own overflow don't trigger an overflow on the entire toolbar
if (!this._enabled ||
(aEvent && aEvent.target != this._toolbar.customizationTarget) ||
--- a/browser/components/customizableui/CustomizeMode.jsm
+++ b/browser/components/customizableui/CustomizeMode.jsm
@@ -1324,17 +1324,17 @@ CustomizeMode.prototype = {
this._removeDragHandlers(aContainer);
DragPositionManager.remove(this.window, aArea, aContainer);
this.areas.delete(aContainer);
}
},
openAddonsManagerThemes(aEvent) {
aEvent.target.parentNode.parentNode.hidePopup();
- this.window.BrowserOpenAddonsMgr('addons://list/theme');
+ this.window.BrowserOpenAddonsMgr("addons://list/theme");
},
getMoreThemes(aEvent) {
aEvent.target.parentNode.parentNode.hidePopup();
let getMoreURL = Services.urlFormatter.formatURLPref("lightweightThemes.getMoreURL");
this.window.openUILinkIn(getMoreURL, "tab");
},
@@ -2025,17 +2025,17 @@ CustomizeMode.prototype = {
} else {
// otherwise:
prop = "borderRightWidth";
otherProp = "border-left-width";
}
if (makeSpaceImmediately) {
aItem.setAttribute("notransition", "true");
}
- aItem.style[prop] = width + 'px';
+ aItem.style[prop] = width + "px";
aItem.style.removeProperty(otherProp);
if (makeSpaceImmediately) {
// Force a layout flush:
aItem.getBoundingClientRect();
aItem.removeAttribute("notransition");
}
}
}
--- a/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js
+++ b/browser/components/customizableui/test/browser_1161838_inserted_new_default_buttons.js
@@ -50,17 +50,17 @@ function test() {
let futureNavbarPlacements = gFuturePlacements.get(CustomizableUI.AREA_NAVBAR);
ok(futureNavbarPlacements, "Should have placements for nav-bar");
if (futureNavbarPlacements) {
ok(futureNavbarPlacements.has(testWidgetNew.id), "widget should be in future placements");
}
CustomizableUIInternal._placeNewDefaultWidgetsInArea(CustomizableUI.AREA_NAVBAR);
let indexInSavedPlacements = savedPlacements.indexOf(testWidgetNew.id);
- info("Saved placements: " + savedPlacements.join(', '));
+ info("Saved placements: " + savedPlacements.join(", "));
isnot(indexInSavedPlacements, -1, "Widget should have been inserted");
is(indexInSavedPlacements, savedPlacements.indexOf("bookmarks-menu-button") + 1,
"Widget should be in the right place.");
if (futureNavbarPlacements) {
ok(!futureNavbarPlacements.has(testWidgetNew.id), "widget should be out of future placements");
}
--- a/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js
+++ b/browser/components/customizableui/test/browser_876926_customize_mode_wrapping.js
@@ -50,27 +50,27 @@ function isLast(containerId, defaultPlac
"Widget " + id + " should be in " + containerId + " in customizing window.");
is(otherWin.document.getElementById(containerId).customizationTarget.lastChild.id, id,
"Widget " + id + " should be in " + containerId + " in other window.");
}
function getLastVisibleNodeInToolbar(containerId, win = window) {
let container = win.document.getElementById(containerId).customizationTarget;
let rv = container.lastChild;
- while (rv && (rv.getAttribute('hidden') == 'true' || (rv.firstChild && rv.firstChild.getAttribute('hidden') == 'true'))) {
+ while (rv && (rv.getAttribute("hidden") == "true" || (rv.firstChild && rv.firstChild.getAttribute("hidden") == "true"))) {
rv = rv.previousSibling;
}
return rv;
}
function isLastVisibleInToolbar(containerId, defaultPlacements, id) {
let newPlacements;
for (let i = defaultPlacements.length - 1; i >= 0; i--) {
let el = document.getElementById(defaultPlacements[i]);
- if (el && el.getAttribute('hidden') != 'true') {
+ if (el && el.getAttribute("hidden") != "true") {
newPlacements = [...defaultPlacements];
newPlacements.splice(i + 1, 0, id);
break;
}
}
if (!newPlacements) {
assertAreaPlacements(containerId, defaultPlacements.concat([id]));
} else {
--- a/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js
+++ b/browser/components/customizableui/test/browser_876944_customize_mode_create_destroy.js
@@ -5,17 +5,17 @@
"use strict";
const kTestWidget1 = "test-customize-mode-create-destroy1";
const kTestWidget2 = "test-customize-mode-create-destroy2";
// Creating and destroying a widget should correctly wrap/unwrap stuff
add_task(function* testWrapUnwrap() {
yield startCustomizing();
- CustomizableUI.createWidget({id: kTestWidget1, label: 'Pretty label', tooltiptext: 'Pretty tooltip'});
+ CustomizableUI.createWidget({id: kTestWidget1, label: "Pretty label", tooltiptext: "Pretty tooltip"});
let elem = document.getElementById(kTestWidget1);
let wrapper = document.getElementById("wrapper-" + kTestWidget1);
ok(elem, "There should be an item");
ok(wrapper, "There should be a wrapper");
is(wrapper.firstChild.id, kTestWidget1, "Wrapper should have test widget");
is(wrapper.parentNode.id, "customization-palette", "Wrapper should be in palette");
CustomizableUI.destroyWidget(kTestWidget1);
wrapper = document.getElementById("wrapper-" + kTestWidget1);
@@ -27,17 +27,17 @@ add_task(function* testWrapUnwrap() {
// Creating and destroying a widget should correctly deal with panel placeholders
add_task(function* testPanelPlaceholders() {
let panel = document.getElementById(CustomizableUI.AREA_PANEL);
// The value of expectedPlaceholders depends on the default palette layout.
// Bug 1229236 is for these tests to be smarter so the test doesn't need to
// change when the default placements change.
let expectedPlaceholders = 1 + (isInDevEdition() ? 1 : 0);
is(panel.querySelectorAll(".panel-customization-placeholder").length, expectedPlaceholders, "The number of placeholders should be correct.");
- CustomizableUI.createWidget({id: kTestWidget2, label: 'Pretty label', tooltiptext: 'Pretty tooltip', defaultArea: CustomizableUI.AREA_PANEL});
+ CustomizableUI.createWidget({id: kTestWidget2, label: "Pretty label", tooltiptext: "Pretty tooltip", defaultArea: CustomizableUI.AREA_PANEL});
let elem = document.getElementById(kTestWidget2);
let wrapper = document.getElementById("wrapper-" + kTestWidget2);
ok(elem, "There should be an item");
ok(wrapper, "There should be a wrapper");
is(wrapper.firstChild.id, kTestWidget2, "Wrapper should have test widget");
is(wrapper.parentNode, panel, "Wrapper should be in panel");
expectedPlaceholders = isInDevEdition() ? 1 : 3;
is(panel.querySelectorAll(".panel-customization-placeholder").length, expectedPlaceholders, "The number of placeholders should be correct.");
--- a/browser/components/customizableui/test/browser_877006_missing_view.js
+++ b/browser/components/customizableui/test/browser_877006_missing_view.js
@@ -1,21 +1,21 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Should be able to add broken view widget
add_task(function testAddbrokenViewWidget() {
- const kWidgetId = 'test-877006-broken-widget';
+ const kWidgetId = "test-877006-broken-widget";
let widgetSpec = {
id: kWidgetId,
- type: 'view',
- viewId: 'idontexist',
+ type: "view",
+ viewId: "idontexist",
/* Empty handler so we try to attach it maybe? */
onViewShowing() {
}
};
let noError = true;
try {
CustomizableUI.createWidget(widgetSpec);
--- a/browser/components/customizableui/test/browser_887438_currentset_shim.js
+++ b/browser/components/customizableui/test/browser_887438_currentset_shim.js
@@ -17,24 +17,24 @@ add_task(function() {
}
}
for (let node of overflowPanelList.childNodes) {
if (node.getAttribute("skipintoolbarset") != "true") {
nodeIds.push(node.id);
}
}
let currentSet = navbar.currentSet;
- is(currentSet.split(',').length, nodeIds.length, "Should be just as many nodes as there are.");
- is(currentSet, nodeIds.join(','), "Current set and node IDs should match.");
+ is(currentSet.split(",").length, nodeIds.length, "Should be just as many nodes as there are.");
+ is(currentSet, nodeIds.join(","), "Current set and node IDs should match.");
});
// Insert, then remove items
add_task(function() {
let currentSet = navbar.currentSet;
- let newCurrentSet = currentSet.replace('home-button', 'feed-button,sync-button,home-button');
+ let newCurrentSet = currentSet.replace("home-button", "feed-button,sync-button,home-button");
navbar.currentSet = newCurrentSet;
is(newCurrentSet, navbar.currentSet, "Current set should match expected current set.");
let feedBtn = document.getElementById("feed-button");
let syncBtn = document.getElementById("sync-button");
ok(feedBtn, "Feed button should have been added.");
ok(syncBtn, "Sync button should have been added.");
if (feedBtn && syncBtn) {
let feedParent = feedBtn.parentNode;
@@ -49,17 +49,17 @@ add_task(function() {
}
navbar.currentSet = currentSet;
is(currentSet, navbar.currentSet, "Should be able to remove the added items.");
});
// Simultaneous insert/remove:
add_task(function() {
let currentSet = navbar.currentSet;
- let newCurrentSet = currentSet.replace('home-button', 'feed-button');
+ let newCurrentSet = currentSet.replace("home-button", "feed-button");
navbar.currentSet = newCurrentSet;
is(newCurrentSet, navbar.currentSet, "Current set should match expected current set.");
let feedBtn = document.getElementById("feed-button");
ok(feedBtn, "Feed button should have been added.");
let homeBtn = document.getElementById("home-button");
ok(!homeBtn, "Home button should have been removed.");
if (feedBtn) {
let feedParent = feedBtn.parentNode;
--- a/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js
+++ b/browser/components/customizableui/test/browser_942581_unregisterArea_keeps_placements.js
@@ -10,17 +10,17 @@ const kTestWidgetCount = 3;
registerCleanupFunction(removeCustomToolbars);
// unregisterArea should keep placements by default and restore them when re-adding the area
add_task(function*() {
let widgetIds = [];
for (let i = 0; i < kTestWidgetCount; i++) {
let id = kTestWidgetPfx + i;
widgetIds.push(id);
- let spec = {id, type: 'button', removable: true, label: "unregisterArea test", tooltiptext: "" + i};
+ let spec = {id, type: "button", removable: true, label: "unregisterArea test", tooltiptext: "" + i};
CustomizableUI.createWidget(spec);
}
for (let i = kTestWidgetCount; i < kTestWidgetCount * 2; i++) {
let id = kTestWidgetPfx + i;
widgetIds.push(id);
createDummyXULButton(id, "unregisterArea XUL test " + i);
}
let toolbarNode = createToolbarWithPlacements(kToolbarName, widgetIds);
--- a/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js
+++ b/browser/components/customizableui/test/browser_952963_areaType_getter_no_area.js
@@ -27,17 +27,17 @@ add_task(function*() {
toolbarNode.remove();
let w = CustomizableUI.getWidget(kUnregisterAreaTestWidget);
checkAreaType(w);
w = CustomizableUI.getWidget(kTestWidget);
checkAreaType(w);
- let spec = {id: kUnregisterAreaTestWidget, type: 'button', removable: true,
+ let spec = {id: kUnregisterAreaTestWidget, type: "button", removable: true,
label: "areaType test", tooltiptext: "areaType test"};
CustomizableUI.createWidget(spec);
toolbarNode = createToolbarWithPlacements(kToolbarName, [kUnregisterAreaTestWidget]);
CustomizableUI.unregisterArea(kToolbarName);
toolbarNode.remove();
w = CustomizableUI.getWidget(spec.id);
checkAreaType(w);
CustomizableUI.removeWidgetFromArea(kUnregisterAreaTestWidget);
--- a/browser/components/customizableui/test/browser_956602_remove_special_widget.js
+++ b/browser/components/customizableui/test/browser_956602_remove_special_widget.js
@@ -6,17 +6,17 @@
// Adding a separator and then dragging it out of the navbar shouldn't throw
add_task(function*() {
try {
let navbar = document.getElementById("nav-bar");
let separatorSelector = "toolbarseparator[id^=customizableui-special-separator]";
ok(!navbar.querySelector(separatorSelector), "Shouldn't be a separator in the navbar");
- CustomizableUI.addWidgetToArea('separator', 'nav-bar');
+ CustomizableUI.addWidgetToArea("separator", "nav-bar");
yield startCustomizing();
let separator = navbar.querySelector(separatorSelector);
ok(separator, "There should be a separator in the navbar now.");
let palette = document.getElementById("customization-palette");
simulateItemDrag(separator, palette);
ok(!palette.querySelector(separatorSelector), "No separator in the palette.");
} catch (ex) {
Cu.reportError(ex);
--- a/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js
+++ b/browser/components/customizableui/test/browser_969661_character_encoding_navbar_disabled.js
@@ -10,17 +10,17 @@
add_task(function*() {
yield startCustomizing();
CustomizableUI.addWidgetToArea("characterencoding-button", "PanelUI-contents");
yield endCustomizing();
yield PanelUI.show();
let panelHiddenPromise = promisePanelHidden(window);
PanelUI.hide();
yield panelHiddenPromise;
- CustomizableUI.addWidgetToArea("characterencoding-button", 'nav-bar');
+ CustomizableUI.addWidgetToArea("characterencoding-button", "nav-bar");
let button = document.getElementById("characterencoding-button");
ok(!button.hasAttribute("disabled"), "Button shouldn't be disabled");
});
add_task(function asyncCleanup() {
resetCustomization();
});
--- a/browser/components/customizableui/test/browser_973641_button_addon.js
+++ b/browser/components/customizableui/test/browser_973641_button_addon.js
@@ -8,17 +8,17 @@ const kButton = "test_button_for_addon";
var initialLocation = gBrowser.currentURI.spec;
add_task(function*() {
info("Check addon button functionality");
// create mocked addon button on the navigation bar
let widgetSpec = {
id: kButton,
- type: 'button',
+ type: "button",
onClick() {
gBrowser.selectedTab = gBrowser.addTab("about:addons");
}
};
CustomizableUI.createWidget(widgetSpec);
CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_NAVBAR);
// check the button's functionality in navigation bar
--- a/browser/components/customizableui/test/browser_973932_addonbar_currentset.js
+++ b/browser/components/customizableui/test/browser_973932_addonbar_currentset.js
@@ -5,26 +5,26 @@
"use strict";
var addonbarID = CustomizableUI.AREA_ADDONBAR;
var addonbar = document.getElementById(addonbarID);
// Check that currentset is correctly updated after a reset:
add_task(function*() {
let placements = CustomizableUI.getWidgetIdsInArea(addonbarID);
- is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements");
+ is(placements.join(","), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements");
ok(CustomizableUI.inDefaultState, "Should be in default state");
info("Adding a spring to add-on bar shim");
CustomizableUI.addWidgetToArea("spring", addonbarID, 1);
ok(addonbar.getElementsByTagName("toolbarspring").length, "There should be a spring in the toolbar");
ok(!CustomizableUI.inDefaultState, "Should no longer be in default state");
placements = CustomizableUI.getWidgetIdsInArea(addonbarID);
- is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match placements after spring addition");
+ is(placements.join(","), addonbar.getAttribute("currentset"), "Addon-bar currentset should match placements after spring addition");
yield startCustomizing();
yield gCustomizeMode.reset();
ok(CustomizableUI.inDefaultState, "Should be in default state after reset");
placements = CustomizableUI.getWidgetIdsInArea(addonbarID);
- is(placements.join(','), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements after reset");
+ is(placements.join(","), addonbar.getAttribute("currentset"), "Addon-bar currentset should match default placements after reset");
ok(!addonbar.getElementsByTagName("toolbarspring").length, "There should be no spring in the toolbar");
yield endCustomizing();
});
--- a/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js
+++ b/browser/components/customizableui/test/browser_981418-widget-onbeforecreated-handler.js
@@ -1,29 +1,29 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
-const kWidgetId = 'test-981418-widget-onbeforecreated';
+const kWidgetId = "test-981418-widget-onbeforecreated";
// Should be able to add broken view widget
add_task(function* testAddOnBeforeCreatedWidget() {
let viewShownDeferred = Promise.defer();
let onBeforeCreatedCalled = false;
let widgetSpec = {
id: kWidgetId,
- type: 'view',
- viewId: kWidgetId + 'idontexistyet',
+ type: "view",
+ viewId: kWidgetId + "idontexistyet",
onBeforeCreated(doc) {
let view = doc.createElement("panelview");
- view.id = kWidgetId + 'idontexistyet';
+ view.id = kWidgetId + "idontexistyet";
let label = doc.createElement("label");
label.setAttribute("value", "Hello world");
- label.className = 'panel-subview-header';
+ label.className = "panel-subview-header";
view.appendChild(label);
document.getElementById("PanelUI-multiView").appendChild(view);
onBeforeCreatedCalled = true;
},
onViewShowing() {
viewShownDeferred.resolve();
}
};
--- a/browser/components/feeds/FeedConverter.js
+++ b/browser/components/feeds/FeedConverter.js
@@ -541,23 +541,23 @@ GenericProtocolHandler.prototype = {
if (iid.equals(Ci.nsIProtocolHandler) ||
iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
function FeedProtocolHandler() {
- this._init('feed');
+ this._init("feed");
}
FeedProtocolHandler.prototype = new GenericProtocolHandler();
FeedProtocolHandler.prototype.classID = Components.ID("{4f91ef2e-57ba-472e-ab7a-b4999e42d6c0}");
function PodCastProtocolHandler() {
- this._init('pcast');
+ this._init("pcast");
}
PodCastProtocolHandler.prototype = new GenericProtocolHandler();
PodCastProtocolHandler.prototype.classID = Components.ID("{1c31ed79-accd-4b94-b517-06e0c81999d5}");
var components = [FeedConverter,
FeedResultService,
FeedProtocolHandler,
PodCastProtocolHandler];
--- a/browser/components/feeds/FeedWriter.js
+++ b/browser/components/feeds/FeedWriter.js
@@ -175,17 +175,17 @@ FeedWriter.prototype = {
_setContentText(id, text) {
let element = this._document.getElementById(id);
let textNode = text.createDocumentFragment(element);
while (element.hasChildNodes())
element.removeChild(element.firstChild);
element.appendChild(textNode);
if (text.base) {
- element.setAttributeNS(XML_NS, 'base', text.base.spec);
+ element.setAttributeNS(XML_NS, "base", text.base.spec);
}
},
/**
* Safely sets the href attribute on an anchor tag, providing the URI
* specified can be loaded according to rules.
* @param element
* The element to set a URI attribute on
@@ -227,25 +227,25 @@ FeedWriter.prototype = {
},
_getString(key) {
return this._bundle.GetStringFromName(key);
},
_setCheckboxCheckedState(aCheckbox, aValue) {
// see checkbox.xml, xbl bindings are not applied within the sandbox! TODO
- let change = (aValue != (aCheckbox.getAttribute('checked') == 'true'));
+ let change = (aValue != (aCheckbox.getAttribute("checked") == "true"));
if (aValue)
- aCheckbox.setAttribute('checked', 'true');
+ aCheckbox.setAttribute("checked", "true");
else
- aCheckbox.removeAttribute('checked');
+ aCheckbox.removeAttribute("checked");
if (change) {
- let event = this._document.createEvent('Events');
- event.initEvent('CheckboxStateChange', true, true);
+ let event = this._document.createEvent("Events");
+ event.initEvent("CheckboxStateChange", true, true);
aCheckbox.dispatchEvent(event);
}
},
/**
* Returns a date suitable for displaying in the feed preview.
* If the date cannot be parsed, the return value is "false".
* @param dateString
@@ -263,18 +263,18 @@ FeedWriter.prototype = {
},
__dateFormatter: null,
get _dateFormatter() {
if (!this.__dateFormatter) {
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric',
- hour: 'numeric', minute: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric",
+ hour: "numeric", minute: "numeric" };
this.__dateFormatter = new Intl.DateTimeFormat(locale, dtOptions);
}
return this.__dateFormatter;
},
/**
* Returns the feed type.
*/
@@ -346,18 +346,18 @@ FeedWriter.prototype = {
let titleText = this._getFormattedString("linkTitleTextFormat",
[parts.getPropertyAsAString("title")]);
let feedTitleText = this._document.getElementById("feedTitleText");
let titleImageWidth = parseInt(parts.getPropertyAsAString("width")) + 15;
// Fix the margin on the main title, so that the image doesn't run over
// the underline
- feedTitleLink.setAttribute('title', titleText);
- feedTitleText.style.marginRight = titleImageWidth + 'px';
+ feedTitleLink.setAttribute("title", titleText);
+ feedTitleText.style.marginRight = titleImageWidth + "px";
this._safeSetURIAttribute(feedTitleLink, "href",
parts.getPropertyAsAString("link"));
} catch (e) {
LOG("Failed to set Title Image (this is benign): " + e);
}
},
@@ -742,25 +742,25 @@ FeedWriter.prototype = {
return;
let feedType = this._getFeedType();
// change the background
let header = this._document.getElementById("feedHeader");
switch (feedType) {
case Ci.nsIFeed.TYPE_VIDEO:
- header.className = 'videoPodcastBackground';
+ header.className = "videoPodcastBackground";
break;
case Ci.nsIFeed.TYPE_AUDIO:
- header.className = 'audioPodcastBackground';
+ header.className = "audioPodcastBackground";
break;
default:
- header.className = 'feedBackground';
+ header.className = "feedBackground";
}
let liveBookmarksMenuItem = this._document.getElementById("liveBookmarksMenuItem");
// Last-selected application
let menuItem = liveBookmarksMenuItem.cloneNode(false);
menuItem.removeAttribute("selected");
menuItem.setAttribute("id", "selectedAppMenuItem");
@@ -858,17 +858,17 @@ FeedWriter.prototype = {
let feedinfo1 = this._document.getElementById("feedSubscriptionInfo1");
let feedinfo1Str = this._getString(textfeedinfo1);
let feedinfo2 = this._document.getElementById("feedSubscriptionInfo2");
let feedinfo2Str = this._getString(textfeedinfo2);
feedinfo1.textContent = feedinfo1Str;
feedinfo2.textContent = feedinfo2Str;
- header.setAttribute('firstrun', 'true');
+ header.setAttribute("firstrun", "true");
this._mm.sendAsyncMessage("FeedWriter:ShownFirstRun");
}
},
/**
* Returns the original URI object of the feed and ensures that this
* component is only ever invoked from the preview document.
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -98,21 +98,21 @@ if (AppConstants.MOZ_CRASHREPORTER) {
"resource:///modules/ContentCrashHandlers.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "UnsubmittedCrashHandler",
"resource:///modules/ContentCrashHandlers.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "CrashSubmit",
"resource://gre/modules/CrashSubmit.jsm");
}
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
- return Services.strings.createBundle('chrome://branding/locale/brand.properties');
+ return Services.strings.createBundle("chrome://branding/locale/brand.properties");
});
XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
- return Services.strings.createBundle('chrome://browser/locale/browser.properties');
+ return Services.strings.createBundle("chrome://browser/locale/browser.properties");
});
// Seconds of idle before trying to create a bookmarks backup.
const BOOKMARKS_BACKUP_IDLE_TIME_SEC = 8 * 60;
// Minimum interval between backups. We try to not create more than one backup
// per interval.
const BOOKMARKS_BACKUP_MIN_INTERVAL_DAYS = 1;
// Maximum interval between backups. If the last backup is older than these
@@ -504,17 +504,17 @@ BrowserGlue.prototype = {
if (!win) {
return;
}
let brandBundle = win.document.getElementById("bundle_brand");
let brandShortName = brandBundle.getString("brandShortName");
let message = win.gNavigatorBundle.getFormattedString("addonwatch.slow", [addon.name, brandShortName]);
let notificationBox = win.document.getElementById("global-notificationbox");
- let notificationId = 'addon-slow:' + addonId;
+ let notificationId = "addon-slow:" + addonId;
let notification = notificationBox.getNotificationWithValue(notificationId);
// Monitor the response of users
const STATE_WARNING_DISPLAYED = 0;
const STATE_USER_PICKED_DISABLE = 1;
const STATE_USER_PICKED_IGNORE_FOR_NOW = 2;
const STATE_USER_PICKED_IGNORE_FOREVER = 3;
const STATE_USER_CLOSED_NOTIFICATION = 4;
--- a/browser/components/originattributes/test/browser/browser_cache.js
+++ b/browser/components/originattributes/test/browser/browser_cache.js
@@ -147,20 +147,20 @@ function* doTest(aBrowser) {
yield ContentTask.spawn(aBrowser, argObj, function* (arg) {
let videoURL = arg.urlPrefix + "file_thirdPartyChild.video.ogv";
let audioURL = arg.urlPrefix + "file_thirdPartyChild.audio.ogg";
let trackURL = arg.urlPrefix + "file_thirdPartyChild.track.vtt";
let URLSuffix = "?r=" + arg.randomSuffix;
// Create the audio and video elements.
- let audio = content.document.createElement('audio');
- let video = content.document.createElement('video');
- let audioSource = content.document.createElement('source');
- let audioTrack = content.document.createElement('track');
+ let audio = content.document.createElement("audio");
+ let video = content.document.createElement("video");
+ let audioSource = content.document.createElement("source");
+ let audioTrack = content.document.createElement("track");
// Append the audio and track element into the body, and wait until they're finished.
yield new Promise(resolve => {
let audioLoaded = false;
let trackLoaded = false;
let audioListener = () => {
audio.removeEventListener("canplaythrough", audioListener);
--- a/browser/components/originattributes/test/browser/browser_httpauth.js
+++ b/browser/components/originattributes/test/browser/browser_httpauth.js
@@ -1,17 +1,17 @@
let Cu = Components.utils;
let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
let server = new HttpServer();
-server.registerPathHandler('/file.html', fileHandler);
+server.registerPathHandler("/file.html", fileHandler);
server.start(-1);
-let BASE_URI = 'http://localhost:' + server.identity.primaryPort;
-let FILE_URI = BASE_URI + '/file.html';
+let BASE_URI = "http://localhost:" + server.identity.primaryPort;
+let FILE_URI = BASE_URI + "/file.html";
let credentialQueue = [];
// Ask the user agent for authorization.
function fileHandler(metadata, response) {
if (!metadata.hasHeader("Authorization")) {
response.setStatusLine(metadata.httpVersion, 401, "Unauthorized");
response.setHeader("WWW-Authenticate", "Basic realm=\"User Visible Realm\"");
--- a/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js
+++ b/browser/components/originattributes/test/browser/browser_imageCacheIsolation.js
@@ -8,32 +8,32 @@ let Cu = Components.utils;
let {HttpServer} = Cu.import("resource://testing-common/httpd.js", {});
const NUM_ISOLATION_LOADS = 2;
const NUM_CACHED_LOADS = 1;
let gHits = 0;
let server = new HttpServer();
-server.registerPathHandler('/image.png', imageHandler);
-server.registerPathHandler('/file.html', fileHandler);
+server.registerPathHandler("/image.png", imageHandler);
+server.registerPathHandler("/file.html", fileHandler);
server.start(-1);
registerCleanupFunction(() => {
server.stop(() => {
server = null;
});
});
-let BASE_URI = 'http://localhost:' + server.identity.primaryPort;
-let IMAGE_URI = BASE_URI + '/image.png';
-let FILE_URI = BASE_URI + '/file.html';
+let BASE_URI = "http://localhost:" + server.identity.primaryPort;
+let IMAGE_URI = BASE_URI + "/image.png";
+let FILE_URI = BASE_URI + "/file.html";
function imageHandler(metadata, response) {
- info('XXX: loading image from server');
+ info("XXX: loading image from server");
gHits++;
response.setHeader("Cache-Control", "max-age=10000", false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.setHeader("Content-Type", "image/png", false);
var body = "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAEUlEQVQImWP4z8AAQTAamQkAhpcI+DeMzFcAAAAASUVORK5CYII=";
response.bodyOutputStream.write(body, body.length);
}
@@ -41,25 +41,25 @@ function fileHandler(metadata, response)
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.setHeader("Content-Type", "text/html", false);
let body = `<html><body><image src=${IMAGE_URI}></body></html>`;
response.bodyOutputStream.write(body, body.length);
}
function doBefore() {
// reset hit counter
- info('XXX resetting gHits');
+ info("XXX resetting gHits");
gHits = 0;
- info('XXX clearing image cache');
+ info("XXX clearing image cache");
let imageCache = Cc["@mozilla.org/image/tools;1"]
.getService(Ci.imgITools)
.getImgCacheForDocument(null);
imageCache.clearCache(true);
imageCache.clearCache(false);
- info('XXX clearning network cache');
+ info("XXX clearning network cache");
let networkCache = Cc["@mozilla.org/netwerk/cache-storage-service;1"]
.getService(Ci.nsICacheStorageService);
networkCache.clear();
}
// the test function does nothing on purpose.
function doTest(aBrowser) {
return 0;
--- a/browser/components/originattributes/test/browser/head.js
+++ b/browser/components/originattributes/test/browser/head.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
const TEST_URL_PATH = "/browser/browser/components/originattributes/test/browser/";
// The flags of test modes.
const TEST_MODE_FIRSTPARTY = 0;
const TEST_MODE_NO_ISOLATION = 1;
const TEST_MODE_CONTAINERS = 2;
@@ -68,17 +68,17 @@ function* openTabInUserContext(aURL, aUs
*
* @return tab - The tab object of this tab.
* browser - The browser object of this tab.
*/
function* openTabInFirstParty(aURL, aFirstPartyDomain,
aFrameSetting = DEFAULT_FRAME_SETTING) {
// If the first party domain ends with '/', we remove it.
- if (aFirstPartyDomain.endsWith('/')) {
+ if (aFirstPartyDomain.endsWith("/")) {
aFirstPartyDomain = aFirstPartyDomain.slice(0, -1);
}
let basicPageURL = aFirstPartyDomain + gFirstPartyBasicPage;
// Open the tab for the basic first party page.
let tab = gBrowser.addTab(basicPageURL);
@@ -112,31 +112,31 @@ function* openTabInFirstParty(aURL, aFir
let numOfLayers = 0;
for (let type of arg.frames) {
let document = content.document;
numOfLayers++;
if (type === typeFrame) {
// Add a frameset which carries the frame element.
- let frameSet = document.createElement('frameset');
+ let frameSet = document.createElement("frameset");
frameSet.cols = "50%,50%";
- let frame = document.createElement('frame');
- let dummyFrame = document.createElement('frame');
+ let frame = document.createElement("frame");
+ let dummyFrame = document.createElement("frame");
frameSet.appendChild(frame);
frameSet.appendChild(dummyFrame);
document.body.appendChild(frameSet);
frameElement = frame;
} else if (type === typeIFrame) {
// Add an iframe.
- let iframe = document.createElement('iframe');
+ let iframe = document.createElement("iframe");
document.body.appendChild(iframe);
frameElement = iframe;
} else {
ok(false, "Invalid frame type.");
break;
}
--- a/browser/components/places/content/bookmarkProperties.js
+++ b/browser/components/places/content/bookmarkProperties.js
@@ -52,17 +52,17 @@
* - "tags"
* - "loadInSidebar"
* - "folderPicker" - hides both the tree and the menu.
*
* window.arguments[0].performed is set to true if any transaction has
* been performed by the dialog.
*/
-Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils",
"resource://gre/modules/PromiseUtils.jsm");
const BOOKMARK_ITEM = 0;
--- a/browser/components/places/content/bookmarksPanel.js
+++ b/browser/components/places/content/bookmarksPanel.js
@@ -4,17 +4,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function init() {
document.getElementById("bookmarks-view").place =
"place:queryType=1&folder=" + window.top.PlacesUIUtils.allBookmarksFolderId;
}
function searchBookmarks(aSearchString) {
- var tree = document.getElementById('bookmarks-view');
+ var tree = document.getElementById("bookmarks-view");
if (!aSearchString)
tree.place = tree.place;
else
tree.applyFilter(aSearchString,
[PlacesUtils.bookmarksMenuFolderId,
PlacesUtils.unfiledBookmarksFolderId,
PlacesUtils.toolbarFolderId]);
}
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -405,17 +405,17 @@ var PlacesOrganizer = {
* Populates the restore menu with the dates of the backups available.
*/
populateRestoreMenu: function PO_populateRestoreMenu() {
let restorePopup = document.getElementById("fileRestorePopup");
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric" };
let dateFormatter = new Intl.DateTimeFormat(locale, dtOptions);
// Remove existing menu items. Last item is the restoreFromFile item.
while (restorePopup.childNodes.length > 1)
restorePopup.removeChild(restorePopup.firstChild);
Task.spawn(function* () {
let backupFiles = yield PlacesBackups.getBackupFiles();
@@ -691,17 +691,17 @@ var PlacesOrganizer = {
// NOT YET USED
_updateThumbnail: function PO__updateThumbnail() {
var bo = document.getElementById("previewBox").boxObject;
var width = bo.width;
var height = bo.height;
var canvas = document.getElementById("itemThumbnail");
- var ctx = canvas.getContext('2d');
+ var ctx = canvas.getContext("2d");
var notAvailableText = canvas.getAttribute("notavailabletext");
ctx.save();
ctx.fillStyle = "-moz-Dialog";
ctx.fillRect(0, 0, width, height);
ctx.translate(width / 2, height / 2);
ctx.fillStyle = "GrayText";
ctx.mozTextStyle = "12pt sans serif";
--- a/browser/components/places/content/treeView.js
+++ b/browser/components/places/content/treeView.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
+Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const PTV_interfaces = [Ci.nsITreeView,
Ci.nsINavHistoryResultObserver,
Ci.nsINavHistoryResultTreeViewer,
Ci.nsISupportsWeakReference];
function PlacesTreeView(aFlatList, aOnOpenFlatContainer, aController) {
this._tree = null;
@@ -497,30 +497,30 @@ PlacesTreeView.prototype = {
// We use a different formatter for times within the current day,
// so we cache both a "today" formatter and a general date formatter.
__todayFormatter: null,
get _todayFormatter() {
if (!this.__todayFormatter) {
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { hour: 'numeric', minute: 'numeric' };
+ const dtOptions = { hour: "numeric", minute: "numeric" };
this.__todayFormatter = new Intl.DateTimeFormat(locale, dtOptions);
}
return this.__todayFormatter;
},
__dateFormatter: null,
get _dateFormatter() {
if (!this.__dateFormatter) {
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: '2-digit', month: 'numeric', day: 'numeric',
- hour: 'numeric', minute: 'numeric' };
+ const dtOptions = { year: "2-digit", month: "numeric", day: "numeric",
+ hour: "numeric", minute: "numeric" };
this.__dateFormatter = new Intl.DateTimeFormat(locale, dtOptions);
}
return this.__dateFormatter;
},
COLUMN_TYPE_UNKNOWN: 0,
COLUMN_TYPE_TITLE: 1,
COLUMN_TYPE_URI: 2,
--- a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
+++ b/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
@@ -88,17 +88,17 @@ add_task(function* () {
function focusTag(PlacesOrganizer) {
PlacesOrganizer.selectLeftPaneQuery("Tags");
let tags = PlacesOrganizer._places.selectedNode;
tags.containerOpen = true;
let fooTag = tags.getChild(0);
let tagNode = fooTag;
PlacesOrganizer._places.selectNode(fooTag);
- is(tagNode.title, 'foo', "tagNode title is foo");
+ is(tagNode.title, "foo", "tagNode title is foo");
let ip = PlacesOrganizer._places.insertionPoint;
ok(ip.isTag, "IP is a tag");
}
function copyHistNode(PlacesOrganizer, ContentTree) {
// focus the history object
PlacesOrganizer.selectLeftPaneQuery("History");
let histContainer = PlacesOrganizer._places.selectedNode;
--- a/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js
+++ b/browser/components/places/tests/browser/browser_bookmarkProperties_editTagContainer.js
@@ -21,17 +21,17 @@ add_task(function* () {
PlacesOrganizer.selectLeftPaneQuery("Tags");
let tree = PlacesOrganizer._places;
let tagsContainer = tree.selectedNode;
tagsContainer.containerOpen = true;
let fooTag = tagsContainer.getChild(0);
let tagNode = fooTag;
tree.selectNode(fooTag);
- is(tagNode.title, 'tag1', "tagNode title is correct");
+ is(tagNode.title, "tag1", "tagNode title is correct");
ok(tree.controller.isCommandEnabled("placesCmd_show:info"),
"'placesCmd_show:info' on current selected node is enabled");
yield withBookmarksDialog(
true,
function openDialog() {
tree.controller.doCommand("placesCmd_show:info");
--- a/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js
+++ b/browser/components/places/tests/browser/browser_bookmarklet_windowOpen.js
@@ -1,28 +1,28 @@
"use strict";
-const TEST_URL = 'http://example.com/browser/browser/components/places/tests/browser/pageopeningwindow.html';
+const TEST_URL = "http://example.com/browser/browser/components/places/tests/browser/pageopeningwindow.html";
function makeBookmarkFor(url, keyword) {
return Promise.all([
PlacesUtils.bookmarks.insert({ parentGuid: PlacesUtils.bookmarks.unfiledGuid,
title: "bookmarklet",
url }),
PlacesUtils.keywords.insert({url,
keyword})
]);
}
add_task(function* openKeywordBookmarkWithWindowOpen() {
// This is the current default, but let's not assume that...
yield SpecialPowers.pushPrefEnv({"set": [
- [ 'browser.link.open_newwindow', 3 ],
- [ 'dom.disable_open_during_load', true ]
+ [ "browser.link.open_newwindow", 3 ],
+ [ "dom.disable_open_during_load", true ]
]});
let moztab;
let tabOpened = BrowserTestUtils.openNewForegroundTab(gBrowser, "about:mozilla")
.then((tab) => { moztab = tab; });
let keywordForBM = "openmeatab";
let bookmarkInfo;
--- a/browser/components/places/tests/browser/browser_library_commands.js
+++ b/browser/components/places/tests/browser/browser_library_commands.js
@@ -19,17 +19,17 @@ add_task(function* test_date_container()
let library = yield promiseLibrary();
info("Ensure date containers under History cannot be cut but can be deleted");
yield PlacesTestUtils.addVisits(TEST_URI);
// Select and open the left pane "History" query.
let PO = library.PlacesOrganizer;
- PO.selectLeftPaneQuery('History');
+ PO.selectLeftPaneQuery("History");
isnot(PO._places.selectedNode, null, "We correctly selected History");
// Check that both delete and cut commands are disabled, cause this is
// a child of the left pane folder.
ok(PO._places.controller.isCommandEnabled("cmd_copy"),
"Copy command is enabled");
ok(!PO._places.controller.isCommandEnabled("cmd_cut"),
"Cut command is disabled");
@@ -76,17 +76,17 @@ add_task(function* test_date_container()
add_task(function* test_query_on_toolbar() {
let library = yield promiseLibrary();
info("Ensure queries can be cut or deleted");
// Select and open the left pane "Bookmarks Toolbar" folder.
let PO = library.PlacesOrganizer;
- PO.selectLeftPaneQuery('BookmarksToolbar');
+ PO.selectLeftPaneQuery("BookmarksToolbar");
isnot(PO._places.selectedNode, null, "We have a valid selection");
is(PlacesUtils.getConcreteItemId(PO._places.selectedNode),
PlacesUtils.toolbarFolderId,
"We have correctly selected bookmarks toolbar node.");
// Check that both cut and delete commands are disabled, cause this is a child
// of AllBookmarksFolderId.
ok(PO._places.controller.isCommandEnabled("cmd_copy"),
@@ -145,17 +145,17 @@ add_task(function* test_search_contents(
index: 0 });
let library = yield promiseLibrary();
info("Ensure query contents can be cut or deleted");
// Select and open the left pane "Bookmarks Toolbar" folder.
let PO = library.PlacesOrganizer;
- PO.selectLeftPaneQuery('BookmarksToolbar');
+ PO.selectLeftPaneQuery("BookmarksToolbar");
isnot(PO._places.selectedNode, null, "We have a valid selection");
is(PlacesUtils.getConcreteItemId(PO._places.selectedNode),
PlacesUtils.toolbarFolderId,
"We have correctly selected bookmarks toolbar node.");
let searchBox = library.document.getElementById("searchFilter");
searchBox.value = "example";
library.PlacesSearchBox.search(searchBox.value);
@@ -183,17 +183,17 @@ add_task(function* test_tags() {
PlacesUtils.tagging.tagURI(NetUtil.newURI("http://example.com/"), ["test"]);
let library = yield promiseLibrary();
info("Ensure query contents can be cut or deleted");
// Select and open the left pane "Bookmarks Toolbar" folder.
let PO = library.PlacesOrganizer;
- PO.selectLeftPaneQuery('Tags');
+ PO.selectLeftPaneQuery("Tags");
let tagsNode = PO._places.selectedNode;
isnot(tagsNode, null, "We have a valid selection");
let tagsTitle = PlacesUtils.getString("TagsFolderTitle");
is(tagsNode.title, tagsTitle,
"Tags has been properly selected");
// Check that both cut and delete commands are disabled.
ok(PO._places.controller.isCommandEnabled("cmd_copy"),
--- a/browser/components/places/tests/browser/browser_library_panel_leak.js
+++ b/browser/components/places/tests/browser/browser_library_panel_leak.js
@@ -24,17 +24,17 @@ function test() {
isnot(contentTree, null, "Sanity check: placeContent tree should exist");
isnot(organizer.PlacesOrganizer, null, "Sanity check: PlacesOrganizer should exist");
isnot(organizer.gEditItemOverlay, null, "Sanity check: gEditItemOverlay should exist");
ok(organizer.gEditItemOverlay.initialized, "gEditItemOverlay is initialized");
isnot(organizer.gEditItemOverlay.itemId, -1, "Editing a bookmark");
// Select History in the left pane.
- organizer.PlacesOrganizer.selectLeftPaneQuery('History');
+ organizer.PlacesOrganizer.selectLeftPaneQuery("History");
// Select the first history entry.
let selection = contentTree.view.selection;
selection.clearSelection();
selection.rangedSelect(0, 0, true);
// Check the panel is editing the history entry.
is(organizer.gEditItemOverlay.itemId, -1, "Editing an history entry");
// Close Library window.
organizer.close();
--- a/browser/components/preferences/connection.js
+++ b/browser/components/preferences/connection.js
@@ -174,19 +174,19 @@ var gConnectionsDialog = {
autoURLPref.value = autoURL.value = URIFixup.createFixupURI(autoURL.value, 0).spec;
} catch (ex) {}
},
sanitizeNoProxiesPref() {
var noProxiesPref = document.getElementById("network.proxy.no_proxies_on");
// replace substrings of ; and \n with commas if they're neither immediately
// preceded nor followed by a valid separator character
- noProxiesPref.value = noProxiesPref.value.replace(/([^, \n;])[;\n]+(?![,\n;])/g, '$1,');
+ noProxiesPref.value = noProxiesPref.value.replace(/([^, \n;])[;\n]+(?![,\n;])/g, "$1,");
// replace any remaining ; and \n since some may follow commas, etc.
- noProxiesPref.value = noProxiesPref.value.replace(/[;\n]/g, '');
+ noProxiesPref.value = noProxiesPref.value.replace(/[;\n]/g, "");
},
readHTTPProxyServer() {
var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
if (shareProxiesPref.value)
this.updateProtocolPrefs();
return undefined;
},
--- a/browser/components/preferences/containers.js
+++ b/browser/components/preferences/containers.js
@@ -100,17 +100,17 @@ let gContainersManager = {
if (this.identity.icon && this.identity.icon == icon) {
iconSwatch.setAttribute("selected", true);
}
iconSwatch.setAttribute("label",
containersBundle.GetStringFromName(`containers.${icon}.label`));
let iconElement = document.createElement("hbox");
- iconElement.className = 'userContext-icon';
+ iconElement.className = "userContext-icon";
iconElement.setAttribute("data-identity-icon", icon);
iconSwatch.appendChild(iconElement);
radiogroup.appendChild(iconSwatch);
}
return radiogroup;
},
@@ -129,17 +129,17 @@ let gContainersManager = {
if (this.identity.color && this.identity.color == color) {
colorSwatch.setAttribute("selected", true);
}
colorSwatch.setAttribute("label",
containersBundle.GetStringFromName(`containers.${color}.label`));
let iconElement = document.createElement("hbox");
- iconElement.className = 'userContext-icon';
+ iconElement.className = "userContext-icon";
iconElement.setAttribute("data-identity-icon", "circle");
iconElement.setAttribute("data-identity-color", color);
colorSwatch.appendChild(iconElement);
radiogroup.appendChild(colorSwatch);
}
return radiogroup;
},
--- a/browser/components/preferences/cookies.js
+++ b/browser/components/preferences/cookies.js
@@ -211,28 +211,28 @@ var gCookiesWindow = {
return this._filterSet[aIndex];
var start = 0;
var count = 0, hostIndex = 0;
var cacheIndex = Math.min(this._cacheValid, aIndex);
if (cacheIndex > 0) {
var cacheItem = this._cacheItems[cacheIndex];
- start = cacheItem['start'];
- count = hostIndex = cacheItem['count'];
+ start = cacheItem["start"];
+ count = hostIndex = cacheItem["count"];
}
for (let i = start; i < gCookiesWindow._hostOrder.length; ++i) { // var host in gCookiesWindow._hosts) {
let currHost = gCookiesWindow._hosts[gCookiesWindow._hostOrder[i]];// gCookiesWindow._hosts[host];
if (!currHost) continue;
if (count == aIndex)
return currHost;
hostIndex = count;
- var cacheEntry = { 'start' : i, 'count' : count };
+ var cacheEntry = { "start" : i, "count" : count };
var cacheStart = count;
if (currHost.open) {
if (count < aIndex && aIndex <= (count + currHost.cookies.length)) {
// We are looking for an entry within this host's children,
// enumerate them looking for the index.
++count;
for (let cookie of currHost.cookies) {
@@ -497,18 +497,18 @@ var gCookiesWindow = {
},
formatExpiresString(aExpires) {
if (aExpires) {
var date = new Date(1000 * aExpires);
const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
.getService(Components.interfaces.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric',
- hour: 'numeric', minute: 'numeric', second: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric",
+ hour: "numeric", minute: "numeric", second: "numeric" };
return date.toLocaleString(locale, dtOptions);
}
return this._bundle.getString("expireAtEndOfSession");
},
_getUserContextString(aUserContextId) {
if (parseInt(aUserContextId) == 0) {
return this._bundle.getString("defaultUserContextLabel");
--- a/browser/components/preferences/in-content/applications.js
+++ b/browser/components/preferences/in-content/applications.js
@@ -1,18 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Constants & Enumeration Values
-Components.utils.import('resource://gre/modules/Services.jsm');
-Components.utils.import('resource://gre/modules/AppConstants.jsm');
+Components.utils.import("resource://gre/modules/Services.jsm");
+Components.utils.import("resource://gre/modules/AppConstants.jsm");
const TYPE_MAYBE_FEED = "application/vnd.mozilla.maybe.feed";
const TYPE_MAYBE_VIDEO_FEED = "application/vnd.mozilla.maybe.video.feed";
const TYPE_MAYBE_AUDIO_FEED = "application/vnd.mozilla.maybe.audio.feed";
const TYPE_PDF = "application/pdf";
const PREF_PDFJS_DISABLED = "pdfjs.disabled";
const TOPIC_PDFJS_HANDLER_CHANGED = "pdfjs:handlerChanged";
--- a/browser/components/preferences/in-content/preferences.js
+++ b/browser/components/preferences/in-content/preferences.js
@@ -81,18 +81,18 @@ function init_all() {
});
window.addEventListener("hashchange", onHashChange);
gotoPref();
init_dynamic_padding();
var initFinished = new CustomEvent("Initialized", {
- 'bubbles': true,
- 'cancelable': true
+ "bubbles": true,
+ "cancelable": true
});
document.dispatchEvent(initFinished);
categories = categories.querySelectorAll("richlistitem.category");
for (let category of categories) {
let name = internalPrefCategoryNameToFriendlyName(category.value);
let helpSelector = `#header-${name} > .help-button`;
let helpButton = document.querySelector(helpSelector);
@@ -103,27 +103,27 @@ function init_all() {
// notifying observers that the UI is now ready.
Services.obs.notifyObservers(window, "advanced-pane-loaded", null);
}
// Make the space above the categories list shrink on low window heights
function init_dynamic_padding() {
let categories = document.getElementById("categories");
let catPadding = Number.parseInt(getComputedStyle(categories)
- .getPropertyValue('padding-top'));
+ .getPropertyValue("padding-top"));
let fullHeight = categories.lastElementChild.getBoundingClientRect().bottom;
let mediaRule = `
@media (max-height: ${fullHeight}px) {
#categories {
padding-top: calc(100vh - ${fullHeight - catPadding}px);
}
}
`;
- let mediaStyle = document.createElementNS('http://www.w3.org/1999/xhtml', 'html:style');
- mediaStyle.setAttribute('type', 'text/css');
+ let mediaStyle = document.createElementNS("http://www.w3.org/1999/xhtml", "html:style");
+ mediaStyle.setAttribute("type", "text/css");
mediaStyle.appendChild(document.createCDATASection(mediaRule));
document.documentElement.appendChild(mediaStyle);
}
function telemetryBucketForCategory(category) {
switch (category) {
case "general":
case "search":
--- a/browser/components/preferences/in-content/privacy.js
+++ b/browser/components/preferences/in-content/privacy.js
@@ -405,57 +405,57 @@ var gPrivacyPane = {
/**
* Initialize the starting state for the auto-start private browsing mode pref reverter.
*/
initAutoStartPrivateBrowsingReverter() {
let mode = document.getElementById("historyMode");
let autoStart = document.getElementById("privateBrowsingAutoStart");
this._lastMode = mode.selectedIndex;
- this._lastCheckState = autoStart.hasAttribute('checked');
+ this._lastCheckState = autoStart.hasAttribute("checked");
},
_lastMode: null,
_lastCheckState: null,
updateAutostart() {
let mode = document.getElementById("historyMode");
let autoStart = document.getElementById("privateBrowsingAutoStart");
let pref = document.getElementById("browser.privatebrowsing.autostart");
if ((mode.value == "custom" && this._lastCheckState == autoStart.checked) ||
(mode.value == "remember" && !this._lastCheckState) ||
(mode.value == "dontremember" && this._lastCheckState)) {
// These are all no-op changes, so we don't need to prompt.
this._lastMode = mode.selectedIndex;
- this._lastCheckState = autoStart.hasAttribute('checked');
+ this._lastCheckState = autoStart.hasAttribute("checked");
return;
}
if (!this._shouldPromptForRestart) {
// We're performing a revert. Just let it happen.
return;
}
let buttonIndex = confirmRestartPrompt(autoStart.checked, 1,
true, false);
if (buttonIndex == CONFIRM_RESTART_PROMPT_RESTART_NOW) {
- pref.value = autoStart.hasAttribute('checked');
+ pref.value = autoStart.hasAttribute("checked");
let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]
.getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart);
return;
}
this._shouldPromptForRestart = false;
if (this._lastCheckState) {
autoStart.checked = "checked";
} else {
- autoStart.removeAttribute('checked');
+ autoStart.removeAttribute("checked");
}
- pref.value = autoStart.hasAttribute('checked');
+ pref.value = autoStart.hasAttribute("checked");
mode.selectedIndex = this._lastMode;
mode.doCommand();
this._shouldPromptForRestart = true;
},
/**
* Displays fine-grained, per-site preferences for tracking protection.
--- a/browser/components/preferences/in-content/search.js
+++ b/browser/components/preferences/in-content/search.js
@@ -23,17 +23,17 @@ var gSearchPane = {
},
init() {
gEngineView = new EngineView(new EngineStore());
document.getElementById("engineList").view = gEngineView;
this.buildDefaultEngineDropDown();
let addEnginesLink = document.getElementById("addEngines");
- let searchEnginesURL = Services.wm.getMostRecentWindow('navigator:browser')
+ let searchEnginesURL = Services.wm.getMostRecentWindow("navigator:browser")
.BrowserSearch.searchEnginesURL;
addEnginesLink.setAttribute("href", searchEnginesURL);
window.addEventListener("click", this);
window.addEventListener("command", this);
window.addEventListener("dragstart", this);
window.addEventListener("keypress", this);
window.addEventListener("select", this);
--- a/browser/components/preferences/in-content/subdialogs.js
+++ b/browser/components/preferences/in-content/subdialogs.js
@@ -29,17 +29,17 @@ var gSubDialog = {
updateTitle(aEvent) {
if (aEvent.target != gSubDialog._frame.contentDocument)
return;
document.getElementById("dialogTitle").textContent = gSubDialog._frame.contentDocument.title;
},
injectXMLStylesheet(aStylesheetURL) {
let contentStylesheet = this._frame.contentDocument.createProcessingInstruction(
- 'xml-stylesheet',
+ "xml-stylesheet",
'href="' + aStylesheetURL + '" type="text/css"'
);
this._frame.contentDocument.insertBefore(contentStylesheet,
this._frame.contentDocument.documentElement);
},
open(aURL, aFeatures = null, aParams = null, aClosingCallback = null) {
// If we're already open/opening on this URL, do nothing.
@@ -266,17 +266,17 @@ var gSubDialog = {
"Please consider changing this.");
comparisonFrameHeight = parseFloat(frameHeight);
}
if (comparisonFrameHeight > maxHeight) {
// If the height is bigger than that of the window, we should let the contents scroll:
frameHeight = maxHeight + "px";
frameMinHeight = maxHeight + "px";
- let containers = this._frame.contentDocument.querySelectorAll('.largeDialogContainer');
+ let containers = this._frame.contentDocument.querySelectorAll(".largeDialogContainer");
for (let container of containers) {
container.classList.add("doScroll");
}
}
this._frame.style.height = frameHeight;
this._box.style.minHeight = "calc(" +
(boxVerticalBorder + groupBoxTitleHeight + boxVerticalPadding) +
--- a/browser/components/preferences/in-content/sync.js
+++ b/browser/components/preferences/in-content/sync.js
@@ -126,21 +126,21 @@ var gSyncPane = {
}, this);
window.addEventListener("unload", function() {
topics.forEach(function(topic) {
Weave.Svc.Obs.remove(topic, this.updateWeavePrefs, this);
}, gSyncPane);
});
- XPCOMUtils.defineLazyGetter(this, '_stringBundle', () => {
+ XPCOMUtils.defineLazyGetter(this, "_stringBundle", () => {
return Services.strings.createBundle("chrome://browser/locale/preferences/preferences.properties");
});
- XPCOMUtils.defineLazyGetter(this, '_accountsStringBundle', () => {
+ XPCOMUtils.defineLazyGetter(this, "_accountsStringBundle", () => {
return Services.strings.createBundle("chrome://browser/locale/accounts.properties");
});
let url = Services.prefs.getCharPref("identity.mobilepromo.android") + "sync-preferences";
document.getElementById("fxaMobilePromo-android").setAttribute("href", url);
document.getElementById("fxaMobilePromo-android-hasFxaAccount").setAttribute("href", url);
url = Services.prefs.getCharPref("identity.mobilepromo.ios") + "sync-preferences";
document.getElementById("fxaMobilePromo-ios").setAttribute("href", url);
@@ -201,17 +201,17 @@ var gSyncPane = {
}
setEventListener("noAccountSetup", "click", function(aEvent) {
aEvent.stopPropagation();
gSyncPane.openSetup(null);
});
setEventListener("noAccountPair", "click", function(aEvent) {
aEvent.stopPropagation();
- gSyncPane.openSetup('pair');
+ gSyncPane.openSetup("pair");
});
setEventListener("syncChangePassword", "command",
() => gSyncUtils.changePassword());
setEventListener("syncResetPassphrase", "command",
() => gSyncUtils.resetPassphrase());
setEventListener("syncReset", "command", gSyncPane.resetSync);
setEventListener("syncAddDeviceLabel", "click", function() {
gSyncPane.openAddDevice();
--- a/browser/components/preferences/in-content/tests/browser_advanced_siteData.js
+++ b/browser/components/preferences/in-content/tests/browser_advanced_siteData.js
@@ -1,16 +1,16 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
/* import-globals-from ../../../../../testing/modules/sinon-1.16.1.js */
Services.scriptloader.loadSubScript("resource://testing-common/sinon-1.16.1.js");
const TEST_HOST = "example.com";
const TEST_ORIGIN = "http://" + TEST_HOST;
const TEST_BASE_URL = TEST_ORIGIN + "/browser/browser/components/preferences/in-content/tests/";
const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {});
--- a/browser/components/preferences/in-content/tests/browser_advanced_update.js
+++ b/browser/components/preferences/in-content/tests/browser_advanced_update.js
@@ -1,16 +1,16 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
const { classes: Cc, interfaces: Ci, manager: Cm, utils: Cu, results: Cr } = Components;
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
const mockUpdateManager = {
contractId: "@mozilla.org/updates/update-manager;1",
_mockClassId: uuidGenerator.generateUUID(),
@@ -83,18 +83,18 @@ function resetPreferences() {
Services.prefs.clearUserPref("browser.search.update");
}
function formatInstallDate(sec) {
var date = new Date(sec);
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric',
- hour: 'numeric', minute: 'numeric', second: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric",
+ hour: "numeric", minute: "numeric", second: "numeric" };
return date.toLocaleString(locale, dtOptions);
}
registerCleanupFunction(resetPreferences);
add_task(function*() {
yield openPreferencesViaOpenPreferencesAPI("advanced", "updateTab", { leaveOpen: true });
resetPreferences();
--- a/browser/components/preferences/in-content/tests/browser_bug410900.js
+++ b/browser/components/preferences/in-content/tests/browser_bug410900.js
@@ -31,16 +31,16 @@ function runTest(win) {
var rbox = win.document.getElementById("handlersView");
ok(rbox, "handlersView is present");
var items = rbox && rbox.getElementsByTagName("richlistitem");
ok(items && items.length > 0, "App handler list populated");
var handlerAdded = false;
for (let i = 0; i < items.length; i++) {
- if (items[i].getAttribute('type') == "apppanetest")
+ if (items[i].getAttribute("type") == "apppanetest")
handlerAdded = true;
}
ok(handlerAdded, "apppanetest protocol handler was successfully added");
gBrowser.removeCurrentTab();
finish();
}
--- a/browser/components/preferences/in-content/tests/browser_privacypane_1.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_1.js
@@ -1,16 +1,16 @@
let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let rootDir = getRootDirectory(gTestPath);
let jar = getJar(rootDir);
if (jar) {
let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
+ rootDir = "file://" + tmpdir.path + "/";
}
/* import-globals-from privacypane_tests_perwindow.js */
loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
run_test_subset([
test_pane_visibility,
test_dependent_elements,
test_dependent_cookie_elements,
--- a/browser/components/preferences/in-content/tests/browser_privacypane_3.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_3.js
@@ -1,15 +1,15 @@
let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let rootDir = getRootDirectory(gTestPath);
let jar = getJar(rootDir);
if (jar) {
let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
+ rootDir = "file://" + tmpdir.path + "/";
}
/* import-globals-from privacypane_tests_perwindow.js */
loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
run_test_subset([
test_custom_retention("rememberHistory", "remember"),
test_custom_retention("rememberHistory", "custom"),
test_custom_retention("rememberForms", "custom"),
--- a/browser/components/preferences/in-content/tests/browser_privacypane_4.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_4.js
@@ -1,17 +1,17 @@
requestLongerTimeout(2);
let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let rootDir = getRootDirectory(gTestPath);
let jar = getJar(rootDir);
if (jar) {
let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
+ rootDir = "file://" + tmpdir.path + "/";
}
/* import-globals-from privacypane_tests_perwindow.js */
loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
run_test_subset([
test_custom_retention("acceptCookies", "remember"),
test_custom_retention("acceptCookies", "custom"),
--- a/browser/components/preferences/in-content/tests/browser_privacypane_5.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_5.js
@@ -1,15 +1,15 @@
let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let rootDir = getRootDirectory(gTestPath);
let jar = getJar(rootDir);
if (jar) {
let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
+ rootDir = "file://" + tmpdir.path + "/";
}
/* import-globals-from privacypane_tests_perwindow.js */
loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
run_test_subset([
test_locbar_suggestion_retention("history", true),
test_locbar_suggestion_retention("bookmark", true),
test_locbar_suggestion_retention("openpage", false),
--- a/browser/components/preferences/in-content/tests/browser_privacypane_8.js
+++ b/browser/components/preferences/in-content/tests/browser_privacypane_8.js
@@ -1,15 +1,15 @@
let loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let rootDir = getRootDirectory(gTestPath);
let jar = getJar(rootDir);
if (jar) {
let tmpdir = extractJarToTmp(jar);
- rootDir = "file://" + tmpdir.path + '/';
+ rootDir = "file://" + tmpdir.path + "/";
}
/* import-globals-from privacypane_tests_perwindow.js */
loader.loadSubScript(rootDir + "privacypane_tests_perwindow.js", this);
run_test_subset([
// history mode should be initialized to remember
test_historymode_retention("remember", undefined),
--- a/browser/components/preferences/in-content/tests/browser_subdialogs.js
+++ b/browser/components/preferences/in-content/tests/browser_subdialogs.js
@@ -247,17 +247,17 @@ add_task(function* wrapped_text_in_dialo
yield close_subdialog_and_test_generic_end_state(tab.linkedBrowser,
function() { content.window.gSubDialog._frame.contentWindow.window.close(); },
null, 0);
});
add_task(function* dialog_too_tall_should_get_reduced_in_height() {
yield open_subdialog_and_test_generic_start_state(tab.linkedBrowser, function domcontentloadedFn() {
let frame = content.window.gSubDialog._frame;
- frame.contentDocument.documentElement.style.height = '100000px';
+ frame.contentDocument.documentElement.style.height = "100000px";
});
yield ContentTask.spawn(tab.linkedBrowser, null, function*() {
let frame = content.window.gSubDialog._frame;
Assert.equal(frame.style.width, "32em", "Width should be set on the frame from the dialog");
Assert.ok(parseInt(frame.style.height, 10) < content.window.innerHeight,
"Height on the frame should be smaller than window's innerHeight");
});
--- a/browser/components/search/test/browser_contextmenu.js
+++ b/browser/components/search/test/browser_contextmenu.js
@@ -71,17 +71,17 @@ add_task(function* () {
let popupPromise = BrowserTestUtils.waitForEvent(contextMenu, "popupshown");
BrowserTestUtils.synthesizeMouseAtCenter("body", eventDetails, gBrowser.selectedBrowser);
yield popupPromise;
info("checkContextMenu");
var searchItem = contextMenu.getElementsByAttribute("id", "context-searchselect")[0];
ok(searchItem, "Got search context menu item");
- is(searchItem.label, 'Search ' + ENGINE_NAME + ' for \u201ctest search\u201d', "Check context menu label");
+ is(searchItem.label, "Search " + ENGINE_NAME + " for \u201ctest search\u201d", "Check context menu label");
is(searchItem.disabled, false, "Check that search context menu item is enabled");
yield BrowserTestUtils.openNewForegroundTab(gBrowser, () => {
searchItem.click();
});
is(gBrowser.currentURI.spec,
"http://mochi.test:8888/browser/browser/components/search/test/?test=test+search&ie=utf-8&channel=contextsearch",
--- a/browser/components/search/test/head.js
+++ b/browser/components/search/test/head.js
@@ -4,17 +4,17 @@
Cu.import("resource://gre/modules/Promise.jsm");
/**
* Recursively compare two objects and check that every property of expectedObj has the same value
* on actualObj.
*/
function isSubObjectOf(expectedObj, actualObj, name) {
for (let prop in expectedObj) {
- if (typeof expectedObj[prop] == 'function')
+ if (typeof expectedObj[prop] == "function")
continue;
if (expectedObj[prop] instanceof Object) {
is(actualObj[prop].length, expectedObj[prop].length, name + "[" + prop + "]");
isSubObjectOf(expectedObj[prop], actualObj[prop], name + "[" + prop + "]");
} else {
is(actualObj[prop], expectedObj[prop], name + "[" + prop + "]");
}
}
--- a/browser/components/syncedtabs/TabListView.js
+++ b/browser/components/syncedtabs/TabListView.js
@@ -112,17 +112,17 @@ TabListView.prototype = {
this._updateSearchBox(state);
for (let client of state.clients) {
let clientNode = this._doc.getElementById("item-" + client.id);
if (clientNode) {
this._updateClient(client, clientNode);
}
client.tabs.forEach((tab, index) => {
- let tabNode = this._doc.getElementById('tab-' + client.id + '-' + index);
+ let tabNode = this._doc.getElementById("tab-" + client.id + "-" + index);
this._updateTab(tab, tabNode, index);
});
}
},
// Client rows are hidden when the list is filtered
_renderFilteredClient(client, filter) {
client.tabs.forEach((tab, index) => {
@@ -240,17 +240,17 @@ TabListView.prototype = {
/**
* Update the element representing a tab, ensuring it's in sync with the
* underlying data.
* @param {tab} item - Item to use as a source.
* @param {Element} itemNode - Element to update.
*/
_updateTab(item, itemNode, index) {
itemNode.setAttribute("title", `${item.title}\n${item.url}`);
- itemNode.setAttribute("id", "tab-" + item.client + '-' + index);
+ itemNode.setAttribute("id", "tab-" + item.client + "-" + index);
if (item.selected) {
itemNode.classList.add("selected");
} else {
itemNode.classList.remove("selected");
}
if (item.focused) {
itemNode.focus();
}
@@ -308,17 +308,17 @@ TabListView.prototype = {
onKeyDown(event) {
if (event.keyCode == this._window.KeyEvent.DOM_VK_DOWN) {
event.preventDefault();
this.props.onMoveSelectionDown();
} else if (event.keyCode == this._window.KeyEvent.DOM_VK_UP) {
event.preventDefault();
this.props.onMoveSelectionUp();
} else if (event.keyCode == this._window.KeyEvent.DOM_VK_RETURN) {
- let selectedNode = this.container.querySelector('.item.selected');
+ let selectedNode = this.container.querySelector(".item.selected");
if (selectedNode.dataset.url) {
this.onOpenSelected(selectedNode.dataset.url, event);
} else if (selectedNode) {
this.props.onToggleBranch(selectedNode.dataset.id);
}
}
},
@@ -376,25 +376,25 @@ TabListView.prototype = {
onFilterFocus() {
this.props.onFilterFocus();
},
onFilterBlur() {
this.props.onFilterBlur();
},
_getSelectedTabNode() {
- let item = this.container.querySelector('.item.selected');
+ let item = this.container.querySelector(".item.selected");
if (this._isTab(item) && item.dataset.url) {
return item;
}
return null;
},
_getSelectedClientNode() {
- let item = this.container.querySelector('.item.selected');
+ let item = this.container.querySelector(".item.selected");
if (this._isClient(item)) {
return item;
}
return null;
},
// Set up the custom context menu
_setupContextMenu() {
@@ -511,17 +511,17 @@ TabListView.prototype = {
menu = getContextMenu(this._window);
this.adjustContextMenu(menu);
}
menu.openPopupAtScreen(event.screenX, event.screenY, true, event);
},
adjustContextMenu(menu) {
- let item = this.container.querySelector('.item.selected');
+ let item = this.container.querySelector(".item.selected");
let showTabOptions = this._isTab(item);
let el = menu.firstChild;
while (el) {
let show = false;
if (showTabOptions) {
if (el.getAttribute("id") != "syncedTabsOpenAllInTabs") {
--- a/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
+++ b/browser/components/syncedtabs/test/browser/browser_sidebar_syncedtabslist.js
@@ -73,17 +73,17 @@ function* testClean() {
window.SidebarUI.browser.contentWindow.removeEventListener("unload", listener);
resolve();
});
SidebarUI.hide();
});
}
add_task(function* testSyncedTabsSidebarList() {
- yield SidebarUI.show('viewTabsSidebar');
+ yield SidebarUI.show("viewTabsSidebar");
Assert.equal(SidebarUI.currentID, "viewTabsSidebar", "Sidebar should have SyncedTabs loaded");
let syncedTabsDeckComponent = SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
let SyncedTabs = SidebarUI.browser.contentWindow.SyncedTabs;
Assert.ok(syncedTabsDeckComponent, "component exists");
@@ -129,17 +129,17 @@ add_task(function* testSyncedTabsSidebar
});
});
});
add_task(testClean);
add_task(function* testSyncedTabsSidebarFilteredList() {
- yield SidebarUI.show('viewTabsSidebar');
+ yield SidebarUI.show("viewTabsSidebar");
let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
Assert.ok(syncedTabsDeckComponent, "component exists");
originalSyncedTabsInternal = SyncedTabs._internal;
SyncedTabs._internal = {
isConfiguredToSyncTabs: true,
@@ -190,17 +190,17 @@ add_task(function* testSyncedTabsSidebar
});
});
add_task(testClean);
add_task(function* testSyncedTabsSidebarStatus() {
let accountExists = false;
- yield SidebarUI.show('viewTabsSidebar');
+ yield SidebarUI.show("viewTabsSidebar");
let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
originalSyncedTabsInternal = SyncedTabs._internal;
SyncedTabs._internal = {
isConfiguredToSyncTabs: false,
hasSyncedThisSession: false,
getTabClients() {},
@@ -251,17 +251,17 @@ add_task(function* testSyncedTabsSidebar
selectedPanel = syncedTabsDeckComponent.container.querySelector(".sync-state.selected");
Assert.ok(selectedPanel.classList.contains("tabs-container"),
"tabs panel is selected");
});
add_task(testClean);
add_task(function* testSyncedTabsSidebarContextMenu() {
- yield SidebarUI.show('viewTabsSidebar');
+ yield SidebarUI.show("viewTabsSidebar");
let syncedTabsDeckComponent = window.SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
let SyncedTabs = window.SidebarUI.browser.contentWindow.SyncedTabs;
Assert.ok(syncedTabsDeckComponent, "component exists");
originalSyncedTabsInternal = SyncedTabs._internal;
SyncedTabs._internal = {
isConfiguredToSyncTabs: true,
--- a/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js
+++ b/browser/components/syncedtabs/test/xpcshell/test_TabListComponent.js
@@ -22,18 +22,18 @@ const ACTION_METHODS = [
add_task(function* testInitUninit() {
let store = new SyncedTabsListStore();
let ViewMock = sinon.stub();
let view = {render() {}, destroy() {}};
ViewMock.returns(view);
- sinon.spy(view, 'render');
- sinon.spy(view, 'destroy');
+ sinon.spy(view, "render");
+ sinon.spy(view, "destroy");
sinon.spy(store, "on");
sinon.stub(store, "getData");
sinon.stub(store, "focusInput");
let component = new TabListComponent({window, store, View: ViewMock, SyncedTabs});
for (let action of ACTION_METHODS) {
--- a/browser/components/tests/browser/browser_bug538331.js
+++ b/browser/components/tests/browser/browser_bug538331.js
@@ -113,17 +113,17 @@ this.__defineGetter__("gBG", function()
getService(Ci.nsIObserver);
});
function test() {
waitForExplicitFinish();
// Reset the startup page pref since it may have been set by other tests
// and we will assume it is default.
- Services.prefs.clearUserPref('browser.startup.page');
+ Services.prefs.clearUserPref("browser.startup.page");
if (gPrefService.prefHasUserValue(PREF_MSTONE)) {
gOriginalMStone = gPrefService.getCharPref(PREF_MSTONE);
}
if (gPrefService.prefHasUserValue(PREF_OVERRIDE_URL)) {
gOriginalOverrideURL = gPrefService.getCharPref(PREF_OVERRIDE_URL);
}
--- a/browser/components/translation/BingTranslator.jsm
+++ b/browser/components/translation/BingTranslator.jsm
@@ -295,33 +295,33 @@ BingRequest.prototype = {
let url = getUrlParam("https://api.microsofttranslator.com/v2/Http.svc/TranslateArray",
"browser.translation.bing.translateArrayURL");
// Prepare request headers.
let headers = [["Content-type", "text/xml"], ["Authorization", auth]];
// Prepare the request body.
let requestString =
- '<TranslateArrayRequest>' +
- '<AppId/>' +
- '<From>' + this.sourceLanguage + '</From>' +
- '<Options>' +
+ "<TranslateArrayRequest>" +
+ "<AppId/>" +
+ "<From>" + this.sourceLanguage + "</From>" +
+ "<Options>" +
'<ContentType xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2">text/html</ContentType>' +
'<ReservedFlags xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" />' +
- '</Options>' +
+ "</Options>" +
'<Texts xmlns:s="http://schemas.microsoft.com/2003/10/Serialization/Arrays">';
for (let [, text] of this.translationData) {
- requestString += '<s:string>' + text + '</s:string>';
+ requestString += "<s:string>" + text + "</s:string>";
this.characterCount += text.length;
}
- requestString += '</Texts>' +
- '<To>' + this.targetLanguage + '</To>' +
- '</TranslateArrayRequest>';
+ requestString += "</Texts>" +
+ "<To>" + this.targetLanguage + "</To>" +
+ "</TranslateArrayRequest>";
// Set up request options.
let deferred = Promise.defer();
let options = {
onLoad: (function(responseText, xhr) {
deferred.resolve(this);
}).bind(this),
onError(e, responseText, xhr) {
--- a/browser/components/translation/TranslationDocument.jsm
+++ b/browser/components/translation/TranslationDocument.jsm
@@ -170,17 +170,17 @@ this.TranslationDocument.prototype = {
// Otherwise, if this node doesn't contain any useful content,
// or if it is a root itself, we can replace it with a placeholder node.
// We can't simply eliminate this node from our string representation
// because that could change the HTML structure (e.g., it would
// probably merge two separate text nodes).
// It's not necessary to add more than one placeholder in sequence;
// we can optimize them away.
item.original.push(TranslationItem_NodePlaceholder);
- str += '<br>';
+ str += "<br>";
wasLastItemPlaceholder = true;
}
}
return generateTranslationHtmlForItem(item, str);
},
/**
@@ -363,17 +363,17 @@ const TranslationItem_NodePlaceholder =
*
* @param item A TranslationItem object.
* param content The inner content for this item.
* @returns string The outer HTML needed for translation
* of this item.
*/
function generateTranslationHtmlForItem(item, content) {
let localName = item.isRoot ? "div" : "b";
- return '<' + localName + ' id=n' + item.id + '>' +
+ return "<" + localName + " id=n" + item.id + ">" +
content +
"</" + localName + ">";
}
/**
* Regenerate the text string that represents a TranslationItem object,
* with data from its "original" array. The array must have already
* been created by TranslationDocument.generateTextForItem().
--- a/browser/components/translation/cld2/post.js
+++ b/browser/components/translation/cld2/post.js
@@ -10,162 +10,162 @@ LanguageInfo.detectLanguage = LanguageIn
// Closure is overzealous in its function call optimization, and tries
// to turn these singleton methods into unbound function calls.
ensureCache.alloc = ensureCache.alloc.bind(ensureCache);
ensureCache.prepare = ensureCache.prepare.bind(ensureCache);
// From public/encodings.h. Unfortunately, the WebIDL binder doesn't
// allow us to define or automatically derive these in the IDL.
var Encodings = {
- 'ISO_8859_1' : 0,
- 'ISO_8859_2' : 1,
- 'ISO_8859_3' : 2,
- 'ISO_8859_4' : 3,
- 'ISO_8859_5' : 4,
- 'ISO_8859_6' : 5,
- 'ISO_8859_7' : 6,
- 'ISO_8859_8' : 7,
- 'ISO_8859_9' : 8,
- 'ISO_8859_10' : 9,
- 'JAPANESE_EUC_JP' : 10,
- 'EUC_JP' : 10,
- 'JAPANESE_SHIFT_JIS' : 11,
- 'SHIFT_JIS' : 11,
- 'JAPANESE_JIS' : 12,
- 'JIS' : 12,
- 'CHINESE_BIG5' : 13,
- 'BIG5' : 13,
- 'CHINESE_GB' : 14,
- 'CHINESE_EUC_CN' : 15,
- 'EUC_CN' : 15,
- 'KOREAN_EUC_KR' : 16,
- 'EUC_KR' : 16,
- 'UNICODE_UNUSED' : 17,
- 'CHINESE_EUC_DEC' : 18,
- 'EUC_DEC' : 18,
- 'CHINESE_CNS' : 19,
- 'CNS' : 19,
- 'CHINESE_BIG5_CP950' : 20,
- 'BIG5_CP950' : 20,
- 'JAPANESE_CP932' : 21,
- 'CP932' : 21,
- 'UTF8' : 22,
- 'UNKNOWN_ENCODING' : 23,
- 'ASCII_7BIT' : 24,
- 'RUSSIAN_KOI8_R' : 25,
- 'KOI8_R' : 25,
- 'RUSSIAN_CP1251' : 26,
- 'CP1251' : 26,
- 'MSFT_CP1252' : 27,
- 'CP1252' : 27,
- 'RUSSIAN_KOI8_RU' : 28,
- 'KOI8_RU' : 28,
- 'MSFT_CP1250' : 29,
- 'CP1250' : 29,
- 'ISO_8859_15' : 30,
- 'MSFT_CP1254' : 31,
- 'CP1254' : 31,
- 'MSFT_CP1257' : 32,
- 'CP1257' : 32,
- 'ISO_8859_11' : 33,
- 'MSFT_CP874' : 34,
- 'CP874' : 34,
- 'MSFT_CP1256' : 35,
- 'CP1256' : 35,
- 'MSFT_CP1255' : 36,
- 'CP1255' : 36,
- 'ISO_8859_8_I' : 37,
- 'HEBREW_VISUAL' : 38,
- 'CZECH_CP852' : 39,
- 'CP852' : 39,
- 'CZECH_CSN_369103' : 40,
- 'CSN_369103' : 40,
- 'MSFT_CP1253' : 41,
- 'CP1253' : 41,
- 'RUSSIAN_CP866' : 42,
- 'CP866' : 42,
- 'ISO_8859_13' : 43,
- 'ISO_2022_KR' : 44,
- 'GBK' : 45,
- 'GB18030' : 46,
- 'BIG5_HKSCS' : 47,
- 'ISO_2022_CN' : 48,
- 'TSCII' : 49,
- 'TAMIL_MONO' : 50,
- 'TAMIL_BI' : 51,
- 'JAGRAN' : 52,
- 'MACINTOSH_ROMAN' : 53,
- 'UTF7' : 54,
- 'BHASKAR' : 55,
- 'HTCHANAKYA' : 56,
- 'UTF16BE' : 57,
- 'UTF16LE' : 58,
- 'UTF32BE' : 59,
- 'UTF32LE' : 60,
- 'BINARYENC' : 61,
- 'HZ_GB_2312' : 62,
- 'UTF8UTF8' : 63,
- 'TAM_ELANGO' : 64,
- 'TAM_LTTMBARANI' : 65,
- 'TAM_SHREE' : 66,
- 'TAM_TBOOMIS' : 67,
- 'TAM_TMNEWS' : 68,
- 'TAM_WEBTAMIL' : 69,
- 'KDDI_SHIFT_JIS' : 70,
- 'DOCOMO_SHIFT_JIS' : 71,
- 'SOFTBANK_SHIFT_JIS' : 72,
- 'KDDI_ISO_2022_JP' : 73,
- 'ISO_2022_JP' : 73,
- 'SOFTBANK_ISO_2022_JP' : 74,
+ "ISO_8859_1" : 0,
+ "ISO_8859_2" : 1,
+ "ISO_8859_3" : 2,
+ "ISO_8859_4" : 3,
+ "ISO_8859_5" : 4,
+ "ISO_8859_6" : 5,
+ "ISO_8859_7" : 6,
+ "ISO_8859_8" : 7,
+ "ISO_8859_9" : 8,
+ "ISO_8859_10" : 9,
+ "JAPANESE_EUC_JP" : 10,
+ "EUC_JP" : 10,
+ "JAPANESE_SHIFT_JIS" : 11,
+ "SHIFT_JIS" : 11,
+ "JAPANESE_JIS" : 12,
+ "JIS" : 12,
+ "CHINESE_BIG5" : 13,
+ "BIG5" : 13,
+ "CHINESE_GB" : 14,
+ "CHINESE_EUC_CN" : 15,
+ "EUC_CN" : 15,
+ "KOREAN_EUC_KR" : 16,
+ "EUC_KR" : 16,
+ "UNICODE_UNUSED" : 17,
+ "CHINESE_EUC_DEC" : 18,
+ "EUC_DEC" : 18,
+ "CHINESE_CNS" : 19,
+ "CNS" : 19,
+ "CHINESE_BIG5_CP950" : 20,
+ "BIG5_CP950" : 20,
+ "JAPANESE_CP932" : 21,
+ "CP932" : 21,
+ "UTF8" : 22,
+ "UNKNOWN_ENCODING" : 23,
+ "ASCII_7BIT" : 24,
+ "RUSSIAN_KOI8_R" : 25,
+ "KOI8_R" : 25,
+ "RUSSIAN_CP1251" : 26,
+ "CP1251" : 26,
+ "MSFT_CP1252" : 27,
+ "CP1252" : 27,
+ "RUSSIAN_KOI8_RU" : 28,
+ "KOI8_RU" : 28,
+ "MSFT_CP1250" : 29,
+ "CP1250" : 29,
+ "ISO_8859_15" : 30,
+ "MSFT_CP1254" : 31,
+ "CP1254" : 31,
+ "MSFT_CP1257" : 32,
+ "CP1257" : 32,
+ "ISO_8859_11" : 33,
+ "MSFT_CP874" : 34,
+ "CP874" : 34,
+ "MSFT_CP1256" : 35,
+ "CP1256" : 35,
+ "MSFT_CP1255" : 36,
+ "CP1255" : 36,
+ "ISO_8859_8_I" : 37,
+ "HEBREW_VISUAL" : 38,
+ "CZECH_CP852" : 39,
+ "CP852" : 39,
+ "CZECH_CSN_369103" : 40,
+ "CSN_369103" : 40,
+ "MSFT_CP1253" : 41,
+ "CP1253" : 41,
+ "RUSSIAN_CP866" : 42,
+ "CP866" : 42,
+ "ISO_8859_13" : 43,
+ "ISO_2022_KR" : 44,
+ "GBK" : 45,
+ "GB18030" : 46,
+ "BIG5_HKSCS" : 47,
+ "ISO_2022_CN" : 48,
+ "TSCII" : 49,
+ "TAMIL_MONO" : 50,
+ "TAMIL_BI" : 51,
+ "JAGRAN" : 52,
+ "MACINTOSH_ROMAN" : 53,
+ "UTF7" : 54,
+ "BHASKAR" : 55,
+ "HTCHANAKYA" : 56,
+ "UTF16BE" : 57,
+ "UTF16LE" : 58,
+ "UTF32BE" : 59,
+ "UTF32LE" : 60,
+ "BINARYENC" : 61,
+ "HZ_GB_2312" : 62,
+ "UTF8UTF8" : 63,
+ "TAM_ELANGO" : 64,
+ "TAM_LTTMBARANI" : 65,
+ "TAM_SHREE" : 66,
+ "TAM_TBOOMIS" : 67,
+ "TAM_TMNEWS" : 68,
+ "TAM_WEBTAMIL" : 69,
+ "KDDI_SHIFT_JIS" : 70,
+ "DOCOMO_SHIFT_JIS" : 71,
+ "SOFTBANK_SHIFT_JIS" : 72,
+ "KDDI_ISO_2022_JP" : 73,
+ "ISO_2022_JP" : 73,
+ "SOFTBANK_ISO_2022_JP" : 74,
};
// Accept forms both with and without underscores/hypens.
for (let code of Object.keys(Encodings)) {
- if (code['includes']("_"))
+ if (code["includes"]("_"))
Encodings[code.replace(/_/g, "")] = Encodings[code];
}
addOnPreMain(function() {
onmessage = function(aMsg) {
- let data = aMsg['data'];
+ let data = aMsg["data"];
let langInfo;
- if (data['tld'] == undefined && data['encoding'] == undefined && data['language'] == undefined) {
- langInfo = LanguageInfo.detectLanguage(data['text'], !data['isHTML']);
+ if (data["tld"] == undefined && data["encoding"] == undefined && data["language"] == undefined) {
+ langInfo = LanguageInfo.detectLanguage(data["text"], !data["isHTML"]);
} else {
// Do our best to find the given encoding in the encodings table.
// Otherwise, just fall back to unknown.
- let enc = String(data['encoding']).toUpperCase().replace(/[_-]/g, "");
+ let enc = String(data["encoding"]).toUpperCase().replace(/[_-]/g, "");
let encoding;
if (Encodings.hasOwnProperty(enc))
encoding = Encodings[enc];
else
- encoding = Encodings['UNKNOWN_ENCODING'];
+ encoding = Encodings["UNKNOWN_ENCODING"];
- langInfo = LanguageInfo.detectLanguage(data['text'], !data['isHTML'],
- data['tld'] || null,
+ langInfo = LanguageInfo.detectLanguage(data["text"], !data["isHTML"],
+ data["tld"] || null,
encoding,
- data['language'] || null);
+ data["language"] || null);
}
postMessage({
- 'language': langInfo.getLanguageCode(),
- 'confident': langInfo.getIsReliable(),
+ "language": langInfo.getLanguageCode(),
+ "confident": langInfo.getIsReliable(),
- 'languages': new Array(3).fill(0).map((_, index) => {
+ "languages": new Array(3).fill(0).map((_, index) => {
let lang = langInfo.get_languages(index);
return {
- 'languageCode': lang.getLanguageCode(),
- 'percent': lang.getPercent(),
+ "languageCode": lang.getLanguageCode(),
+ "percent": lang.getPercent(),
};
}).filter(lang => {
// Ignore empty results.
- return lang['languageCode'] != "un" || lang['percent'] > 0;
+ return lang["languageCode"] != "un" || lang["percent"] > 0;
}),
});
Module.destroy(langInfo);
};
postMessage("ready");
});
--- a/browser/components/translation/test/browser_translation_telemetry.js
+++ b/browser/components/translation/test/browser_translation_telemetry.js
@@ -64,17 +64,17 @@ var MetricsChecker = {
/**
* A recurrent loop for making assertions about collected metrics.
*/
_assertionLoop(prevMetrics, metrics, additions) {
for (let metric of Object.keys(additions)) {
let addition = additions[metric];
// Allows nesting metrics. Useful for keyed histograms.
- if (typeof addition === 'object') {
+ if (typeof addition === "object") {
this._assertionLoop(prevMetrics[metric], metrics[metric], addition);
continue;
}
Assert.equal(prevMetrics[metric] + addition, metrics[metric]);
}
},
checkAdditions(additions) {
--- a/browser/components/uitour/UITour-lib.js
+++ b/browser/components/uitour/UITour-lib.js
@@ -1,104 +1,104 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// create namespace
-if (typeof Mozilla == 'undefined') {
+if (typeof Mozilla == "undefined") {
var Mozilla = {};
}
(function($) {
- 'use strict';
+ "use strict";
// create namespace
- if (typeof Mozilla.UITour == 'undefined') {
+ if (typeof Mozilla.UITour == "undefined") {
Mozilla.UITour = {};
}
var themeIntervalId = null;
function _stopCyclingThemes() {
if (themeIntervalId) {
clearInterval(themeIntervalId);
themeIntervalId = null;
}
}
function _sendEvent(action, data) {
- var event = new CustomEvent('mozUITour', {
+ var event = new CustomEvent("mozUITour", {
bubbles: true,
detail: {
action,
data: data || {}
}
});
document.dispatchEvent(event);
}
function _generateCallbackID() {
- return Math.random().toString(36).replace(/[^a-z]+/g, '');
+ return Math.random().toString(36).replace(/[^a-z]+/g, "");
}
function _waitForCallback(callback) {
var id = _generateCallbackID();
function listener(event) {
- if (typeof event.detail != 'object')
+ if (typeof event.detail != "object")
return;
if (event.detail.callbackID != id)
return;
- document.removeEventListener('mozUITourResponse', listener);
+ document.removeEventListener("mozUITourResponse", listener);
callback(event.detail.data);
}
- document.addEventListener('mozUITourResponse', listener);
+ document.addEventListener("mozUITourResponse", listener);
return id;
}
var notificationListener = null;
function _notificationListener(event) {
- if (typeof event.detail != 'object')
+ if (typeof event.detail != "object")
return;
- if (typeof notificationListener != 'function')
+ if (typeof notificationListener != "function")
return;
notificationListener(event.detail.event, event.detail.params);
}
Mozilla.UITour.DEFAULT_THEME_CYCLE_DELAY = 10 * 1000;
- Mozilla.UITour.CONFIGNAME_SYNC = 'sync';
- Mozilla.UITour.CONFIGNAME_AVAILABLETARGETS = 'availableTargets';
+ Mozilla.UITour.CONFIGNAME_SYNC = "sync";
+ Mozilla.UITour.CONFIGNAME_AVAILABLETARGETS = "availableTargets";
Mozilla.UITour.ping = function(callback) {
var data = {};
if (callback) {
data.callbackID = _waitForCallback(callback);
}
- _sendEvent('ping', data);
+ _sendEvent("ping", data);
};
Mozilla.UITour.observe = function(listener, callback) {
notificationListener = listener;
if (listener) {
- document.addEventListener('mozUITourNotification',
+ document.addEventListener("mozUITourNotification",
_notificationListener);
Mozilla.UITour.ping(callback);
} else {
- document.removeEventListener('mozUITourNotification',
+ document.removeEventListener("mozUITourNotification",
_notificationListener);
}
};
Mozilla.UITour.registerPageID = function(pageID) {
- _sendEvent('registerPageID', {
+ _sendEvent("registerPageID", {
pageID
});
};
Mozilla.UITour.showHeartbeat = function(message, thankyouMessage, flowId, engagementURL,
learnMoreLabel, learnMoreURL, options) {
var args = {
message,
@@ -113,28 +113,28 @@ if (typeof Mozilla == 'undefined') {
for (var option in options) {
if (!options.hasOwnProperty(option)) {
continue;
}
args[option] = options[option];
}
}
- _sendEvent('showHeartbeat', args);
+ _sendEvent("showHeartbeat", args);
};
Mozilla.UITour.showHighlight = function(target, effect) {
- _sendEvent('showHighlight', {
+ _sendEvent("showHighlight", {
target,
effect
});
};
Mozilla.UITour.hideHighlight = function() {
- _sendEvent('hideHighlight');
+ _sendEvent("hideHighlight");
};
Mozilla.UITour.showInfo = function(target, title, text, icon, buttons, options) {
var buttonData = [];
if (Array.isArray(buttons)) {
for (var i = 0; i < buttons.length; i++) {
buttonData.push({
label: buttons[i].label,
@@ -146,186 +146,186 @@ if (typeof Mozilla == 'undefined') {
}
var closeButtonCallbackID, targetCallbackID;
if (options && options.closeButtonCallback)
closeButtonCallbackID = _waitForCallback(options.closeButtonCallback);
if (options && options.targetCallback)
targetCallbackID = _waitForCallback(options.targetCallback);
- _sendEvent('showInfo', {
+ _sendEvent("showInfo", {
target,
title,
text,
icon,
buttons: buttonData,
closeButtonCallbackID,
targetCallbackID
});
};
Mozilla.UITour.hideInfo = function() {
- _sendEvent('hideInfo');
+ _sendEvent("hideInfo");
};
Mozilla.UITour.previewTheme = function(theme) {
_stopCyclingThemes();
- _sendEvent('previewTheme', {
+ _sendEvent("previewTheme", {
theme: JSON.stringify(theme)
});
};
Mozilla.UITour.resetTheme = function() {
_stopCyclingThemes();
- _sendEvent('resetTheme');
+ _sendEvent("resetTheme");
};
Mozilla.UITour.cycleThemes = function(themes, delay, callback) {
_stopCyclingThemes();
if (!delay) {
delay = Mozilla.UITour.DEFAULT_THEME_CYCLE_DELAY;
}
function nextTheme() {
var theme = themes.shift();
themes.push(theme);
- _sendEvent('previewTheme', {
+ _sendEvent("previewTheme", {
theme: JSON.stringify(theme),
state: true
});
callback(theme);
}
themeIntervalId = setInterval(nextTheme, delay);
nextTheme();
};
Mozilla.UITour.showMenu = function(name, callback) {
var showCallbackID;
if (callback)
showCallbackID = _waitForCallback(callback);
- _sendEvent('showMenu', {
+ _sendEvent("showMenu", {
name,
showCallbackID,
});
};
Mozilla.UITour.hideMenu = function(name) {
- _sendEvent('hideMenu', {
+ _sendEvent("hideMenu", {
name
});
};
Mozilla.UITour.showNewTab = function() {
- _sendEvent('showNewTab');
+ _sendEvent("showNewTab");
};
Mozilla.UITour.getConfiguration = function(configName, callback) {
- _sendEvent('getConfiguration', {
+ _sendEvent("getConfiguration", {
callbackID: _waitForCallback(callback),
configuration: configName,
});
};
Mozilla.UITour.setConfiguration = function(configName, configValue) {
- _sendEvent('setConfiguration', {
+ _sendEvent("setConfiguration", {
configuration: configName,
value: configValue,
});
};
/**
* Request the browser open the Firefox Accounts page.
*
* @param {Object} extraURLCampaignParams - An object containing additional
* paramaters for the URL opened by the browser for reasons of promotional
* campaign tracking. Each attribute of the object must have a name that
* is a string, begins with "utm_" and contains only only alphanumeric
* characters, dashes or underscores. The values may be any string and will
* automatically be encoded.
*/
Mozilla.UITour.showFirefoxAccounts = function(extraURLCampaignParams) {
- _sendEvent('showFirefoxAccounts', {
+ _sendEvent("showFirefoxAccounts", {
extraURLCampaignParams: JSON.stringify(extraURLCampaignParams),
});
};
Mozilla.UITour.resetFirefox = function() {
- _sendEvent('resetFirefox');
+ _sendEvent("resetFirefox");
};
Mozilla.UITour.addNavBarWidget = function(name, callback) {
- _sendEvent('addNavBarWidget', {
+ _sendEvent("addNavBarWidget", {
name,
callbackID: _waitForCallback(callback),
});
};
Mozilla.UITour.setDefaultSearchEngine = function(identifier) {
- _sendEvent('setDefaultSearchEngine', {
+ _sendEvent("setDefaultSearchEngine", {
identifier,
});
};
Mozilla.UITour.setTreatmentTag = function(name, value) {
- _sendEvent('setTreatmentTag', {
+ _sendEvent("setTreatmentTag", {
name,
value
});
};
Mozilla.UITour.getTreatmentTag = function(name, callback) {
- _sendEvent('getTreatmentTag', {
+ _sendEvent("getTreatmentTag", {
name,
callbackID: _waitForCallback(callback)
});
};
Mozilla.UITour.setSearchTerm = function(term) {
- _sendEvent('setSearchTerm', {
+ _sendEvent("setSearchTerm", {
term
});
};
Mozilla.UITour.openSearchPanel = function(callback) {
- _sendEvent('openSearchPanel', {
+ _sendEvent("openSearchPanel", {
callbackID: _waitForCallback(callback)
});
};
Mozilla.UITour.forceShowReaderIcon = function() {
- _sendEvent('forceShowReaderIcon');
+ _sendEvent("forceShowReaderIcon");
};
Mozilla.UITour.toggleReaderMode = function() {
- _sendEvent('toggleReaderMode');
+ _sendEvent("toggleReaderMode");
};
Mozilla.UITour.openPreferences = function(pane) {
- _sendEvent('openPreferences', {
+ _sendEvent("openPreferences", {
pane
});
};
/**
* Closes the tab where this code is running. As usual, if the tab is in the
* foreground, the tab that was displayed before is selected.
*
* The last tab in the current window will never be closed, in which case
* this call will have no effect. The calling code is expected to take an
* action after a small timeout in order to handle this case, for example by
* displaying a goodbye message or a button to restart the tour.
*/
Mozilla.UITour.closeTab = function() {
- _sendEvent('closeTab');
+ _sendEvent("closeTab");
};
})();
// Make this library Require-able.
-if (typeof module !== 'undefined' && module.exports) {
+if (typeof module !== "undefined" && module.exports) {
module.exports = Mozilla.UITour;
}
--- a/browser/components/uitour/test/browser_UITour_heartbeat.js
+++ b/browser/components/uitour/test/browser_UITour_heartbeat.js
@@ -180,25 +180,25 @@ add_UITour_task(function* test_heartbeat
["Heartbeat:NotificationOffered", "Heartbeat:NotificationClosed", "Heartbeat:TelemetrySent"]);
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL);
// Validate the returned timestamp.
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Close the heartbeat notification.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
cleanUpNotification(flowId);
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received");
checkTelemetry(data, flowId, ["offeredTS", "closedTS"]);
// This rejects whenever an unexpected notification is received.
yield receivedExpectedPromise;
})
@@ -221,29 +221,29 @@ add_UITour_task(function* test_heartbeat
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL, null, null, {
iconURL
});
// Validate the returned timestamp.
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Check the icon URL
let notification = getHeartbeatNotification(flowId);
is(notification.image, iconURL, "The optional icon URL is not taken correctly");
// Close the heartbeat notification.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
cleanUpNotification(flowId);
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received");
checkTelemetry(data, flowId, ["offeredTS", "closedTS"]);
// This rejects whenever an unexpected notification is received.
yield receivedExpectedPromise;
})
@@ -263,32 +263,32 @@ add_UITour_task(function* test_heartbeat
"Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, null);
// Validate the returned timestamp.
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
// wait for them here.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
// The UI was just shown. We can simulate a click on a rating element (i.e., "star").
simulateVote(flowId, 2);
data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
+ validateTimestamp("Heartbeat:Voted", data.timestamp);
// Validate the closing timestamp.
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened.");
// Validate the data we send out.
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
is(data.score, 2, "Checking Telemetry payload.score");
@@ -312,32 +312,32 @@ add_UITour_task(function* test_heartbeat
"Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, invalidEngagementURL);
// Validate the returned timestamp.
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
// wait for them here.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
// The UI was just shown. We can simulate a click on a rating element (i.e., "star").
simulateVote(flowId, 2);
data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
+ validateTimestamp("Heartbeat:Voted", data.timestamp);
// Validate the closing timestamp.
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened.");
// Validate the data we send out.
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
is(data.score, 2, "Checking Telemetry payload.score");
@@ -361,33 +361,33 @@ add_UITour_task(function* test_heartbeat
"Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, null);
// Validate the returned timestamp.
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
// wait for them here.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
// The UI was just shown. We can simulate a click on a rating element (i.e., "star").
simulateVote(flowId, expectedScore);
data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
+ validateTimestamp("Heartbeat:Voted", data.timestamp);
is(data.score, expectedScore, "Should report a score of " + expectedScore);
// Validate the closing timestamp and vote.
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
is(gBrowser.tabs.length, originalTabCount, "No engagement tab should be opened.");
// Validate the data we send out.
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
is(data.score, expectedScore, "Checking Telemetry payload.score");
@@ -412,32 +412,32 @@ add_UITour_task(function* test_heartbeat
"Heartbeat:NotificationClosed", "Heartbeat:Voted", "Heartbeat:TelemetrySent"]);
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, engagementURL);
// Validate the returned timestamp.
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Wait an the Voted, Closed and Telemetry Sent events. They are fired together, so
// wait for them here.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let votedPromise = promiseWaitHeartbeatNotification("Heartbeat:Voted");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
// The UI was just shown. We can simulate a click on a rating element (i.e., "star").
simulateVote(flowId, 1);
data = yield votedPromise;
- validateTimestamp('Heartbeat:Voted', data.timestamp);
+ validateTimestamp("Heartbeat:Voted", data.timestamp);
// Validate the closing timestamp, vote and make sure the engagement page was opened.
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
is(gBrowser.tabs.length, expectedTabCount, "Engagement URL should open in a new tab.");
gBrowser.removeCurrentTab();
// Validate the data we send out.
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "votedTS", "closedTS", "score"]);
is(data.score, 1, "Checking Telemetry payload.score");
@@ -464,38 +464,38 @@ add_UITour_task(function* test_heartbeat
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("Do you want to engage with us?", "Thank you!", flowId, engagementURL, null, null, {
engagementButtonLabel: "Engage Me",
});
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Wait an the Engaged, Closed and Telemetry Sent events. They are fired together, so
// wait for them here.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let engagedPromise = promiseWaitHeartbeatNotification("Heartbeat:Engaged");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
// Simulate user engagement.
let notification = getHeartbeatNotification(flowId);
is(notification.querySelectorAll(".star-x").length, 0, "No stars should be present");
// The UI was just shown. We can simulate a click on the engagement button.
let engagementButton = notification.querySelector(".notification-button");
is(engagementButton.label, "Engage Me", "Check engagement button text");
engagementButton.doCommand();
data = yield engagedPromise;
- validateTimestamp('Heartbeat:Engaged', data.timestamp);
+ validateTimestamp("Heartbeat:Engaged", data.timestamp);
// Validate the closing timestamp, vote and make sure the engagement page was opened.
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
is(gBrowser.tabs.length, expectedTabCount, "Engagement URL should open in a new tab.");
gBrowser.removeCurrentTab();
// Validate the data we send out.
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "engagedTS", "closedTS"]);
@@ -521,34 +521,34 @@ add_UITour_task(function* test_heartbeat
"Heartbeat:NotificationClosed", "Heartbeat:LearnMore", "Heartbeat:TelemetrySent"]);
// Show the Heartbeat notification and wait for it to be displayed.
let shownPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationOffered");
gContentAPI.showHeartbeat("How would you rate Firefox?", "Thank you!", flowId, dummyURL,
"What is this?", dummyURL);
let data = yield shownPromise;
- validateTimestamp('Heartbeat:Offered', data.timestamp);
+ validateTimestamp("Heartbeat:Offered", data.timestamp);
// Wait an the LearnMore, Closed and Telemetry Sent events. They are fired together, so
// wait for them here.
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let learnMorePromise = promiseWaitHeartbeatNotification("Heartbeat:LearnMore");
let pingSentPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
// The UI was just shown. Simulate a click on the learn more link.
clickLearnMore(flowId);
data = yield learnMorePromise;
- validateTimestamp('Heartbeat:LearnMore', data.timestamp);
+ validateTimestamp("Heartbeat:LearnMore", data.timestamp);
cleanUpNotification(flowId);
// The notification was closed.
data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
is(gBrowser.tabs.length, expectedTabCount, "Learn more URL should open in a new tab.");
gBrowser.removeCurrentTab();
// Validate the data we send out.
data = yield pingSentPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "learnMoreTS", "closedTS"]);
@@ -732,17 +732,17 @@ add_UITour_task(function* test_telemetry
yield shownPromise;
let closedPromise = promiseWaitHeartbeatNotification("Heartbeat:NotificationClosed");
let pingPromise = promiseWaitHeartbeatNotification("Heartbeat:TelemetrySent");
cleanUpNotification(flowId);
// The notification was closed.
let data = yield closedPromise;
- validateTimestamp('Heartbeat:NotificationClosed', data.timestamp);
+ validateTimestamp("Heartbeat:NotificationClosed", data.timestamp);
// Validate the data we send out.
data = yield pingPromise;
info("'Heartbeat:TelemetrySent' notification received.");
checkTelemetry(data, flowId, ["offeredTS", "closedTS"].concat(expectedFields));
for (let param of expectedFields) {
is(data[param], extraParams[param],
"Whitelisted experiment configs should be copied into Telemetry pings");
--- a/browser/experiments/test/addons/experiment-racybranch/bootstrap.js
+++ b/browser/experiments/test/addons/experiment-racybranch/bootstrap.js
@@ -8,17 +8,17 @@ var gStarted = false;
function startup(data, reasonCode) {
if (gStarted) {
return;
}
gStarted = true;
// delay realstartup to trigger the race condition
- Cc['@mozilla.org/thread-manager;1'].getService(Ci.nsIThreadManager)
+ Cc["@mozilla.org/thread-manager;1"].getService(Ci.nsIThreadManager)
.mainThread.dispatch(realstartup, 0);
}
function realstartup() {
let experiments = Experiments.instance();
let experiment = experiments._getActiveExperiment();
if (experiment.branch) {
Cu.reportError("Found pre-existing branch: " + experiment.branch);
--- a/browser/extensions/aushelper/bootstrap.js
+++ b/browser/extensions/aushelper/bootstrap.js
@@ -72,17 +72,17 @@ function startup() {
for (let j = 4; j < 8; j++) {
let c = regVal.charCodeAt(j).toString(16);
if (c.length == 1) {
c = "0" + c;
}
hexVal.unshift(c);
}
cpuRevMatch = false;
- if (microCodeVersions.indexOf(parseInt(hexVal.join(''))) != -1) {
+ if (microCodeVersions.indexOf(parseInt(hexVal.join(""))) != -1) {
cpuRevMatch = true;
}
break;
}
} catch (e) {
if (i == keyNames.length - 1) {
// The registry key name's value was not successfully queried.
cpuRevMatch = null;
--- a/browser/extensions/pocket/content/main.js
+++ b/browser/extensions/pocket/content/main.js
@@ -81,17 +81,17 @@ var pktUI = (function() {
}
function pocketPanelDidHide(event) {
if (_currentPanelDidHide) {
_currentPanelDidHide(event);
}
// clear the panel
- getPanelFrame().setAttribute('src', 'about:blank');
+ getPanelFrame().setAttribute("src", "about:blank");
}
// -- Communication to API -- //
/**
* Either save or attempt to log the user in
*/
@@ -114,60 +114,60 @@ var pktUI = (function() {
// -- Panel UI -- //
/**
* Show the sign-up panel
*/
function showSignUp() {
// AB test: Direct logged-out users to tab vs panel
- if (pktApi.getSignupPanelTabTestVariant() == 'v2') {
+ if (pktApi.getSignupPanelTabTestVariant() == "v2") {
let site = Services.prefs.getCharPref("extensions.pocket.site");
- openTabWithUrl('https://' + site + '/firefox_learnmore?s=ffi&t=autoredirect&tv=page_learnmore&src=ff_ext', true);
+ openTabWithUrl("https://" + site + "/firefox_learnmore?s=ffi&t=autoredirect&tv=page_learnmore&src=ff_ext", true);
// force the panel closed before it opens
getPanel().hidePopup();
return;
}
// Control: Show panel as normal
getFirefoxAccountSignedInUser(function(userdata) {
- var fxasignedin = (typeof userdata == 'object' && userdata !== null) ? '1' : '0';
+ var fxasignedin = (typeof userdata == "object" && userdata !== null) ? "1" : "0";
var startheight = 490;
var inOverflowMenu = isInOverflowMenu();
- var controlvariant = pktApi.getSignupPanelTabTestVariant() == 'control';
+ var controlvariant = pktApi.getSignupPanelTabTestVariant() == "control";
if (inOverflowMenu) {
startheight = overflowMenuHeight;
} else {
startheight = 460;
- if (fxasignedin == '1') {
+ if (fxasignedin == "1") {
startheight = 406;
}
}
if (!controlvariant) {
startheight = 427;
}
var variant;
if (inOverflowMenu) {
- variant = 'overflow';
+ variant = "overflow";
} else {
- variant = 'storyboard_lm';
+ variant = "storyboard_lm";
}
showPanel("about:pocket-signup?pockethost="
+ Services.prefs.getCharPref("extensions.pocket.site")
+ "&fxasignedin="
+ fxasignedin
+ "&variant="
+ variant
- + '&controlvariant='
+ + "&controlvariant="
+ controlvariant
- + '&inoverflowmenu='
+ + "&inoverflowmenu="
+ inOverflowMenu
+ "&locale="
+ getUILocale(), {
onShow() {
},
onHide: panelDidHide,
width: inOverflowMenu ? overflowMenuWidth : 300,
height: startheight
@@ -176,48 +176,48 @@ var pktUI = (function() {
}
/**
* Show the logged-out state / sign-up panel
*/
function saveAndShowConfirmation(url, title) {
// Validate input parameter
- if (typeof url !== 'undefined' && url.startsWith("about:reader?url=")) {
+ if (typeof url !== "undefined" && url.startsWith("about:reader?url=")) {
url = ReaderMode.getOriginalUrl(url);
}
- var isValidURL = (typeof url !== 'undefined' && (url.startsWith("http") || url.startsWith('https')));
+ var isValidURL = (typeof url !== "undefined" && (url.startsWith("http") || url.startsWith("https")));
var inOverflowMenu = isInOverflowMenu();
var startheight = pktApi.isPremiumUser() && isValidURL ? savePanelHeights.expanded : savePanelHeights.collapsed;
if (inOverflowMenu) {
startheight = overflowMenuHeight;
}
- var panelId = showPanel("about:pocket-saved?pockethost=" + Services.prefs.getCharPref("extensions.pocket.site") + "&premiumStatus=" + (pktApi.isPremiumUser() ? '1' : '0') + '&inoverflowmenu=' + inOverflowMenu + "&locale=" + getUILocale(), {
+ var panelId = showPanel("about:pocket-saved?pockethost=" + Services.prefs.getCharPref("extensions.pocket.site") + "&premiumStatus=" + (pktApi.isPremiumUser() ? "1" : "0") + "&inoverflowmenu=" + inOverflowMenu + "&locale=" + getUILocale(), {
onShow() {
- var saveLinkMessageId = 'saveLink';
+ var saveLinkMessageId = "saveLink";
// Send error message for invalid url
if (!isValidURL) {
// TODO: Pass key for localized error in error object
let error = {
- message: 'Only links can be saved',
+ message: "Only links can be saved",
localizedKey: "onlylinkssaved"
};
pktUIMessaging.sendErrorMessageToPanel(panelId, saveLinkMessageId, error);
return;
}
// Check online state
if (!navigator.onLine) {
// TODO: Pass key for localized error in error object
let error = {
- message: 'You must be connected to the Internet in order to save to Pocket. Please connect to the Internet and try again.'
+ message: "You must be connected to the Internet in order to save to Pocket. Please connect to the Internet and try again."
};
pktUIMessaging.sendErrorMessageToPanel(panelId, saveLinkMessageId, error);
return;
}
// Add url
var options = {
success(data, request) {
@@ -272,17 +272,17 @@ var pktUI = (function() {
// as if the user tries to click again on the toolbar button the overlay
// will close instead of the button will be clicked
var iframe = getPanelFrame();
// Register event handlers
registerEventMessages();
// Load the iframe
- iframe.setAttribute('src', url);
+ iframe.setAttribute("src", url);
// Uncomment to leave panel open -- for debugging
// panel.setAttribute('noautohide', true);
// panel.setAttribute('consumeoutsideclicks', false);
//
// For some reason setting onpopupshown and onpopuphidden on the panel directly didn't work, so
// do it this hacky way for now
@@ -330,17 +330,17 @@ var pktUI = (function() {
/**
* Register all of the messages needed for the panels
*/
function registerEventMessages() {
var iframe = getPanelFrame();
// Only register the messages once
- var didInitAttributeKey = 'did_init';
+ var didInitAttributeKey = "did_init";
var didInitMessageListener = iframe.getAttribute(didInitAttributeKey);
if (typeof didInitMessageListener !== "undefined" && didInitMessageListener == 1) {
return;
}
iframe.setAttribute(didInitAttributeKey, 1);
// When the panel is displayed it generated an event called
// "show": we will listen for that event and when it happens,
@@ -532,21 +532,21 @@ var pktUI = (function() {
var panel = frame;
while (panel && panel.localName != "panel") {
panel = panel.parentNode;
}
return panel;
}
function getPanelFrame() {
- var frame = document.getElementById('pocket-panel-iframe');
+ var frame = document.getElementById("pocket-panel-iframe");
if (!frame) {
var frameParent = document.getElementById("PanelUI-pocketView").firstChild;
frame = document.createElement("iframe");
- frame.id = 'pocket-panel-iframe';
+ frame.id = "pocket-panel-iframe";
frame.setAttribute("type", "content");
frameParent.appendChild(frame);
}
return frame;
}
function getSubview() {
var view = document.getElementById("PanelUI-pocketView");
@@ -594,17 +594,17 @@ var pktUI = (function() {
// -- Communication to Background -- //
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Interaction_between_privileged_and_non-privileged_pages
var pktUIMessaging = (function() {
/**
* Prefix message id for message listening
*/
function prefixedMessageId(messageId) {
- return 'PKT_' + messageId;
+ return "PKT_" + messageId;
}
/**
* Register a listener and callback for a specific messageId
*/
function addMessageListener(iframe, messageId, callback) {
iframe.addEventListener(prefixedMessageId(messageId), function(e) {
var nodePrincipal = e.target.nodePrincipal;
@@ -634,17 +634,17 @@ var pktUIMessaging = (function() {
var panelFrame = pktUI.getPanelFrame();
if (!isPocketPanelFrameValid(panelFrame)) { return; }
var doc = panelFrame.contentWindow.document;
var documentElement = doc.documentElement;
// Send message to panel
- var panelMessageId = prefixedMessageId(panelId + '_' + messageId);
+ var panelMessageId = prefixedMessageId(panelId + "_" + messageId);
var AnswerEvt = doc.createElement("PKTMessage");
AnswerEvt.setAttribute("payload", JSON.stringify([payload]));
documentElement.appendChild(AnswerEvt);
var event = doc.createEvent("HTMLEvents");
event.initEvent(panelMessageId, true, false);
AnswerEvt.dispatchEvent(event);
--- a/browser/extensions/pocket/content/panels/js/messages.js
+++ b/browser/extensions/pocket/content/panels/js/messages.js
@@ -8,21 +8,21 @@ var pktPanelMessaging = (function() {
if (panelId && panelId.length > 1) {
return panelId[1];
}
return 0;
}
function prefixedMessageId(messageId) {
- return 'PKT_' + messageId;
+ return "PKT_" + messageId;
}
function panelPrefixedMessageId(panelId, messageId) {
- return prefixedMessageId(panelId + '_' + messageId);
+ return prefixedMessageId(panelId + "_" + messageId);
}
function addMessageListener(panelId, messageId, callback) {
document.addEventListener(panelPrefixedMessageId(panelId, messageId), function(e) {
callback(JSON.parse(e.target.getAttribute("payload"))[0]);
// TODO: Figure out why e.target.parentNode is null
--- a/browser/extensions/pocket/content/panels/js/saved.js
+++ b/browser/extensions/pocket/content/panels/js/saved.js
@@ -4,17 +4,17 @@ It does not contain any logic for saving
*/
var PKT_SAVED_OVERLAY = function(options) {
var myself = this;
this.inited = false;
this.active = false;
this.wrapper = null;
this.pockethost = "getpocket.com";
this.savedItemId = 0;
- this.savedUrl = '';
+ this.savedUrl = "";
this.premiumStatus = false;
this.preventCloseTimerCancel = false;
this.closeValid = true;
this.mouseInside = false;
this.autocloseTimer = null;
this.inoverflowmenu = false;
this.dictJSON = {};
this.autocloseTiming = 3500;
@@ -25,78 +25,78 @@ var PKT_SAVED_OVERLAY = function(options
this.cxt_entered = 0;
this.cxt_suggested = 0;
this.cxt_removed = 0;
this.justaddedsuggested = false;
this.fillTagContainer = function(tags, container, tagclass) {
container.children().remove();
for (var i = 0; i < tags.length; i++) {
var newtag = $('<li><a href="#" class="token_tag"></a></li>');
- newtag.find('a').text(tags[i]);
+ newtag.find("a").text(tags[i]);
newtag.addClass(tagclass);
container.append(newtag);
this.cxt_suggested_available++;
}
};
this.fillUserTags = function() {
thePKT_SAVED.sendMessage("getTags", {}, function(resp) {
- if (typeof resp == 'object' && typeof resp.tags == 'object') {
+ if (typeof resp == "object" && typeof resp.tags == "object") {
myself.userTags = resp.tags;
}
});
};
this.fillSuggestedTags = function() {
- if (!$('.pkt_ext_suggestedtag_detail').length) {
+ if (!$(".pkt_ext_suggestedtag_detail").length) {
myself.suggestedTagsLoaded = true;
myself.startCloseTimer();
return;
}
thePKT_SAVED.sendMessage("getSuggestedTags",
{
url: myself.savedUrl
}, function(resp) {
- $('.pkt_ext_suggestedtag_detail').removeClass('pkt_ext_suggestedtag_detail_loading');
- if (resp.status == 'success') {
+ $(".pkt_ext_suggestedtag_detail").removeClass("pkt_ext_suggestedtag_detail_loading");
+ if (resp.status == "success") {
var newtags = [];
for (var i = 0; i < resp.value.suggestedTags.length; i++) {
newtags.push(resp.value.suggestedTags[i].tag);
}
myself.suggestedTagsLoaded = true;
if (!myself.mouseInside) {
myself.startCloseTimer();
}
- myself.fillTagContainer(newtags, $('.pkt_ext_suggestedtag_detail ul'), 'token_suggestedtag');
- } else if (resp.status == 'error') {
+ myself.fillTagContainer(newtags, $(".pkt_ext_suggestedtag_detail ul"), "token_suggestedtag");
+ } else if (resp.status == "error") {
var msg = $('<p class="suggestedtag_msg">');
msg.text(resp.error.message);
- $('.pkt_ext_suggestedtag_detail').append(msg);
+ $(".pkt_ext_suggestedtag_detail").append(msg);
this.suggestedTagsLoaded = true;
if (!myself.mouseInside) {
myself.startCloseTimer();
}
}
});
}
this.initAutoCloseEvents = function() {
- this.wrapper.on('mouseenter', function() {
+ this.wrapper.on("mouseenter", function() {
myself.mouseInside = true;
myself.stopCloseTimer();
});
- this.wrapper.on('mouseleave', function() {
+ this.wrapper.on("mouseleave", function() {
myself.mouseInside = false;
myself.startCloseTimer();
});
- this.wrapper.on('click', function(e) {
+ this.wrapper.on("click", function(e) {
myself.closeValid = false;
});
};
this.startCloseTimer = function(manualtime) {
var settime = manualtime ? manualtime : myself.autocloseTiming;
- if (typeof myself.autocloseTimer == 'number') {
+ if (typeof myself.autocloseTimer == "number") {
clearTimeout(myself.autocloseTimer);
}
myself.autocloseTimer = setTimeout(function() {
if (myself.closeValid || myself.preventCloseTimerCancel) {
myself.preventCloseTimerCancel = false;
myself.closePopup();
}
}, settime);
@@ -107,113 +107,113 @@ var PKT_SAVED_OVERLAY = function(options
}
clearTimeout(myself.autocloseTimer);
};
this.closePopup = function() {
myself.stopCloseTimer();
thePKT_SAVED.sendMessage("close");
};
this.checkValidTagSubmit = function() {
- var inputlength = $.trim($('.pkt_ext_tag_input_wrapper').find('.token-input-input-token').children('input').val()).length;
- if ($('.pkt_ext_containersaved').find('.token-input-token').length || (inputlength > 0 && inputlength < 26)) {
- $('.pkt_ext_containersaved').find('.pkt_ext_btn').removeClass('pkt_ext_btn_disabled');
+ var inputlength = $.trim($(".pkt_ext_tag_input_wrapper").find(".token-input-input-token").children("input").val()).length;
+ if ($(".pkt_ext_containersaved").find(".token-input-token").length || (inputlength > 0 && inputlength < 26)) {
+ $(".pkt_ext_containersaved").find(".pkt_ext_btn").removeClass("pkt_ext_btn_disabled");
} else {
- $('.pkt_ext_containersaved').find('.pkt_ext_btn').addClass('pkt_ext_btn_disabled');
+ $(".pkt_ext_containersaved").find(".pkt_ext_btn").addClass("pkt_ext_btn_disabled");
}
myself.updateSlidingTagList();
};
this.updateSlidingTagList = function() {
- var inputleft = $('.token-input-input-token input').position().left;
- var listleft = $('.token-input-list').position().left;
- var listleftmanual = parseInt($('.token-input-list').css('left'));
+ var inputleft = $(".token-input-input-token input").position().left;
+ var listleft = $(".token-input-list").position().left;
+ var listleftmanual = parseInt($(".token-input-list").css("left"));
var listleftnatural = listleft - listleftmanual;
- var leftwidth = $('.pkt_ext_tag_input_wrapper').outerWidth();
+ var leftwidth = $(".pkt_ext_tag_input_wrapper").outerWidth();
if ((inputleft + listleft + 20) > leftwidth) {
- $('.token-input-list').css('left', Math.min(((inputleft + listleftnatural - leftwidth + 20) * -1), 0) + 'px');
+ $(".token-input-list").css("left", Math.min(((inputleft + listleftnatural - leftwidth + 20) * -1), 0) + "px");
} else {
- $('.token-input-list').css('left', '0');
+ $(".token-input-list").css("left", "0");
}
};
this.checkPlaceholderStatus = function() {
- if (this.wrapper.find('.pkt_ext_tag_input_wrapper').find('.token-input-token').length) {
- this.wrapper.find('.token-input-input-token input').attr('placeholder', '');
+ if (this.wrapper.find(".pkt_ext_tag_input_wrapper").find(".token-input-token").length) {
+ this.wrapper.find(".token-input-input-token input").attr("placeholder", "");
} else {
- this.wrapper.find('.token-input-input-token input').attr('placeholder', $('.pkt_ext_tag_input').attr('placeholder')).css('width', '200px');
+ this.wrapper.find(".token-input-input-token input").attr("placeholder", $(".pkt_ext_tag_input").attr("placeholder")).css("width", "200px");
}
};
this.initTagInput = function() {
- var inputwrapper = $('.pkt_ext_tag_input_wrapper');
- inputwrapper.find('.pkt_ext_tag_input').tokenInput([], {
+ var inputwrapper = $(".pkt_ext_tag_input_wrapper");
+ inputwrapper.find(".pkt_ext_tag_input").tokenInput([], {
searchDelay: 200,
minChars: 1,
animateDropdown: false,
noResultsHideDropdown: true,
scrollKeyboard: true,
emptyInputLength: 200,
search_function(term, cb) {
var returnlist = [];
if (term.length) {
var limit = 15;
- var r = new RegExp('^' + term);
+ var r = new RegExp("^" + term);
for (var i = 0; i < myself.userTags.length; i++) {
if (r.test(myself.userTags[i]) && limit > 0) {
returnlist.push({name:myself.userTags[i]});
limit--;
}
}
}
- if (!$('.token-input-dropdown-tag').data('init')) {
- $('.token-input-dropdown-tag').css('width', inputwrapper.outerWidth()).data('init');
- inputwrapper.append($('.token-input-dropdown-tag'));
+ if (!$(".token-input-dropdown-tag").data("init")) {
+ $(".token-input-dropdown-tag").css("width", inputwrapper.outerWidth()).data("init");
+ inputwrapper.append($(".token-input-dropdown-tag"));
}
cb(returnlist);
},
textToData(text) {
if ($.trim(text).length > 25 || !$.trim(text).length) {
if (text.length > 25) {
myself.showTagsError(myself.dictJSON.maxtaglength);
changestamp = Date.now();
setTimeout(function() {
- $('.token-input-input-token input').val(text).focus();
+ $(".token-input-input-token input").val(text).focus();
}, 10);
}
return null;
}
myself.hideTagsError();
return {name:myself.sanitizeText(text.toLowerCase())};
},
onReady() {
- $('.token-input-dropdown').addClass('token-input-dropdown-tag');
- inputwrapper.find('.token-input-input-token input').attr('placeholder', $('.tag-input').attr('placeholder')).css('width', '200px');
- if ($('.pkt_ext_suggestedtag_detail').length) {
- myself.wrapper.find('.pkt_ext_suggestedtag_detail').on('click', '.token_tag', function(e) {
+ $(".token-input-dropdown").addClass("token-input-dropdown-tag");
+ inputwrapper.find(".token-input-input-token input").attr("placeholder", $(".tag-input").attr("placeholder")).css("width", "200px");
+ if ($(".pkt_ext_suggestedtag_detail").length) {
+ myself.wrapper.find(".pkt_ext_suggestedtag_detail").on("click", ".token_tag", function(e) {
e.preventDefault();
var tag = $(e.target);
- if ($(this).parents('.pkt_ext_suggestedtag_detail_disabled').length) {
+ if ($(this).parents(".pkt_ext_suggestedtag_detail_disabled").length) {
return;
}
myself.justaddedsuggested = true;
- inputwrapper.find('.pkt_ext_tag_input').tokenInput('add', {id:inputwrapper.find('.token-input-token').length, name:tag.text()});
- tag.addClass('token-suggestedtag-inactive');
- $('.token-input-input-token input').focus();
+ inputwrapper.find(".pkt_ext_tag_input").tokenInput("add", {id:inputwrapper.find(".token-input-token").length, name:tag.text()});
+ tag.addClass("token-suggestedtag-inactive");
+ $(".token-input-input-token input").focus();
});
}
- $('.token-input-list').on('keydown', 'input', function(e) {
+ $(".token-input-list").on("keydown", "input", function(e) {
if (e.which == 37) {
myself.updateSlidingTagList();
}
- }).on('keypress', 'input', function(e) {
+ }).on("keypress", "input", function(e) {
if (e.which == 13) {
- if (typeof changestamp == 'undefined' || (Date.now() - changestamp > 250)) {
+ if (typeof changestamp == "undefined" || (Date.now() - changestamp > 250)) {
e.preventDefault();
- myself.wrapper.find('.pkt_ext_btn').trigger('click');
+ myself.wrapper.find(".pkt_ext_btn").trigger("click");
}
}
- }).on('keyup', 'input', function(e) {
+ }).on("keyup", "input", function(e) {
myself.checkValidTagSubmit();
});
myself.checkPlaceholderStatus();
},
onAdd() {
myself.checkValidTagSubmit();
changestamp = Date.now();
myself.hideInactiveTags();
@@ -227,193 +227,193 @@ var PKT_SAVED_OVERLAY = function(options
},
onShowDropdown() {
thePKT_SAVED.sendMessage("expandSavePanel");
},
onHideDropdown() {
thePKT_SAVED.sendMessage("collapseSavePanel");
}
});
- $('body').on('keydown', function(e) {
+ $("body").on("keydown", function(e) {
var key = e.keyCode || e.which;
if (key == 8) {
- var selected = $('.token-input-selected-token');
+ var selected = $(".token-input-selected-token");
if (selected.length) {
e.preventDefault();
e.stopImmediatePropagation();
- inputwrapper.find('.pkt_ext_tag_input').tokenInput('remove', {name:selected.find('p').text()});
+ inputwrapper.find(".pkt_ext_tag_input").tokenInput("remove", {name:selected.find("p").text()});
}
- } else if ($(e.target).parent().hasClass('token-input-input-token')) {
+ } else if ($(e.target).parent().hasClass("token-input-input-token")) {
e.stopImmediatePropagation();
}
});
};
this.disableInput = function() {
- this.wrapper.find('.pkt_ext_item_actions').addClass('pkt_ext_item_actions_disabled');
- this.wrapper.find('.pkt_ext_btn').addClass('pkt_ext_btn_disabled');
- this.wrapper.find('.pkt_ext_tag_input_wrapper').addClass('pkt_ext_tag_input_wrapper_disabled');
- if (this.wrapper.find('.pkt_ext_suggestedtag_detail').length) {
- this.wrapper.find('.pkt_ext_suggestedtag_detail').addClass('pkt_ext_suggestedtag_detail_disabled');
+ this.wrapper.find(".pkt_ext_item_actions").addClass("pkt_ext_item_actions_disabled");
+ this.wrapper.find(".pkt_ext_btn").addClass("pkt_ext_btn_disabled");
+ this.wrapper.find(".pkt_ext_tag_input_wrapper").addClass("pkt_ext_tag_input_wrapper_disabled");
+ if (this.wrapper.find(".pkt_ext_suggestedtag_detail").length) {
+ this.wrapper.find(".pkt_ext_suggestedtag_detail").addClass("pkt_ext_suggestedtag_detail_disabled");
}
};
this.enableInput = function() {
- this.wrapper.find('.pkt_ext_item_actions').removeClass('pkt_ext_item_actions_disabled');
+ this.wrapper.find(".pkt_ext_item_actions").removeClass("pkt_ext_item_actions_disabled");
this.checkValidTagSubmit();
- this.wrapper.find('.pkt_ext_tag_input_wrapper').removeClass('pkt_ext_tag_input_wrapper_disabled');
- if (this.wrapper.find('.pkt_ext_suggestedtag_detail').length) {
- this.wrapper.find('.pkt_ext_suggestedtag_detail').removeClass('pkt_ext_suggestedtag_detail_disabled');
+ this.wrapper.find(".pkt_ext_tag_input_wrapper").removeClass("pkt_ext_tag_input_wrapper_disabled");
+ if (this.wrapper.find(".pkt_ext_suggestedtag_detail").length) {
+ this.wrapper.find(".pkt_ext_suggestedtag_detail").removeClass("pkt_ext_suggestedtag_detail_disabled");
}
};
this.initAddTagInput = function() {
- $('.pkt_ext_btn').click(function(e) {
+ $(".pkt_ext_btn").click(function(e) {
e.preventDefault();
- if ($(this).hasClass('pkt_ext_btn_disabled') || $('.pkt_ext_edit_msg_active').filter('.pkt_ext_edit_msg_error').length) {
+ if ($(this).hasClass("pkt_ext_btn_disabled") || $(".pkt_ext_edit_msg_active").filter(".pkt_ext_edit_msg_error").length) {
return;
}
myself.disableInput();
- $('.pkt_ext_containersaved').find('.pkt_ext_detail h2').text(myself.dictJSON.processingtags);
+ $(".pkt_ext_containersaved").find(".pkt_ext_detail h2").text(myself.dictJSON.processingtags);
var originaltags = [];
- $('.token-input-token').each(function() {
- var text = $.trim($(this).find('p').text());
+ $(".token-input-token").each(function() {
+ var text = $.trim($(this).find("p").text());
if (text.length) {
originaltags.push(text);
}
});
thePKT_SAVED.sendMessage("addTags",
{
url: myself.savedUrl,
tags: originaltags
}, function(resp) {
- if (resp.status == 'success') {
+ if (resp.status == "success") {
myself.showStateFinalMsg(myself.dictJSON.tagssaved);
- } else if (resp.status == 'error') {
- $('.pkt_ext_edit_msg').addClass('pkt_ext_edit_msg_error pkt_ext_edit_msg_active').text(resp.error.message);
+ } else if (resp.status == "error") {
+ $(".pkt_ext_edit_msg").addClass("pkt_ext_edit_msg_error pkt_ext_edit_msg_active").text(resp.error.message);
}
});
});
};
this.initRemovePageInput = function() {
- $('.pkt_ext_removeitem').click(function(e) {
- if ($(this).parents('.pkt_ext_item_actions_disabled').length) {
+ $(".pkt_ext_removeitem").click(function(e) {
+ if ($(this).parents(".pkt_ext_item_actions_disabled").length) {
e.preventDefault();
return;
}
- if ($(this).hasClass('pkt_ext_removeitem')) {
+ if ($(this).hasClass("pkt_ext_removeitem")) {
e.preventDefault();
myself.disableInput();
- $('.pkt_ext_containersaved').find('.pkt_ext_detail h2').text(myself.dictJSON.processingremove);
+ $(".pkt_ext_containersaved").find(".pkt_ext_detail h2").text(myself.dictJSON.processingremove);
thePKT_SAVED.sendMessage("deleteItem",
{
itemId: myself.savedItemId
}, function(resp) {
- if (resp.status == 'success') {
+ if (resp.status == "success") {
myself.showStateFinalMsg(myself.dictJSON.pageremoved);
- } else if (resp.status == 'error') {
- $('.pkt_ext_edit_msg').addClass('pkt_ext_edit_msg_error pkt_ext_edit_msg_active').text(resp.error.message);
+ } else if (resp.status == "error") {
+ $(".pkt_ext_edit_msg").addClass("pkt_ext_edit_msg_error pkt_ext_edit_msg_active").text(resp.error.message);
}
});
}
});
};
this.initOpenListInput = function() {
- $('.pkt_ext_openpocket').click(function(e) {
+ $(".pkt_ext_openpocket").click(function(e) {
e.preventDefault();
thePKT_SAVED.sendMessage("openTabWithUrl",
{
- url: $(this).attr('href'),
+ url: $(this).attr("href"),
activate: true
});
myself.closePopup();
});
};
this.showTagsError = function(msg) {
- $('.pkt_ext_edit_msg').addClass('pkt_ext_edit_msg_error pkt_ext_edit_msg_active').text(msg);
- $('.pkt_ext_tag_detail').addClass('pkt_ext_tag_error');
+ $(".pkt_ext_edit_msg").addClass("pkt_ext_edit_msg_error pkt_ext_edit_msg_active").text(msg);
+ $(".pkt_ext_tag_detail").addClass("pkt_ext_tag_error");
};
this.hideTagsError = function(msg) {
- $('.pkt_ext_edit_msg').removeClass('pkt_ext_edit_msg_error pkt_ext_edit_msg_active').text('');
- $('.pkt_ext_tag_detail').removeClass('pkt_ext_tag_error');
+ $(".pkt_ext_edit_msg").removeClass("pkt_ext_edit_msg_error pkt_ext_edit_msg_active").text("");
+ $(".pkt_ext_tag_detail").removeClass("pkt_ext_tag_error");
};
this.showActiveTags = function() {
- if (!$('.pkt_ext_suggestedtag_detail').length) {
+ if (!$(".pkt_ext_suggestedtag_detail").length) {
return;
}
- var activetokenstext = '|';
- $('.token-input-token').each(function(index, element) {
- activetokenstext += $(element).find('p').text() + '|';
+ var activetokenstext = "|";
+ $(".token-input-token").each(function(index, element) {
+ activetokenstext += $(element).find("p").text() + "|";
});
- var inactivetags = $('.pkt_ext_suggestedtag_detail').find('.token_tag_inactive');
+ var inactivetags = $(".pkt_ext_suggestedtag_detail").find(".token_tag_inactive");
inactivetags.each(function(index, element) {
- if (activetokenstext.indexOf('|' + $(element).text() + '|') == -1) {
- $(element).removeClass('token_tag_inactive');
+ if (activetokenstext.indexOf("|" + $(element).text() + "|") == -1) {
+ $(element).removeClass("token_tag_inactive");
}
});
};
this.hideInactiveTags = function() {
- if (!$('.pkt_ext_suggestedtag_detail').length) {
+ if (!$(".pkt_ext_suggestedtag_detail").length) {
return;
}
- var activetokenstext = '|';
- $('.token-input-token').each(function(index, element) {
- activetokenstext += $(element).find('p').text() + '|';
+ var activetokenstext = "|";
+ $(".token-input-token").each(function(index, element) {
+ activetokenstext += $(element).find("p").text() + "|";
});
- var activesuggestedtags = $('.token_tag').not('.token_tag_inactive');
+ var activesuggestedtags = $(".token_tag").not(".token_tag_inactive");
activesuggestedtags.each(function(index, element) {
- if (activetokenstext.indexOf('|' + $(element).text() + '|') > -1) {
- $(element).addClass('token_tag_inactive');
+ if (activetokenstext.indexOf("|" + $(element).text() + "|") > -1) {
+ $(element).addClass("token_tag_inactive");
}
});
};
this.showStateSaved = function(initobj) {
- this.wrapper.find('.pkt_ext_detail h2').text(this.dictJSON.pagesaved);
- this.wrapper.find('.pkt_ext_btn').addClass('pkt_ext_btn_disabled');
- if (typeof initobj.item == 'object') {
+ this.wrapper.find(".pkt_ext_detail h2").text(this.dictJSON.pagesaved);
+ this.wrapper.find(".pkt_ext_btn").addClass("pkt_ext_btn_disabled");
+ if (typeof initobj.item == "object") {
this.savedItemId = initobj.item.item_id;
this.savedUrl = initobj.item.given_url;
}
- $('.pkt_ext_containersaved').addClass('pkt_ext_container_detailactive').removeClass('pkt_ext_container_finalstate');
+ $(".pkt_ext_containersaved").addClass("pkt_ext_container_detailactive").removeClass("pkt_ext_container_finalstate");
myself.fillUserTags();
if (myself.suggestedTagsLoaded) {
myself.startCloseTimer();
} else {
myself.fillSuggestedTags();
}
};
this.sanitizeText = function(s) {
var sanitizeMap = {
"&": "&",
"<": "<",
">": ">",
- '"': '"',
- "'": '''
+ '"': """,
+ "'": "'"
};
- if (typeof s !== 'string') {
- return '';
+ if (typeof s !== "string") {
+ return "";
}
return String(s).replace(/[&<>"']/g, function(str) {
return sanitizeMap[str];
});
};
this.showStateFinalMsg = function(msg) {
- this.wrapper.find('.pkt_ext_tag_detail').one('webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd', function(e) {
- $(this).off('webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd');
+ this.wrapper.find(".pkt_ext_tag_detail").one("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd", function(e) {
+ $(this).off("webkitTransitionEnd transitionend msTransitionEnd oTransitionEnd");
myself.preventCloseTimerCancel = true;
myself.startCloseTimer(myself.autocloseTimingFinalState);
- myself.wrapper.find('.pkt_ext_detail h2').text(msg);
+ myself.wrapper.find(".pkt_ext_detail h2").text(msg);
});
- this.wrapper.addClass('pkt_ext_container_finalstate');
+ this.wrapper.addClass("pkt_ext_container_finalstate");
};
this.showStateError = function(headline, detail) {
- this.wrapper.find('.pkt_ext_detail h2').text(headline);
- this.wrapper.find('.pkt_ext_detail h3').text(detail);
- this.wrapper.addClass('pkt_ext_container_detailactive pkt_ext_container_finalstate pkt_ext_container_finalerrorstate');
+ this.wrapper.find(".pkt_ext_detail h2").text(headline);
+ this.wrapper.find(".pkt_ext_detail h3").text(detail);
+ this.wrapper.addClass("pkt_ext_container_detailactive pkt_ext_container_finalstate pkt_ext_container_finalerrorstate");
this.preventCloseTimerCancel = true;
this.startCloseTimer(myself.autocloseTimingFinalState);
}
this.getTranslations = function() {
this.dictJSON = window.pocketStrings;
};
};
@@ -427,42 +427,42 @@ PKT_SAVED_OVERLAY.prototype = {
// set translations
this.getTranslations();
// set host
this.dictJSON.pockethost = this.pockethost;
// extra modifier class for collapsed state
if (this.inoverflowmenu) {
- $('body').addClass('pkt_ext_saved_overflow');
+ $("body").addClass("pkt_ext_saved_overflow");
}
// extra modifier class for language
if (this.locale) {
- $('body').addClass('pkt_ext_saved_' + this.locale);
+ $("body").addClass("pkt_ext_saved_" + this.locale);
}
// Create actual content
- $('body').append(Handlebars.templates.saved_shell(this.dictJSON));
+ $("body").append(Handlebars.templates.saved_shell(this.dictJSON));
// Add in premium content (if applicable based on premium status)
this.createPremiumFunctionality();
// Initialize functionality for overlay
- this.wrapper = $('.pkt_ext_containersaved');
+ this.wrapper = $(".pkt_ext_containersaved");
this.initTagInput();
this.initAddTagInput();
this.initRemovePageInput();
this.initOpenListInput();
this.initAutoCloseEvents();
},
createPremiumFunctionality() {
- if (this.premiumStatus && !$('.pkt_ext_suggestedtag_detail').length) {
- $('body').append(Handlebars.templates.saved_premiumshell(this.dictJSON));
- $('.pkt_ext_initload').append(Handlebars.templates.saved_premiumextras(this.dictJSON));
+ if (this.premiumStatus && !$(".pkt_ext_suggestedtag_detail").length) {
+ $("body").append(Handlebars.templates.saved_premiumshell(this.dictJSON));
+ $(".pkt_ext_initload").append(Handlebars.templates.saved_premiumextras(this.dictJSON));
}
}
};
// Layer between Bookmarklet and Extensions
var PKT_SAVED = function() {};
@@ -484,40 +484,40 @@ PKT_SAVED.prototype = {
sendMessage(messageId, payload, callback) {
pktPanelMessaging.sendMessage(this.panelId, messageId, payload, callback);
},
create() {
var myself = this;
var url = window.location.href.match(/premiumStatus=([\w|\d|\.]*)&?/);
if (url && url.length > 1) {
- myself.overlay.premiumStatus = (url[1] == '1');
+ myself.overlay.premiumStatus = (url[1] == "1");
}
var host = window.location.href.match(/pockethost=([\w|\.]*)&?/);
if (host && host.length > 1) {
myself.overlay.pockethost = host[1];
}
var inoverflowmenu = window.location.href.match(/inoverflowmenu=([\w|\.]*)&?/);
if (inoverflowmenu && inoverflowmenu.length > 1) {
- myself.overlay.inoverflowmenu = (inoverflowmenu[1] == 'true');
+ myself.overlay.inoverflowmenu = (inoverflowmenu[1] == "true");
}
var locale = window.location.href.match(/locale=([\w|\.]*)&?/);
if (locale && locale.length > 1) {
myself.overlay.locale = locale[1].toLowerCase();
}
myself.overlay.create();
// tell back end we're ready
thePKT_SAVED.sendMessage("show");
// wait confirmation of save before flipping to final saved state
thePKT_SAVED.addMessageListener("saveLink", function(resp) {
- if (resp.status == 'error') {
- if (typeof resp.error == 'object') {
+ if (resp.status == "error") {
+ if (typeof resp.error == "object") {
if (resp.error.localizedKey) {
myself.overlay.showStateError(myself.overlay.dictJSON.pagenotsaved, myself.overlay.dictJSON[resp.error.localizedKey]);
} else {
myself.overlay.showStateError(myself.overlay.dictJSON.pagenotsaved, resp.error.message);
}
} else {
myself.overlay.showStateError(myself.overlay.dictJSON.pagenotsaved, myself.overlay.dictJSON.errorgeneric);
}
@@ -536,16 +536,16 @@ PKT_SAVED.prototype = {
window.thePKT_SAVED = thePKT_SAVED;
thePKT_SAVED.init();
}
var pocketHost = thePKT_SAVED.overlay.pockethost;
// send an async message to get string data
thePKT_SAVED.sendMessage("initL10N", {
tos: [
- 'https://' + pocketHost + '/tos?s=ffi&t=tos&tv=panel_tryit',
- 'https://' + pocketHost + '/privacy?s=ffi&t=privacypolicy&tv=panel_tryit'
+ "https://" + pocketHost + "/tos?s=ffi&t=tos&tv=panel_tryit",
+ "https://" + pocketHost + "/privacy?s=ffi&t=privacypolicy&tv=panel_tryit"
]
}, function(resp) {
window.pocketStrings = resp.strings;
window.thePKT_SAVED.create();
});
});
--- a/browser/extensions/pocket/content/panels/js/signup.js
+++ b/browser/extensions/pocket/content/panels/js/signup.js
@@ -4,52 +4,52 @@ It does not contain any logic for saving
*/
var PKT_SIGNUP_OVERLAY = function(options) {
var myself = this;
this.inited = false;
this.active = false;
this.delayedStateSaved = false;
this.wrapper = null;
this.variant = window.___PKT__SIGNUP_VARIANT;
- this.tagline = window.___PKT__SIGNUP_TAGLINE || '';
+ this.tagline = window.___PKT__SIGNUP_TAGLINE || "";
this.preventCloseTimerCancel = false;
this.translations = {};
this.closeValid = true;
this.mouseInside = false;
this.autocloseTimer = null;
this.variant = "";
this.inoverflowmenu = false;
this.controlvariant;
this.pockethost = "getpocket.com";
this.fxasignedin = false;
this.dictJSON = {};
this.initCloseTabEvents = function() {
- $('.btn,.pkt_ext_learnmore,.alreadyhave > a').click(function(e) {
+ $(".btn,.pkt_ext_learnmore,.alreadyhave > a").click(function(e) {
e.preventDefault();
thePKT_SIGNUP.sendMessage("openTabWithUrl",
{
- url: $(this).attr('href'),
+ url: $(this).attr("href"),
activate: true
});
myself.closePopup();
});
};
this.closePopup = function() {
thePKT_SIGNUP.sendMessage("close");
};
this.sanitizeText = function(s) {
var sanitizeMap = {
"&": "&",
"<": "<",
">": ">",
- '"': '"',
- "'": '''
+ '"': """,
+ "'": "'"
};
- if (typeof s !== 'string') {
- return '';
+ if (typeof s !== "string") {
+ return "";
}
return String(s).replace(/[&<>"']/g, function(str) {
return sanitizeMap[str];
});
};
this.getTranslations = function() {
this.dictJSON = window.pocketStrings;
};
@@ -63,60 +63,60 @@ PKT_SIGNUP_OVERLAY.prototype = {
this.controlvariant = controlvariant[1];
}
var variant = window.location.href.match(/variant=([\w|\.]*)&?/);
if (variant && variant.length > 1) {
this.variant = variant[1];
}
var fxasignedin = window.location.href.match(/fxasignedin=([\w|\d|\.]*)&?/);
if (fxasignedin && fxasignedin.length > 1) {
- this.fxasignedin = (fxasignedin[1] == '1');
+ this.fxasignedin = (fxasignedin[1] == "1");
}
var host = window.location.href.match(/pockethost=([\w|\.]*)&?/);
if (host && host.length > 1) {
this.pockethost = host[1];
}
var inoverflowmenu = window.location.href.match(/inoverflowmenu=([\w|\.]*)&?/);
if (inoverflowmenu && inoverflowmenu.length > 1) {
- this.inoverflowmenu = (inoverflowmenu[1] == 'true');
+ this.inoverflowmenu = (inoverflowmenu[1] == "true");
}
var locale = window.location.href.match(/locale=([\w|\.]*)&?/);
if (locale && locale.length > 1) {
this.locale = locale[1].toLowerCase();
}
if (this.active) {
return;
}
this.active = true;
// set translations
this.getTranslations();
this.dictJSON.fxasignedin = this.fxasignedin ? 1 : 0;
- this.dictJSON.controlvariant = this.controlvariant == 'true' ? 1 : 0;
- this.dictJSON.variant = (this.variant ? this.variant : 'undefined');
- this.dictJSON.variant += this.fxasignedin ? '_fxa' : '_nonfxa';
+ this.dictJSON.controlvariant = this.controlvariant == "true" ? 1 : 0;
+ this.dictJSON.variant = (this.variant ? this.variant : "undefined");
+ this.dictJSON.variant += this.fxasignedin ? "_fxa" : "_nonfxa";
this.dictJSON.pockethost = this.pockethost;
this.dictJSON.showlearnmore = true;
// extra modifier class for collapsed state
if (this.inoverflowmenu) {
- $('body').addClass('pkt_ext_signup_overflow');
+ $("body").addClass("pkt_ext_signup_overflow");
}
// extra modifier class for language
if (this.locale) {
- $('body').addClass('pkt_ext_signup_' + this.locale);
+ $("body").addClass("pkt_ext_signup_" + this.locale);
}
// Create actual content
- if (this.variant == 'overflow') {
- $('body').append(Handlebars.templates.signup_shell(this.dictJSON));
+ if (this.variant == "overflow") {
+ $("body").append(Handlebars.templates.signup_shell(this.dictJSON));
} else {
- $('body').append(Handlebars.templates.signupstoryboard_shell(this.dictJSON));
+ $("body").append(Handlebars.templates.signupstoryboard_shell(this.dictJSON));
}
// tell background we're ready
thePKT_SIGNUP.sendMessage("show");
// close events
this.initCloseTabEvents();
@@ -160,16 +160,16 @@ PKT_SIGNUP.prototype = {
window.thePKT_SIGNUP = thePKT_SIGNUP;
thePKT_SIGNUP.init();
}
var pocketHost = thePKT_SIGNUP.overlay.pockethost;
// send an async message to get string data
thePKT_SIGNUP.sendMessage("initL10N", {
tos: [
- 'https://' + pocketHost + '/tos?s=ffi&t=tos&tv=panel_tryit',
- 'https://' + pocketHost + '/privacy?s=ffi&t=privacypolicy&tv=panel_tryit'
+ "https://" + pocketHost + "/tos?s=ffi&t=tos&tv=panel_tryit",
+ "https://" + pocketHost + "/privacy?s=ffi&t=privacypolicy&tv=panel_tryit"
]
}, function(resp) {
window.pocketStrings = resp.strings;
window.thePKT_SIGNUP.create();
});
});
--- a/browser/extensions/pocket/content/pktApi.jsm
+++ b/browser/extensions/pocket/content/pktApi.jsm
@@ -171,42 +171,42 @@ var pktApi = (function() {
/**
* Returns access token or undefined if no logged in user was found
* @return {string | undefined} Access token for logged in user user
*/
function getAccessToken() {
var pocketCookies = getCookiesFromPocket();
// If no cookie was found just return undefined
- if (typeof pocketCookies['ftv1'] === "undefined") {
+ if (typeof pocketCookies["ftv1"] === "undefined") {
return undefined;
}
// Check if a new user logged in in the meantime and clearUserData if so
- var sessionId = pocketCookies['fsv1'];
- var lastSessionId = getSetting('fsv1');
+ var sessionId = pocketCookies["fsv1"];
+ var lastSessionId = getSetting("fsv1");
if (sessionId !== lastSessionId) {
clearUserData();
setSetting("fsv1", sessionId);
}
// Return access token
- return pocketCookies['ftv1'];
+ return pocketCookies["ftv1"];
}
/**
* Get the current premium status of the user
* @return {number | undefined} Premium status of user
*/
function getPremiumStatus() {
var premiumStatus = getSetting("premium_status");
if (typeof premiumStatus === "undefined") {
// Premium status is not in settings try get it from cookie
var pocketCookies = getCookiesFromPocket();
- premiumStatus = pocketCookies['ps'];
+ premiumStatus = pocketCookies["ps"];
}
return premiumStatus;
}
/**
* Helper method to check if a user is premium or not
* @return {Boolean} Boolean if user is premium or not
*/
@@ -287,18 +287,18 @@ var pktApi = (function() {
}
var error = {message: errorMessage};
options.error(error, request);
}
}
};
// Set headers
- request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- request.setRequestHeader('X-Accept', ' application/json');
+ request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
+ request.setRequestHeader("X-Accept", " application/json");
// Serialize and Fire off the request
var str = [];
for (var p in data) {
if (data.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(data[p]));
}
}
@@ -325,17 +325,17 @@ var pktApi = (function() {
* Add a new link to Pocket
* @param {string} url URL of the link
* @param {Object | undefined} options Can provide a string-based title, a
* `success` callback and an `error` callback.
* @return {Boolean} Returns Boolean whether the api call started sucessfully
*/
function addLink(url, options) {
- var since = getSetting('latestSince');
+ var since = getSetting("latestSince");
var accessToken = getAccessToken();
var sendData = {
access_token: accessToken,
url,
since: since ? since : 0
};
@@ -347,28 +347,28 @@ var pktApi = (function() {
path: "/firefox/save",
data: sendData,
success(data) {
// Update premium status, tags and since
var tags = data.tags;
if ((typeof tags !== "undefined") && Array.isArray(tags)) {
// If a tagslist is in the response replace the tags
- setSetting('tags', JSON.stringify(data.tags));
+ setSetting("tags", JSON.stringify(data.tags));
}
// Update premium status
var premiumStatus = data.premium_status;
if (typeof premiumStatus !== "undefined") {
// If a premium_status is in the response replace the premium_status
setSetting("premium_status", premiumStatus);
}
// Save since value for further requests
- setSetting('latestSince', data.since);
+ setSetting("latestSince", data.since);
if (options.success) {
options.success.apply(options, Array.apply(null, arguments));
}
},
error: options.error
});
}
@@ -397,17 +397,17 @@ var pktApi = (function() {
* with further data to send to the
* API. Can have success and error
* callbacks
* @return {Boolean} Returns Boolean whether the api call started sucessfully
*/
function sendAction(action, options) {
// Options can have an 'actionInfo' object. This actionInfo object gets
// passed through to the action object that will be send to the API endpoint
- if (typeof options.actionInfo !== 'undefined') {
+ if (typeof options.actionInfo !== "undefined") {
action = extend(action, options.actionInfo);
}
return sendActions([action], options);
}
/**
* General function to send all kinds of actions like adding of links or
* removing of items via the API
@@ -603,22 +603,22 @@ var pktApi = (function() {
error: options.error
});
}
/**
* Helper function to get current signup AB group the user is in
*/
function getSignupPanelTabTestVariant() {
- return getMultipleTestOption('panelSignUp', {control: 1, v1: 8, v2: 1 })
+ return getMultipleTestOption("panelSignUp", {control: 1, v1: 8, v2: 1 })
}
function getMultipleTestOption(testName, testOptions) {
// Get the test from preferences if we've already assigned the user to a test
- var settingName = 'test.' + testName;
+ var settingName = "test." + testName;
var assignedValue = getSetting(settingName);
var valArray = [];
// If not assigned yet, pick and store a value
if (!assignedValue) {
// Get a weighted array of test variants from the testOptions object
Object.keys(testOptions).forEach(function(key) {
for (var i = 0; i < testOptions[key]; i++) {
--- a/browser/extensions/presentation/content/PresentationDevicePrompt.jsm
+++ b/browser/extensions/presentation/content/PresentationDevicePrompt.jsm
@@ -162,17 +162,17 @@ PresentationPermissionPrompt.prototype =
this.request.cancel(Cr.NS_ERROR_NOT_AVAILABLE);
},
dismiss: true,
}];
},
// PRIVATE APIs
get _domainName() {
if (this.principal.URI instanceof Ci.nsIFileURL) {
- return this.principal.URI.path.split('/')[1];
+ return this.principal.URI.path.split("/")[1];
}
return this.principal.URI.hostPort;
},
_createPopupContent() {
log("_createPopupContent");
if (!this._devices.length) {
log("No available devices can be listed!");
--- a/browser/modules/AttributionCode.jsm
+++ b/browser/modules/AttributionCode.jsm
@@ -3,24 +3,24 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
this.EXPORTED_SYMBOLS = ["AttributionCode"];
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, 'AppConstants',
- 'resource://gre/modules/AppConstants.jsm');
-XPCOMUtils.defineLazyModuleGetter(this, 'OS',
- 'resource://gre/modules/osfile.jsm');
-XPCOMUtils.defineLazyModuleGetter(this, 'Services',
- 'resource://gre/modules/Services.jsm');
-XPCOMUtils.defineLazyModuleGetter(this, 'Task',
- 'resource://gre/modules/Task.jsm');
+XPCOMUtils.defineLazyModuleGetter(this, "AppConstants",
+ "resource://gre/modules/AppConstants.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "OS",
+ "resource://gre/modules/osfile.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Services",
+ "resource://gre/modules/Services.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
const ATTR_CODE_MAX_LENGTH = 200;
const ATTR_CODE_KEYS_REGEX = /^source|medium|campaign|content$/;
const ATTR_CODE_VALUE_REGEX = /[a-zA-Z0-9_%\\-\\.\\(\\)]*/;
const ATTR_CODE_FIELD_SEPARATOR = "%26"; // URL-encoded &
const ATTR_CODE_KEY_VALUE_SEPARATOR = "%3D"; // URL-encoded =
let gCachedAttrData = null;
--- a/browser/modules/BrowserUsageTelemetry.jsm
+++ b/browser/modules/BrowserUsageTelemetry.jsm
@@ -367,17 +367,17 @@ let BrowserUsageTelemetry = {
if (isOneOff) {
if (!KNOWN_ONEOFF_SOURCES.includes(source)) {
// Silently drop the error if this bogus call
// came from 'urlbar' or 'searchbar'. They're
// calling |recordSearch| twice from two different
// code paths because they want to record the search
// in SEARCH_COUNTS.
- if (['urlbar', 'searchbar'].includes(source)) {
+ if (["urlbar", "searchbar"].includes(source)) {
Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS").add(countId);
return;
}
throw new Error("Unknown source for one-off search: " + source);
}
} else {
if (!KNOWN_SEARCH_SOURCES.includes(source)) {
throw new Error("Unknown source for search: " + source);
--- a/browser/modules/DirectoryLinksProvider.jsm
+++ b/browser/modules/DirectoryLinksProvider.jsm
@@ -35,17 +35,17 @@ XPCOMUtils.defineLazyGetter(this, "gText
return new TextDecoder();
});
XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
});
XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = 'utf8';
+ converter.charset = "utf8";
return converter;
});
// The filename where directory links are stored locally
const DIRECTORY_LINKS_FILE = "directoryLinks.json";
const DIRECTORY_LINKS_TYPE = "application/json";
@@ -594,21 +594,21 @@ var DirectoryLinksProvider = {
base = Services.eTLD.getBaseDomain(uri);
} catch (ex) {}
// Require a scheme match and the base only if desired
return allowed.has(scheme) && (!checkBase || ALLOWED_URL_BASE.has(base));
},
_escapeChars(text) {
let charMap = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": '''
+ "&": "&",
+ "<": "<",
+ ">": ">",
+ '"': """,
+ "'": "'"
};
return text.replace(/[&<>"']/g, (character) => charMap[character]);
},
/**
* Gets the current set of directory links.
* @param aCallback The function that the array of links is passed to.
--- a/browser/modules/FormSubmitObserver.jsm
+++ b/browser/modules/FormSubmitObserver.jsm
@@ -196,23 +196,23 @@ FormSubmitObserver.prototype =
// Note, this is relative to the browser and needs to be translated
// in chrome.
panelData.contentRect = BrowserUtils.getElementBoundingRect(aElement);
// We want to show the popup at the middle of checkbox and radio buttons
// and where the content begin for the other elements.
let offset = 0;
- if (aElement.tagName == 'INPUT' &&
- (aElement.type == 'radio' || aElement.type == 'checkbox')) {
+ if (aElement.tagName == "INPUT" &&
+ (aElement.type == "radio" || aElement.type == "checkbox")) {
panelData.position = "bottomcenter topleft";
} else {
let win = aElement.ownerGlobal;
let style = win.getComputedStyle(aElement, null);
- if (style.direction == 'rtl') {
+ if (style.direction == "rtl") {
offset = parseInt(style.paddingRight) + parseInt(style.borderRightWidth);
} else {
offset = parseInt(style.paddingLeft) + parseInt(style.borderLeftWidth);
}
let zoomFactor = this._getWindowUtils().fullZoom;
panelData.offset = Math.round(offset * zoomFactor);
panelData.position = "after_start";
}
--- a/browser/modules/PermissionUI.jsm
+++ b/browser/modules/PermissionUI.jsm
@@ -67,22 +67,22 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "SitePermissions",
"resource:///modules/SitePermissions.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm");
XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
return Services.strings
- .createBundle('chrome://branding/locale/brand.properties');
+ .createBundle("chrome://branding/locale/brand.properties");
});
XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
return Services.strings
- .createBundle('chrome://browser/locale/browser.properties');
+ .createBundle("chrome://browser/locale/browser.properties");
});
this.PermissionUI = {};
/**
* PermissionPromptPrototype should be subclassed by callers that
* want to display prompts to the user. See each method and property
* below for guidance on what to override.
@@ -333,17 +333,17 @@ this.PermissionPromptPrototype = {
}
let mainAction = popupNotificationActions.length ?
popupNotificationActions[0] : null;
let secondaryActions = popupNotificationActions.splice(1);
let options = this.popupOptions;
- if (!options.hasOwnProperty('displayURI') || options.displayURI) {
+ if (!options.hasOwnProperty("displayURI") || options.displayURI) {
options.displayURI = this.principal.URI;
}
// Permission prompts are always persistent and don't have a close button.
options.persistent = true;
options.hideClose = true;
this.onBeforeShow();
chromeWin.PopupNotifications.show(this.browser,
--- a/browser/modules/PluginContent.jsm
+++ b/browser/modules/PluginContent.jsm
@@ -534,21 +534,21 @@ PluginContent.prototype = {
case "PluginDisabled":
let manageLink = this.getPluginUI(plugin, "managePluginsLink");
this.addLinkClickCallback(manageLink, "forwardCallback", "managePlugins");
shouldShowNotification = true;
break;
case "PluginInstantiated":
let key = this._getPluginInfo(plugin).pluginTag.niceName;
- Services.telemetry.getKeyedHistogramById('PLUGIN_ACTIVATION_COUNT').add(key);
+ Services.telemetry.getKeyedHistogramById("PLUGIN_ACTIVATION_COUNT").add(key);
shouldShowNotification = true;
let pluginRect = plugin.getBoundingClientRect();
if (pluginRect.width <= 5 && pluginRect.height <= 5) {
- Services.telemetry.getHistogramById('PLUGIN_TINY_CONTENT').add(1);
+ Services.telemetry.getHistogramById("PLUGIN_TINY_CONTENT").add(1);
}
break;
}
if (this._getPluginInfo(plugin).mimetype === FLASH_MIME_TYPE) {
this._recordFlashPluginTelemetry(eventType, plugin);
}
@@ -597,35 +597,35 @@ PluginContent.prototype = {
if (!this.flashPluginStats.plugins.has(plugin)) {
// Reporting plugin instance and its dimensions only once.
this.flashPluginStats.plugins.add(plugin);
this.flashPluginStats.instancesCount++;
let pluginRect = plugin.getBoundingClientRect();
- Services.telemetry.getHistogramById('FLASH_PLUGIN_WIDTH')
+ Services.telemetry.getHistogramById("FLASH_PLUGIN_WIDTH")
.add(pluginRect.width);
- Services.telemetry.getHistogramById('FLASH_PLUGIN_HEIGHT')
+ Services.telemetry.getHistogramById("FLASH_PLUGIN_HEIGHT")
.add(pluginRect.height);
- Services.telemetry.getHistogramById('FLASH_PLUGIN_AREA')
+ Services.telemetry.getHistogramById("FLASH_PLUGIN_AREA")
.add(pluginRect.width * pluginRect.height);
let state = this._getPluginInfo(plugin).fallbackType;
if (state === null) {
state = Ci.nsIObjectLoadingContent.PLUGIN_UNSUPPORTED;
}
- Services.telemetry.getHistogramById('FLASH_PLUGIN_STATES')
+ Services.telemetry.getHistogramById("FLASH_PLUGIN_STATES")
.add(state);
}
},
_finishRecordingFlashPluginTelemetry() {
if (this.flashPluginStats) {
- Services.telemetry.getHistogramById('FLASH_PLUGIN_INSTANCES_ON_PAGE')
+ Services.telemetry.getHistogramById("FLASH_PLUGIN_INSTANCES_ON_PAGE")
.add(this.flashPluginStats.instancesCount);
delete this.flashPluginStats;
}
},
isKnownPlugin(objLoadingContent) {
return (objLoadingContent.getContentTypeForMIMEType(objLoadingContent.actualType) ==
Ci.nsIObjectLoadingContent.TYPE_PLUGIN);
@@ -732,18 +732,18 @@ PluginContent.prototype = {
onOverlayClick(event) {
let document = event.target.ownerDocument;
let plugin = document.getBindingParent(event.target);
let contentWindow = plugin.ownerGlobal.top;
let overlay = this.getPluginUI(plugin, "main");
// Have to check that the target is not the link to update the plugin
if (!(event.originalTarget instanceof contentWindow.HTMLAnchorElement) &&
- (event.originalTarget.getAttribute('anonid') != 'closeIcon') &&
- !overlay.hasAttribute('dismissed') &&
+ (event.originalTarget.getAttribute("anonid") != "closeIcon") &&
+ !overlay.hasAttribute("dismissed") &&
event.button == 0 &&
event.isTrusted) {
this._showClickToPlayNotification(plugin, true);
event.stopPropagation();
event.preventDefault();
}
},
@@ -987,17 +987,17 @@ PluginContent.prototype = {
/**
* Traverses down iframes until it find a non-iframe full screen DOM element.
* @param fullScreenIframe
* Target iframe to begin searching from.
* @returns DOM element
* The full screen DOM element contained within the iframe (could be inner iframe), or the original iframe if no inner DOM element is found.
**/
let getTrueFullScreenElement = fullScreenIframe => {
- if (typeof fullScreenIframe.contentDocument !== 'undefined' && fullScreenIframe.contentDocument.mozFullScreenElement) {
+ if (typeof fullScreenIframe.contentDocument !== "undefined" && fullScreenIframe.contentDocument.mozFullScreenElement) {
return getTrueFullScreenElement(fullScreenIframe.contentDocument.mozFullScreenElement);
}
return fullScreenIframe;
}
if (fullScreenElement.tagName === "IFRAME") {
fullScreenElement = getTrueFullScreenElement(fullScreenElement);
}
--- a/browser/modules/Social.jsm
+++ b/browser/modules/Social.jsm
@@ -228,18 +228,18 @@ this.OpenGraphBuilder = {
generateEndpointURL(URLTemplate, pageData) {
// support for existing oexchange style endpoints by supporting their
// querystring arguments. parse the query string template and do
// replacements where necessary the query names may be different than ours,
// so we could see u=%{url} or url=%{url}
let [endpointURL, queryString] = URLTemplate.split("?");
let query = {};
if (queryString) {
- queryString.split('&').forEach(function(val) {
- let [name, value] = val.split('=');
+ queryString.split("&").forEach(function(val) {
+ let [name, value] = val.split("=");
let p = /%\{(.+)\}/.exec(value);
if (!p) {
// preserve non-template query vars
query[name] = value;
} else if (pageData[p[1]]) {
if (p[1] == "previews")
query[name] = pageData[p[1]][0];
else
--- a/browser/modules/SocialService.jsm
+++ b/browser/modules/SocialService.jsm
@@ -70,17 +70,17 @@ var SocialServiceInternal = {
return pref;
}
} catch (err) {
Cu.reportError("SocialService: failed to load manifest: " + pref +
", exception: " + err);
}
}
let originUri = Services.io.newURI(origin);
- return originUri.hostPort.replace('.', '-');
+ return originUri.hostPort.replace(".", "-");
},
orderedProviders(aCallback) {
if (SocialServiceInternal.providerArray.length < 2) {
schedule(function() {
aCallback(SocialServiceInternal.providerArray);
});
return;
}
@@ -153,17 +153,17 @@ XPCOMUtils.defineLazyGetter(SocialServic
function getOriginActivationType(origin) {
// if this is an about uri, treat it as a directory
let URI = Services.io.newURI(origin);
let principal = Services.scriptSecurityManager.createCodebasePrincipal(URI, {});
if (Services.scriptSecurityManager.isSystemPrincipal(principal) || origin == "moz-safe-about:home") {
return "internal";
}
- let directories = Services.prefs.getCharPref("social.directories").split(',');
+ let directories = Services.prefs.getCharPref("social.directories").split(",");
if (directories.indexOf(origin) >= 0)
return "directory";
return "foreign";
}
var ActiveProviders = {
get _providers() {
@@ -492,39 +492,39 @@ this.SocialService = {
listener(topic, origin, providers);
} catch (ex) {
Components.utils.reportError("SocialService: provider listener threw an exception: " + ex);
}
}
},
_manifestFromData(type, data, installOrigin) {
- let featureURLs = ['shareURL'];
- let resolveURLs = featureURLs.concat(['postActivationURL']);
+ let featureURLs = ["shareURL"];
+ let resolveURLs = featureURLs.concat(["postActivationURL"]);
- if (type == 'directory' || type == 'internal') {
+ if (type == "directory" || type == "internal") {
// directory provided manifests must have origin in manifest, use that
- if (!data['origin']) {
+ if (!data["origin"]) {
Cu.reportError("SocialService.manifestFromData directory service provided manifest without origin.");
return null;
}
installOrigin = data.origin;
}
// force/fixup origin
let URI = Services.io.newURI(installOrigin);
let principal = Services.scriptSecurityManager.createCodebasePrincipal(URI, {});
data.origin = principal.origin;
// iconURL and name are required
let providerHasFeatures = featureURLs.some(url => data[url]);
if (!providerHasFeatures) {
Cu.reportError("SocialService.manifestFromData manifest missing required urls.");
return null;
}
- if (!data['name'] || !data['iconURL']) {
+ if (!data["name"] || !data["iconURL"]) {
Cu.reportError("SocialService.manifestFromData manifest missing name or iconURL.");
return null;
}
for (let url of resolveURLs) {
if (data[url]) {
try {
let resolved = Services.io.newURI(principal.URI.resolve(data[url]));
if (!(resolved.schemeIs("http") || resolved.schemeIs("https"))) {
--- a/browser/modules/WindowsPreviewPerTab.jsm
+++ b/browser/modules/WindowsPreviewPerTab.jsm
@@ -271,17 +271,17 @@ PreviewController.prototype = {
let winWidth = this.win.width;
let winHeight = this.win.height;
let composite = PageThumbs.createCanvas();
// Use transparency, Aero glass is drawn black without it.
composite.mozOpaque = false;
- let ctx = composite.getContext('2d');
+ let ctx = composite.getContext("2d");
let scale = this.screenPixelsPerCSSPixel / this.zoom;
composite.width = winWidth * scale;
composite.height = winHeight * scale;
ctx.save();
ctx.scale(scale, scale);
--- a/browser/modules/offlineAppCache.jsm
+++ b/browser/modules/offlineAppCache.jsm
@@ -1,15 +1,15 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
this.EXPORTED_SYMBOLS = ["OfflineAppCacheHelper"];
-Components.utils.import('resource://gre/modules/LoadContextInfo.jsm');
+Components.utils.import("resource://gre/modules/LoadContextInfo.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
this.OfflineAppCacheHelper = {
clear() {
var cacheService = Cc["@mozilla.org/netwerk/cache-storage-service;1"].getService(Ci.nsICacheStorageService);
var appCacheStorage = cacheService.appCacheStorage(LoadContextInfo.default, null);
--- a/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js
+++ b/browser/modules/test/browser_BrowserUITelemetry_syncedtabs.js
@@ -81,17 +81,17 @@ add_task(function* test_menu() {
"synced-tabs": { open: { "toolbarbutton-subview": 1 } },
});
});
add_task(function* test_sidebar() {
// Reset BrowserUITelemetry's world.
BUIT._countableEvents = {};
- yield SidebarUI.show('viewTabsSidebar');
+ yield SidebarUI.show("viewTabsSidebar");
let syncedTabsDeckComponent = SidebarUI.browser.contentWindow.syncedTabsDeckComponent;
syncedTabsDeckComponent._accountStatus = () => Promise.resolve(true);
// Once the tabs container has been selected (which here means "'selected'
// added to the class list") we are ready to test.
let container = SidebarUI.browser.contentDocument.querySelector(".tabs-container");
--- a/browser/modules/test/browser_SelfSupportBackend.js
+++ b/browser/modules/test/browser_SelfSupportBackend.js
@@ -29,20 +29,20 @@ function sendSessionRestoredNotification
/**
* Find a browser, with an IFRAME as parent, who has aURL as the source attribute.
*
* @param aURL The URL to look for to identify the browser.
*
* @returns {Object} The browser element or null on failure.
*/
function findSelfSupportBrowser(aURL) {
- let frames = Services.appShell.hiddenDOMWindow.document.querySelectorAll('iframe');
+ let frames = Services.appShell.hiddenDOMWindow.document.querySelectorAll("iframe");
for (let frame of frames) {
try {
- let browser = frame.contentDocument.getElementById("win").querySelectorAll('browser')[0];
+ let browser = frame.contentDocument.getElementById("win").querySelectorAll("browser")[0];
let url = browser.getAttribute("src");
if (url == aURL) {
return browser;
}
} catch (e) {
continue;
}
}
--- a/browser/modules/test/browser_UsageTelemetry_content.js
+++ b/browser/modules/test/browser_UsageTelemetry_content.js
@@ -72,17 +72,17 @@ add_task(function* test_context_menu() {
info("Validate the search metrics.");
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_CONTEXT_MENU, "search", 1);
Assert.equal(Object.keys(scalars[SCALAR_CONTEXT_MENU]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.contextmenu', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.contextmenu", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "contextmenu", null, {engine: "other-MozSearch"}]]);
contextMenu.hidePopup();
yield BrowserTestUtils.removeTab(gBrowser.selectedTab);
@@ -108,17 +108,17 @@ add_task(function* test_about_newtab() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_ABOUT_NEWTAB, "search_enter", 1);
Assert.equal(Object.keys(scalars[SCALAR_ABOUT_NEWTAB]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.newtab', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.newtab", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "about_newtab", "enter", {engine: "other-MozSearch"}]]);
yield BrowserTestUtils.removeTab(tab);
});
--- a/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js
+++ b/browser/modules/test/browser_UsageTelemetry_content_aboutHome.js
@@ -72,17 +72,17 @@ add_task(function* test_abouthome_simple
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_ABOUT_HOME, "search_enter", 1);
Assert.equal(Object.keys(scalars[SCALAR_ABOUT_HOME]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.abouthome', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.abouthome", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "about_home", "enter", {engine: "other-MozSearch"}]]);
yield BrowserTestUtils.removeTab(tab);
});
--- a/browser/modules/test/browser_UsageTelemetry_searchbar.js
+++ b/browser/modules/test/browser_UsageTelemetry_searchbar.js
@@ -98,17 +98,17 @@ add_task(function* test_plainQuery() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_enter", 1);
Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.searchbar', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.searchbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "searchbar", "enter", {engine: "other-MozSearch"}]]);
yield BrowserTestUtils.removeTab(tab);
});
@@ -132,17 +132,17 @@ add_task(function* test_oneOff() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_oneoff", 1);
Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch2.searchbar', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch2.searchbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "searchbar", "oneoff", {engine: "other-MozSearch2"}]]);
yield BrowserTestUtils.removeTab(tab);
});
@@ -177,18 +177,18 @@ add_task(function* test_suggestion() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_SEARCHBAR, "search_suggestion", 1);
Assert.equal(Object.keys(scalars[SCALAR_SEARCHBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- let searchEngineId = 'other-' + suggestionEngine.name;
- checkKeyedHistogram(search_hist, searchEngineId + '.searchbar', 1);
+ let searchEngineId = "other-" + suggestionEngine.name;
+ checkKeyedHistogram(search_hist, searchEngineId + ".searchbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "searchbar", "suggestion", {engine: searchEngineId}]]);
Services.search.currentEngine = previousEngine;
Services.search.removeEngine(suggestionEngine);
--- a/browser/modules/test/browser_UsageTelemetry_urlbar.js
+++ b/browser/modules/test/browser_UsageTelemetry_urlbar.js
@@ -117,17 +117,17 @@ add_task(function* test_simpleQuery() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_URLBAR, "search_enter", 1);
Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.urlbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "urlbar", "enter", {engine: "other-MozSearch"}]]);
// Check the histograms as well.
let resultIndexes = resultIndexHist.snapshot();
@@ -162,17 +162,17 @@ add_task(function* test_searchAlias() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_URLBAR, "search_alias", 1);
Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.urlbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "urlbar", "alias", {engine: "other-MozSearch"}]]);
// Check the histograms as well.
let resultIndexes = resultIndexHist.snapshot();
@@ -210,17 +210,17 @@ add_task(function* test_oneOff() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_URLBAR, "search_oneoff", 1);
Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- checkKeyedHistogram(search_hist, 'other-MozSearch.urlbar', 1);
+ checkKeyedHistogram(search_hist, "other-MozSearch.urlbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "urlbar", "oneoff", {engine: "other-MozSearch"}]]);
// Check the histograms as well.
let resultIndexes = resultIndexHist.snapshot();
@@ -269,18 +269,18 @@ add_task(function* test_suggestion() {
// Check if the scalars contain the expected values.
const scalars = getParentProcessScalars(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, true, false);
checkKeyedScalar(scalars, SCALAR_URLBAR, "search_suggestion", 1);
Assert.equal(Object.keys(scalars[SCALAR_URLBAR]).length, 1,
"This search must only increment one entry in the scalar.");
// Make sure SEARCH_COUNTS contains identical values.
- let searchEngineId = 'other-' + suggestionEngine.name;
- checkKeyedHistogram(search_hist, searchEngineId + '.urlbar', 1);
+ let searchEngineId = "other-" + suggestionEngine.name;
+ checkKeyedHistogram(search_hist, searchEngineId + ".urlbar", 1);
// Also check events.
let events = Services.telemetry.snapshotBuiltinEvents(Ci.nsITelemetry.DATASET_RELEASE_CHANNEL_OPTIN, false);
events = events.filter(e => e[1] == "navigation" && e[2] == "search");
checkEvents(events, [["navigation", "search", "urlbar", "suggestion", {engine: searchEngineId}]]);
// Check the histograms as well.
let resultIndexes = resultIndexHist.snapshot();
--- a/browser/modules/test/browser_bug1319078.js
+++ b/browser/modules/test/browser_bug1319078.js
@@ -1,14 +1,14 @@
"use strict";
-var gInvalidFormPopup = document.getElementById('invalid-form-popup');
+var gInvalidFormPopup = document.getElementById("invalid-form-popup");
function checkPopupHide() {
- ok(gInvalidFormPopup.state != 'showing' && gInvalidFormPopup.state != 'open',
+ ok(gInvalidFormPopup.state != "showing" && gInvalidFormPopup.state != "open",
"[Test " + testId + "] The invalid form popup should not be shown");
}
var testId = 0;
function incrementTest() {
testId++;
info("Starting next part of test");
@@ -18,32 +18,32 @@ function incrementTest() {
* In this test, we check that no popup appears if the element display is none.
*/
add_task(function* () {
ok(gInvalidFormPopup,
"The browser should have a popup to show when a form is invalid");
incrementTest();
let testPage =
- 'data:text/html,' +
+ "data:text/html," +
'<form target="t"><input type="url" placeholder="url" value="http://" style="display: none;"><input id="s" type="button" value="check"></form>';
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
yield BrowserTestUtils.synthesizeMouse("#s", 0, 0, {}, gBrowser.selectedBrowser);
checkPopupHide();
yield BrowserTestUtils.removeTab(tab);
});
/**
* In this test, we check that no popup appears if the element visibility is hidden.
*/
add_task(function* () {
incrementTest();
let testPage =
- 'data:text/html,' +
+ "data:text/html," +
'<form target="t"><input type="url" placeholder="url" value="http://" style="visibility: hidden;"><input id="s" type="button" value="check"></form>';
let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, testPage);
yield BrowserTestUtils.synthesizeMouse("#s", 0, 0, {}, gBrowser.selectedBrowser);
checkPopupHide();
yield BrowserTestUtils.removeTab(tab);
});
--- a/browser/modules/test/xpcshell/test_AttributionCode.js
+++ b/browser/modules/test/xpcshell/test_AttributionCode.js
@@ -2,17 +2,17 @@
* http://creativecommons.org/publicdomain/zero/1.0/
*/
"use strict";
const {interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/AppConstants.jsm");
Cu.import("resource:///modules/AttributionCode.jsm");
-Cu.import('resource://gre/modules/osfile.jsm');
+Cu.import("resource://gre/modules/osfile.jsm");
Cu.import("resource://gre/modules/Services.jsm");
let validAttrCodes = [
{code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D(not%20set)%26content%3D(not%20set)",
parsed: {"source": "google.com", "medium": "organic",
"campaign": "(not%20set)", "content": "(not%20set)"}},
{code: "source%3Dgoogle.com%26medium%3Dorganic%26campaign%3D%26content%3D",
parsed: {"source": "google.com", "medium": "organic"}},
--- a/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
+++ b/browser/modules/test/xpcshell/test_DirectoryLinksProvider.js
@@ -26,17 +26,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://testing-common/PlacesTestUtils.jsm");
do_get_profile();
const DIRECTORY_LINKS_FILE = "directoryLinks.json";
const DIRECTORY_FRECENCY = 1000;
const SUGGESTED_FRECENCY = Infinity;
const kURLData = {"directory": [{"url":"http://example.com", "title":"LocalSource"}]};
-const kTestURL = 'data:application/json,' + JSON.stringify(kURLData);
+const kTestURL = "data:application/json," + JSON.stringify(kURLData);
// DirectoryLinksProvider preferences
const kLocalePref = DirectoryLinksProvider._observedPrefs.prefSelectedLocale;
const kSourceUrlPref = DirectoryLinksProvider._observedPrefs.linksURL;
const kPingUrlPref = "browser.newtabpage.directory.ping";
const kNewtabEnhancedPref = "browser.newtabpage.enhanced";
// httpd settings
@@ -290,17 +290,17 @@ add_task(function test_shouldUpdateSugge
DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
});
add_task(function* test_updateSuggestedTile() {
let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
// Initial setup
let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
let testObserver = new TestFirstRun();
DirectoryLinksProvider.addObserver(testObserver);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
@@ -416,17 +416,17 @@ add_task(function* test_updateSuggestedT
yield promiseCleanDirectoryLinksProvider();
NewTabUtils.isTopPlacesSite = origIsTopPlacesSite;
NewTabUtils.getProviderLinks = origGetProviderLinks;
DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
});
add_task(function* test_suggestedLinksMap() {
let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3, suggestedTile4], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
// Ensure the suggested tiles were not considered directory tiles.
do_check_eq(links.length, 1);
let expected_data = [{url: "http://someothersite.com", title: "Not_A_Suggested_Site", frecency: DIRECTORY_FRECENCY, lastVisitDate: 1}];
isIdentical(links, expected_data);
@@ -470,17 +470,17 @@ add_task(function* test_topSitesWithSugg
NewTabUtils.getProviderLinks = function(provider) {
return [];
}
// We start off with no top sites with suggested links.
do_check_eq(DirectoryLinksProvider._topSitesWithSuggestedLinks.size, 0);
let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
yield fetchData();
// Check we've populated suggested links as expected.
do_check_eq(DirectoryLinksProvider._suggestedLinks.size, 5);
// When many sites change, we update _topSitesWithSuggestedLinks as expected.
@@ -796,17 +796,17 @@ add_task(function* test_DirectoryLinksPr
let links = yield fetchData();
do_check_eq(links.length, 1);
let expectedData = [{url: "http://example.com", title: "LocalSource", frecency: DIRECTORY_FRECENCY, lastVisitDate: 1}];
isIdentical(links, expectedData);
// tests these 2 things:
// 1. _linksURL is properly set after the pref change
// 2. invalid source url is correctly handled
- let exampleUrl = 'http://localhost:56789/bad';
+ let exampleUrl = "http://localhost:56789/bad";
yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, exampleUrl);
do_check_eq(DirectoryLinksProvider._linksURL, exampleUrl);
// since the download fail, the directory file must remain the same
let newLinks = yield fetchData();
isIdentical(newLinks, expectedData);
// now remove the file, and re-download
@@ -818,31 +818,31 @@ add_task(function* test_DirectoryLinksPr
yield promiseCleanDirectoryLinksProvider();
});
add_task(function* test_DirectoryLinksProvider_getLinks_noDirectoryData() {
let data = {
"directory": [],
};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
do_check_eq(links.length, 0);
yield promiseCleanDirectoryLinksProvider();
});
add_task(function* test_DirectoryLinksProvider_getLinks_badData() {
let data = {
"en-US": {
"en-US": [{url: "http://example.com", title: "US"}],
},
};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
// Make sure we get nothing for incorrectly formatted data
let links = yield fetchData();
do_check_eq(links.length, 0);
yield promiseCleanDirectoryLinksProvider();
});
@@ -965,17 +965,17 @@ add_task(function* test_DirectoryLinksPr
{url: "ftp://example.com"},
{url: "http://example.net"},
{url: "javascript:5"},
{url: "https://example.com"},
{url: "httpJUNKjavascript:42"},
{url: "data:text/plain,hi"},
{url: "http/bork:eh"},
]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
do_check_eq(links.length, 2);
// The only remaining url should be http and https
do_check_eq(links[0].url, data["directory"][1].url);
do_check_eq(links[1].url, data["directory"][3].url);
@@ -986,17 +986,17 @@ add_task(function* test_DirectoryLinksPr
{url: "http://example.com", imageURI: "ftp://example.com"},
{url: "http://example.com", imageURI: "http://example.net"},
{url: "http://example.com", imageURI: "javascript:5"},
{url: "http://example.com", imageURI: "https://example.com"},
{url: "http://example.com", imageURI: "httpJUNKjavascript:42"},
{url: "http://example.com", imageURI: "data:text/plain,hi"},
{url: "http://example.com", imageURI: "http/bork:eh"},
]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
do_check_eq(links.length, 2);
// The only remaining images should be https and data
do_check_eq(links[0].imageURI, data["directory"][3].imageURI);
do_check_eq(links[1].imageURI, data["directory"][5].imageURI);
@@ -1005,17 +1005,17 @@ add_task(function* test_DirectoryLinksPr
add_task(function* test_DirectoryLinksProvider_getAllowedImages_base() {
let data = {"directory": [
{url: "http://example1.com", imageURI: "https://example.com"},
{url: "http://example2.com", imageURI: "https://tiles.cdn.mozilla.net"},
{url: "http://example3.com", imageURI: "https://tiles2.cdn.mozilla.net"},
{url: "http://example4.com", enhancedImageURI: "https://mozilla.net"},
{url: "http://example5.com", imageURI: "data:text/plain,hi"},
]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
// Pretend we're using the default pref to trigger base matching
DirectoryLinksProvider.__linksURLModified = false;
let links = yield fetchData();
do_check_eq(links.length, 4);
@@ -1031,34 +1031,34 @@ add_task(function* test_DirectoryLinksPr
{url: "http://example.com", enhancedImageURI: "ftp://example.com"},
{url: "http://example.com", enhancedImageURI: "http://example.net"},
{url: "http://example.com", enhancedImageURI: "javascript:5"},
{url: "http://example.com", enhancedImageURI: "https://example.com"},
{url: "http://example.com", enhancedImageURI: "httpJUNKjavascript:42"},
{url: "http://example.com", enhancedImageURI: "data:text/plain,hi"},
{url: "http://example.com", enhancedImageURI: "http/bork:eh"},
]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
do_check_eq(links.length, 2);
// The only remaining enhancedImages should be http and https and data
do_check_eq(links[0].enhancedImageURI, data["directory"][3].enhancedImageURI);
do_check_eq(links[1].enhancedImageURI, data["directory"][5].enhancedImageURI);
});
add_task(function* test_DirectoryLinksProvider_getEnhancedLink() {
let data = {"enhanced": [
{url: "http://example.net", enhancedImageURI: "data:,net1"},
{url: "http://example.com", enhancedImageURI: "data:,com1"},
{url: "http://example.com", enhancedImageURI: "data:,com2"},
]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
do_check_eq(links.length, 0); // There are no directory links.
function checkEnhanced(url, image) {
let enhanced = DirectoryLinksProvider.getEnhancedLink({url});
do_check_eq(enhanced && enhanced.enhancedImageURI, image);
@@ -1086,17 +1086,17 @@ add_task(function* test_DirectoryLinksPr
checkEnhanced("http://example.org", undefined);
checkEnhanced("http://localhost", undefined);
checkEnhanced("http://127.0.0.1", undefined);
// Make sure old data is not cached
data = {"enhanced": [
{url: "http://example.com", enhancedImageURI: "data:,fresh"},
]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
+ dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
links = yield fetchData();
do_check_eq(links.length, 0); // There are no directory links.
checkEnhanced("http://example.net", undefined);
checkEnhanced("http://example.com", "data:,fresh");
});
add_task(function* test_DirectoryLinksProvider_enhancedURIs() {
@@ -1108,17 +1108,17 @@ add_task(function* test_DirectoryLinksPr
let data = {
"suggested": [
{url: "http://example.net", enhancedImageURI: "data:,net1", title:"SuggestedTitle", adgroup_name: "Test", frecent_sites: ["test.com"]}
],
"directory": [
{url: "http://example.net", enhancedImageURI: "data:,net2", title:"DirectoryTitle"}
]
};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
// Wait for links to get loaded
let gLinks = NewTabUtils.links;
gLinks.addProvider(DirectoryLinksProvider);
gLinks.populateCache();
yield new Promise(resolve => {
NewTabUtils.allPages.register({
@@ -1182,17 +1182,17 @@ add_task(function* test_timeSensetiveSug
start: startDate.toISOString(),
end: endDate.toISOString(),
}
}, suggestedTile1);
// Initial setup
let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
let data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
let testObserver = new TestTimingRun();
DirectoryLinksProvider.addObserver(testObserver);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
@@ -1253,17 +1253,17 @@ add_task(function* test_timeSensetiveSug
do_check_eq(DirectoryLinksProvider._updateSuggestedTile(), undefined);
// set links back to contain directory tile only
links.shift();
// drop the end time - we should pick up the tile
suggestedTile.time_limits.end = null;
data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
+ dataURI = "data:application/json," + JSON.stringify(data);
// redownload json and getLinks to force time recomputation
yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
// ensure that there's a link returned by _updateSuggestedTile and no timeout
let deferred = Promise.defer();
DirectoryLinksProvider.getLinks(() => {
let link = DirectoryLinksProvider._updateSuggestedTile();
@@ -1275,17 +1275,17 @@ add_task(function* test_timeSensetiveSug
});
yield deferred.promise;
// repeat the test for end time only
suggestedTile.time_limits.start = null;
suggestedTile.time_limits.end = (new Date(Date.now() + 3000)).toISOString();
data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
+ dataURI = "data:application/json," + JSON.stringify(data);
// redownload json and call getLinks() to force time recomputation
yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
// ensure that there's a link returned by _updateSuggestedTile and timeout set
deferred = Promise.defer();
DirectoryLinksProvider.getLinks(() => {
let link = DirectoryLinksProvider._updateSuggestedTile();
@@ -1598,17 +1598,17 @@ add_task(function* test_DirectoryLinksPr
add_task(function test_DirectoryLinksProvider_anonymous() {
do_check_true(DirectoryLinksProvider._newXHR().mozAnon);
});
add_task(function* test_sanitizeExplanation() {
// Note: this is a basic test to ensure we applied sanitization to the link explanation.
// Full testing for appropriate sanitization is done in parser/xml/test/unit/test_sanitizer.js.
let data = {"suggested": [suggestedTile5]};
- let dataURI = 'data:application/json,' + encodeURIComponent(JSON.stringify(data));
+ let dataURI = "data:application/json," + encodeURIComponent(JSON.stringify(data));
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
yield fetchData();
let suggestedSites = [...DirectoryLinksProvider._suggestedLinks.keys()];
do_check_eq(suggestedSites.indexOf("eviltarget.com"), 0);
do_check_eq(suggestedSites.length, 1);
@@ -1620,17 +1620,17 @@ add_task(function* test_sanitizeExplanat
add_task(function* test_inadjecentSites() {
let suggestedTile = Object.assign({
check_inadjacency: true
}, suggestedTile1);
// Initial setup
let topSites = ["1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
let data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
let testObserver = new TestFirstRun();
DirectoryLinksProvider.addObserver(testObserver);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
@@ -1654,17 +1654,17 @@ add_task(function* test_inadjecentSites(
// loading inadjacent sites list function
function setInadjacentSites(sites) {
let badSiteB64 = [];
sites.forEach(site => {
badSiteB64.push(DirectoryLinksProvider._generateHash(site));
});
let theList = {"domains": badSiteB64};
- let uri = 'data:application/json,' + JSON.stringify(theList);
+ let uri = "data:application/json," + JSON.stringify(theList);
DirectoryLinksProvider._inadjacentSitesUrl = uri;
return DirectoryLinksProvider._loadInadjacentSites();
}
// setup gLinks loader
let gLinks = NewTabUtils.links;
gLinks.addProvider(DirectoryLinksProvider);
@@ -1745,17 +1745,17 @@ add_task(function* test_inadjecentSites(
// there should be no suggested link
link = DirectoryLinksProvider._updateSuggestedTile();
do_check_false(link);
do_check_true(DirectoryLinksProvider._newTabHasInadjacentSite);
// remove avoidInadjacentSites flag from suggested tile and reload json
delete suggestedTile.check_inadjacency;
data = {"suggested": [suggestedTile], "directory": [someOtherSite]};
- dataURI = 'data:application/json,' + JSON.stringify(data);
+ dataURI = "data:application/json," + JSON.stringify(data);
yield promiseDirectoryDownloadOnPrefChange(kSourceUrlPref, dataURI);
yield fetchData();
// inadjacent checking should be disabled
do_check_false(DirectoryLinksProvider._avoidInadjacentSites);
link = DirectoryLinksProvider._updateSuggestedTile();
do_check_true(link);
do_check_eq(link.url, "http://turbotax.com");
@@ -1790,17 +1790,17 @@ add_task(function* test_inadjecentSites(
DirectoryLinksProvider._getCurrentTopSiteCount = origCurrentTopSiteCount;
yield promiseCleanDirectoryLinksProvider();
});
add_task(function* test_blockSuggestedTiles() {
// Initial setup
let topSites = ["site0.com", "1040.com", "site2.com", "hrblock.com", "site4.com", "freetaxusa.com", "site6.com"];
let data = {"suggested": [suggestedTile1, suggestedTile2, suggestedTile3], "directory": [someOtherSite]};
- let dataURI = 'data:application/json,' + JSON.stringify(data);
+ let dataURI = "data:application/json," + JSON.stringify(data);
yield promiseSetupDirectoryLinksProvider({linksURL: dataURI});
let links = yield fetchData();
let origIsTopPlacesSite = NewTabUtils.isTopPlacesSite;
NewTabUtils.isTopPlacesSite = function(site) {
return topSites.indexOf(site) >= 0;
}
--- a/services/cloudsync/CloudSyncBookmarks.jsm
+++ b/services/cloudsync/CloudSyncBookmarks.jsm
@@ -550,17 +550,17 @@ var RootFolder = function(rootId, rootNa
} else if (item.__exists__ && item.deleted) {
deletedItems.push(item);
} else if (item.__exists__) {
updatedItems.push(item);
}
}
for (let item of items) {
- if (!item || 'object' !== typeof(item)) {
+ if (!item || "object" !== typeof(item)) {
continue;
}
let promise = exists(item).then(handleSortedItem, Promise.reject.bind(Promise));
promises.push(promise);
}
return Promise.all(promises);
@@ -676,27 +676,27 @@ var RootFolder = function(rootId, rootNa
deferred.resolve();
return deferred.promise;
};
let handleItemChanged = function(id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) {
let deferred = Promise.defer();
- eventSource.emit('change', guid);
+ eventSource.emit("change", guid);
deferred.resolve();
return deferred.promise;
};
let handleItemMoved = function(id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) {
let deferred = Promise.defer();
function complete() {
- eventSource.emit('move', guid);
+ eventSource.emit("move", guid);
deferred.resolve();
}
if (PlacesUtils.bookmarks.TYPE_FOLDER != type) {
complete();
return deferred.promise;
}
--- a/services/cloudsync/CloudSyncTabs.jsm
+++ b/services/cloudsync/CloudSyncTabs.jsm
@@ -83,17 +83,17 @@ TabCache.prototype = {
throw new Error("unable to update client: " + e);
}
} else {
cRecord = new ClientRecord(client);
this.clients.set(cRecord.id, cRecord);
}
for (let tab of tabs) {
- if (!tab || 'object' !== typeof(tab)) {
+ if (!tab || "object" !== typeof(tab)) {
continue;
}
let tRecord;
if (this.tabs.has(tab.url)) {
tRecord = this.tabs.get(tab.url);
try {
tRecord.update(tab);
--- a/services/common/blocklist-updater.js
+++ b/services/common/blocklist-updater.js
@@ -3,17 +3,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
this.EXPORTED_SYMBOLS = ["checkVersions", "addTestBlocklistClient"];
const { classes: Cc, Constructor: CC, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
-Cu.importGlobalProperties(['fetch']);
+Cu.importGlobalProperties(["fetch"]);
const BlocklistClients = Cu.import("resource://services-common/blocklist-clients.js", {});
const PREF_SETTINGS_SERVER = "services.settings.server";
const PREF_BLOCKLIST_CHANGES_PATH = "services.blocklist.changes.path";
const PREF_BLOCKLIST_LAST_UPDATE = "services.blocklist.last_update_seconds";
const PREF_BLOCKLIST_LAST_ETAG = "services.blocklist.last_etag";
const PREF_BLOCKLIST_CLOCK_SKEW_SECONDS = "services.blocklist.clock_skew_seconds";
--- a/services/common/hawkclient.js
+++ b/services/common/hawkclient.js
@@ -66,17 +66,17 @@ XPCOMUtils.defineLazyGetter(this, "log",
log.error(e);
}
return log;
});
// A boolean to indicate if personally identifiable information (or anything
// else sensitive, such as credentials) should be logged.
-XPCOMUtils.defineLazyGetter(this, 'logPII', function() {
+XPCOMUtils.defineLazyGetter(this, "logPII", function() {
try {
return Services.prefs.getBoolPref(PREF_LOG_SENSITIVE_DETAILS);
} catch (_) {
return false;
}
});
/*
--- a/services/common/rest.js
+++ b/services/common/rest.js
@@ -315,17 +315,17 @@ RESTRequest.prototype = {
this.channel = channel;
channel.loadFlags |= this.loadFlags;
channel.notificationCallbacks = this;
this._log.debug(`${method} request to ${this.uri.spec}`);
// Set request headers.
let headers = this._headers;
for (let key in headers) {
- if (key == 'authorization') {
+ if (key == "authorization") {
this._log.trace("HTTP Header " + key + ": ***** (suppressed)");
} else {
this._log.trace("HTTP Header " + key + ": " + headers[key]);
}
channel.setRequestHeader(key, headers[key], false);
}
// Set HTTP request body.
--- a/services/common/tests/unit/test_blocklist_certificates.js
+++ b/services/common/tests/unit/test_blocklist_certificates.js
@@ -45,17 +45,17 @@ add_task(function* test_something() {
if (!sample) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sample.status.status,
sample.status.statusText);
// send the headers
for (let headerLine of sample.sampleHeaders) {
- let headerElements = headerLine.split(':');
+ let headerElements = headerLine.split(":");
response.setHeader(headerElements[0], headerElements[1].trimLeft());
}
response.setHeader("Date", (new Date()).toUTCString());
response.write(sample.responseBody);
} catch (e) {
do_print(e);
}
--- a/services/common/tests/unit/test_blocklist_clients.js
+++ b/services/common/tests/unit/test_blocklist_clients.js
@@ -85,17 +85,17 @@ function run_test() {
if (!sample) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sample.status.status,
sample.status.statusText);
// send the headers
for (let headerLine of sample.sampleHeaders) {
- let headerElements = headerLine.split(':');
+ let headerElements = headerLine.split(":");
response.setHeader(headerElements[0], headerElements[1].trimLeft());
}
response.setHeader("Date", (new Date()).toUTCString());
response.write(sample.responseBody);
response.finish();
} catch (e) {
do_print(e);
--- a/services/common/tests/unit/test_blocklist_pinning.js
+++ b/services/common/tests/unit/test_blocklist_pinning.js
@@ -70,17 +70,17 @@ add_task(function* test_something() {
if (!sample) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sample.status.status,
sample.status.statusText);
// send the headers
for (let headerLine of sample.sampleHeaders) {
- let headerElements = headerLine.split(':');
+ let headerElements = headerLine.split(":");
response.setHeader(headerElements[0], headerElements[1].trimLeft());
}
response.setHeader("Date", (new Date()).toUTCString());
response.write(sample.responseBody);
} catch (e) {
do_print(e);
}
--- a/services/common/tests/unit/test_blocklist_signatures.js
+++ b/services/common/tests/unit/test_blocklist_signatures.js
@@ -126,17 +126,17 @@ add_task(function* test_check_signatures
if (!sampled) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sampled.status.status,
sampled.status.statusText);
// send the headers
for (let headerLine of sampled.sampleHeaders) {
- let headerElements = headerLine.split(':');
+ let headerElements = headerLine.split(":");
response.setHeader(headerElements[0], headerElements[1].trimLeft());
}
// set the server date
response.setHeader("Date", (new Date(serverTimeMillis)).toUTCString());
response.write(sampled.responseBody);
}
@@ -151,17 +151,17 @@ add_task(function* test_check_signatures
}
}
// First, perform a signature verification with known data and signature
// to ensure things are working correctly
let verifier = Cc["@mozilla.org/security/contentsignatureverifier;1"]
.createInstance(Ci.nsIContentSignatureVerifier);
- const emptyData = '[]';
+ const emptyData = "[]";
const emptySignature = "p384ecdsa=zbugm2FDitsHwk5-IWsas1PpWwY29f0Fg5ZHeqD8fzep7AVl2vfcaHA7LdmCZ28qZLOioGKvco3qT117Q4-HlqFTJM7COHzxGyU2MMJ0ZTnhJrPOC1fP3cVQjU1PTWi9";
const name = "onecrl.content-signature.mozilla.org";
ok(verifier.verifyContentSignature(emptyData, emptySignature,
getCertChain(), name));
verifier = Cc["@mozilla.org/security/contentsignatureverifier;1"]
.createInstance(Ci.nsIContentSignatureVerifier);
--- a/services/common/tests/unit/test_blocklist_updater.js
+++ b/services/common/tests/unit/test_blocklist_updater.js
@@ -19,17 +19,17 @@ add_task(function* test_check_maybeSync(
if (!sampled) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sampled.status.status,
sampled.status.statusText);
// send the headers
for (let headerLine of sampled.sampleHeaders) {
- let headerElements = headerLine.split(':');
+ let headerElements = headerLine.split(":");
response.setHeader(headerElements[0], headerElements[1].trimLeft());
}
// set the server date
response.setHeader("Date", (new Date(serverTimeMillis)).toUTCString());
response.write(sampled.responseBody);
} catch (e) {
--- a/services/common/tests/unit/test_hawkrequest.js
+++ b/services/common/tests/unit/test_hawkrequest.js
@@ -88,19 +88,19 @@ add_test(function test_hawk_authenticate
// millisecond values.
let then = 34329600000;
let clockSkew = 120000;
let timeOffset = -1 * clockSkew;
let localTime = then + clockSkew;
// Set the accept-languages pref to the Nepalese dialect of Zulu.
- let acceptLanguage = Cc['@mozilla.org/supports-string;1'].createInstance(Ci.nsISupportsString);
- acceptLanguage.data = 'zu-NP'; // omit trailing ';', which our HTTP libs snip
- Services.prefs.setComplexValue('intl.accept_languages', Ci.nsISupportsString, acceptLanguage);
+ let acceptLanguage = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
+ acceptLanguage.data = "zu-NP"; // omit trailing ';', which our HTTP libs snip
+ Services.prefs.setComplexValue("intl.accept_languages", Ci.nsISupportsString, acceptLanguage);
let credentials = {
id: "eyJleHBpcmVzIjogMTM2NTAxMDg5OC4x",
key: "qTZf4ZFpAMpMoeSsX3zVRjiqmNs=",
algorithm: "sha256"
};
let server = httpd_setup({
--- a/services/common/tests/unit/test_kinto.js
+++ b/services/common/tests/unit/test_kinto.js
@@ -294,17 +294,17 @@ add_task(function* test_kinto_sync() {
if (!sampled) {
do_throw(`unexpected ${request.method} request for ${request.path}?${request.queryString}`);
}
response.setStatusLine(null, sampled.status.status,
sampled.status.statusText);
// send the headers
for (let headerLine of sampled.sampleHeaders) {
- let headerElements = headerLine.split(':');
+ let headerElements = headerLine.split(":");
response.setHeader(headerElements[0], headerElements[1].trimLeft());
}
response.setHeader("Date", (new Date()).toUTCString());
response.write(sampled.responseBody);
} catch (e) {
dump(`${e}\n`);
}
--- a/services/crypto/modules/WeaveCrypto.js
+++ b/services/crypto/modules/WeaveCrypto.js
@@ -5,17 +5,17 @@
this.EXPORTED_SYMBOLS = ["WeaveCrypto"];
var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://services-common/async.js");
-Cu.importGlobalProperties(['crypto']);
+Cu.importGlobalProperties(["crypto"]);
const CRYPT_ALGO = "AES-CBC";
const CRYPT_ALGO_LENGTH = 256;
const AES_CBC_IV_SIZE = 16;
const OPERATIONS = { ENCRYPT: 0, DECRYPT: 1 };
const UTF_LABEL = "utf-8";
const KEY_DERIVATION_ALGO = "PBKDF2";
@@ -51,18 +51,18 @@ WeaveCrypto.prototype = {
this.prefBranch = Services.prefs.getBranch("services.sync.log.");
this.prefBranch.addObserver("cryptoDebug", this.observer, false);
this.observer._self = this;
try {
this.debug = this.prefBranch.getBoolPref("cryptoDebug");
} catch (x) {
this.debug = false;
}
- XPCOMUtils.defineLazyGetter(this, 'encoder', () => new TextEncoder(UTF_LABEL));
- XPCOMUtils.defineLazyGetter(this, 'decoder', () => new TextDecoder(UTF_LABEL, { fatal: true }));
+ XPCOMUtils.defineLazyGetter(this, "encoder", () => new TextEncoder(UTF_LABEL));
+ XPCOMUtils.defineLazyGetter(this, "decoder", () => new TextDecoder(UTF_LABEL, { fatal: true }));
},
log(message) {
if (!this.debug) {
return;
}
dump("WeaveCrypto: " + message + "\n");
Services.console.logStringMessage("WeaveCrypto: " + message);
--- a/services/crypto/modules/utils.js
+++ b/services/crypto/modules/utils.js
@@ -216,17 +216,17 @@ this.CryptoUtils = {
/* Encode i into 4 octets: _INT */
let I = [];
I[0] = String.fromCharCode((i >> 24) & 0xff);
I[1] = String.fromCharCode((i >> 16) & 0xff);
I[2] = String.fromCharCode((i >> 8) & 0xff);
I[3] = String.fromCharCode(i & 0xff);
- U[0] = CryptoUtils.digestBytes(S + I.join(''), h);
+ U[0] = CryptoUtils.digestBytes(S + I.join(""), h);
for (let j = 1; j < c; j++) {
U[j] = CryptoUtils.digestBytes(U[j - 1], h);
}
ret = U[0];
for (let j = 1; j < c; j++) {
ret = CommonUtils.byteArrayToString(XOR(ret, U[j]));
}
--- a/services/crypto/tests/unit/test_crypto_crypt.js
+++ b/services/crypto/tests/unit/test_crypto_crypt.js
@@ -1,10 +1,10 @@
Cu.import("resource://services-crypto/WeaveCrypto.js");
-Cu.importGlobalProperties(['crypto']);
+Cu.importGlobalProperties(["crypto"]);
var cryptoSvc = new WeaveCrypto();
add_task(function* test_key_memoization() {
let cryptoGlobal = cryptoSvc._getCrypto();
let oldImport = cryptoGlobal.subtle.importKey;
if (!oldImport) {
_("Couldn't swizzle crypto.subtle.importKey; returning.");
--- a/services/crypto/tests/unit/test_utils_pbkdf2.js
+++ b/services/crypto/tests/unit/test_utils_pbkdf2.js
@@ -1,13 +1,13 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
// XXX until bug 937114 is fixed
-Cu.importGlobalProperties(['btoa']);
+Cu.importGlobalProperties(["btoa"]);
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://services-common/utils.js");
var {bytesAsHex: b2h} = CommonUtils;
function run_test() {
run_next_test();
}
--- a/services/fxaccounts/Credentials.jsm
+++ b/services/fxaccounts/Credentials.jsm
@@ -85,17 +85,17 @@ this.Credentials = Object.freeze({
* @param {String} email The email of the user.
*
* @return {bitArray} the salt combination with the namespace
*
* Note that PROTOCOL_VERSION does not refer in any way to the version of the
* Firefox Accounts API.
*/
keyWordExtended(name, email) {
- return CommonUtils.stringToBytes(PROTOCOL_VERSION + name + ':' + email);
+ return CommonUtils.stringToBytes(PROTOCOL_VERSION + name + ":" + email);
},
setup(emailInput, passwordInput, options = {}) {
let deferred = Promise.defer();
log.debug("setup credentials for " + emailInput);
let hkdfSalt = options.hkdfSalt || HKDF_SALT;
let hkdfLength = options.hkdfLength || HKDF_LENGTH;
--- a/services/fxaccounts/FxAccounts.jsm
+++ b/services/fxaccounts/FxAccounts.jsm
@@ -710,17 +710,17 @@ FxAccountsInternal.prototype = {
if (!data) {
return false;
}
return this.fxAccountsClient.accountStatus(data.uid);
});
},
checkVerificationStatus() {
- log.trace('checkVerificationStatus');
+ log.trace("checkVerificationStatus");
let currentState = this.currentAccountState;
return currentState.getUserAccountData().then(data => {
if (!data) {
log.trace("checkVerificationStatus - no user data");
return null;
}
// Always check the verification status, even if the local state indicates
@@ -886,17 +886,17 @@ FxAccountsInternal.prototype = {
}
currentState.whenKeysReadyDeferred.resolve(dataWithKeys);
},
(err) => {
currentState.whenKeysReadyDeferred.reject(err);
}
);
} else {
- currentState.whenKeysReadyDeferred.reject('No keyFetchToken');
+ currentState.whenKeysReadyDeferred.reject("No keyFetchToken");
}
}
return currentState.whenKeysReadyDeferred.promise;
}).catch(err =>
this._handleTokenError(err)
).then(result => currentState.resolve(result));
},
@@ -1598,18 +1598,18 @@ FxAccountsInternal.prototype = {
return this.fxaPushService.registerPushEndpoint().then(subscription => {
const deviceName = this._getDeviceName();
let deviceOptions = {};
// if we were able to obtain a subscription
if (subscription && subscription.endpoint) {
deviceOptions.pushCallback = subscription.endpoint;
- let publicKey = subscription.getKey('p256dh');
- let authKey = subscription.getKey('auth');
+ let publicKey = subscription.getKey("p256dh");
+ let authKey = subscription.getKey("auth");
if (publicKey && authKey) {
deviceOptions.pushPublicKey = urlsafeBase64Encode(publicKey);
deviceOptions.pushAuthKey = urlsafeBase64Encode(authKey);
}
}
if (signedInUser.deviceId) {
log.debug("updating existing device details");
--- a/services/fxaccounts/FxAccountsCommon.js
+++ b/services/fxaccounts/FxAccountsCommon.js
@@ -18,17 +18,17 @@ const PREF_LOG_LEVEL = "identity.fxaccou
const PREF_LOG_LEVEL_DUMP = "identity.fxaccounts.log.appender.dump";
// A pref that can be set so "sensitive" information (eg, personally
// identifiable info, credentials, etc) will be logged.
const PREF_LOG_SENSITIVE_DETAILS = "identity.fxaccounts.log.sensitive";
var exports = Object.create(null);
-XPCOMUtils.defineLazyGetter(exports, 'log', function() {
+XPCOMUtils.defineLazyGetter(exports, "log", function() {
let log = Log.repository.getLogger("FirefoxAccounts");
// We set the log level to debug, but the default dump appender is set to
// the level reflected in the pref. Other code that consumes FxA may then
// choose to add another appender at a different level.
log.level = Log.Level.Debug;
let appender = new Log.DumpAppender();
appender.level = Log.Level.Error;
@@ -49,17 +49,17 @@ XPCOMUtils.defineLazyGetter(exports, 'lo
log.error(e);
}
return log;
});
// A boolean to indicate if personally identifiable information (or anything
// else sensitive, such as credentials) should be logged.
-XPCOMUtils.defineLazyGetter(exports, 'logPII', function() {
+XPCOMUtils.defineLazyGetter(exports, "logPII", function() {
try {
return Services.prefs.getBoolPref(PREF_LOG_SENSITIVE_DETAILS);
} catch (_) {
return false;
}
});
exports.FXACCOUNTS_PERMISSION = "firefox-accounts";
--- a/services/fxaccounts/FxAccountsOAuthGrantClient.jsm
+++ b/services/fxaccounts/FxAccountsOAuthGrantClient.jsm
@@ -161,17 +161,17 @@ this.FxAccountsOAuthGrantClient.prototyp
}));
}
// "response.success" means status code is 200
if (request.response.success) {
return resolve(body);
}
- if (typeof body.errno === 'number') {
+ if (typeof body.errno === "number") {
// Offset oauth server errnos to avoid conflict with other FxA server errnos
body.errno += OAUTH_SERVER_ERRNO_OFFSET;
} else if (body.errno) {
body.errno = ERRNO_UNKNOWN_ERROR;
}
return reject(new FxAccountsOAuthGrantClientError(body));
};
--- a/services/fxaccounts/FxAccountsStorage.jsm
+++ b/services/fxaccounts/FxAccountsStorage.jsm
@@ -29,17 +29,17 @@ function FxAccountsStorageManagerCanStor
this.FxAccountsStorageManager = function(options = {}) {
this.options = {
filename: options.filename || DEFAULT_STORAGE_FILENAME,
baseDir: options.baseDir || OS.Constants.Path.profileDir,
}
this.plainStorage = new JSONStorage(this.options);
// On b2g we have no loginManager for secure storage, and tests may want
// to pretend secure storage isn't available.
- let useSecure = 'useSecure' in options ? options.useSecure : haveLoginManager;
+ let useSecure = "useSecure" in options ? options.useSecure : haveLoginManager;
if (useSecure) {
this.secureStorage = new LoginManagerStorage();
} else {
this.secureStorage = null;
}
this._clearCachedData();
// See .initialize() below - this protects against it not being called.
this._promiseInitialized = Promise.reject("initialize not called");
@@ -145,17 +145,17 @@ this.FxAccountsStorageManager.prototype
// data is returned except for "in memory" fields. Note that not specifying
// field names will soon be deprecated/removed - we want all callers to
// specify the fields they care about.
getAccountData: Task.async(function* (fieldNames = null) {
yield this._promiseInitialized;
// We know we are initialized - this means our .cachedPlain is accurate
// and doesn't need to be read (it was read if necessary by initialize).
// So if there's no uid, there's no user signed in.
- if (!('uid' in this.cachedPlain)) {
+ if (!("uid" in this.cachedPlain)) {
return null;
}
let result = {};
if (fieldNames === null) {
// The "old" deprecated way of fetching a logged in user.
for (let [name, value] of Object.entries(this.cachedPlain)) {
result[name] = value;
}
@@ -200,22 +200,22 @@ this.FxAccountsStorageManager.prototype
}
return result;
}),
// Update just the specified fields. This DOES NOT allow you to change to
// a different user, nor to set the user as signed-out.
updateAccountData: Task.async(function* (newFields) {
yield this._promiseInitialized;
- if (!('uid' in this.cachedPlain)) {
+ if (!("uid" in this.cachedPlain)) {
// If this storage instance shows no logged in user, then you can't
// update fields.
throw new Error("No user is logged in");
}
- if (!newFields || 'uid' in newFields || 'email' in newFields) {
+ if (!newFields || "uid" in newFields || "email" in newFields) {
// Once we support
// user changing email address this may need to change, but it's not
// clear how we would be told of such a change anyway...
throw new Error("Can't change uid or email address");
}
log.debug("_updateAccountData with items", Object.keys(newFields));
// work out what bucket.
for (let [name, value] of Object.entries(newFields)) {
--- a/services/fxaccounts/FxAccountsWebChannel.jsm
+++ b/services/fxaccounts/FxAccountsWebChannel.jsm
@@ -430,17 +430,17 @@ this.FxAccountsWebChannelHelpers.prototy
let body = sb.GetStringFromName("relinkVerify.heading") +
"\n\n" + description;
let ps = Services.prompt;
let buttonFlags = (ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING) +
(ps.BUTTON_POS_1 * ps.BUTTON_TITLE_CANCEL) +
ps.BUTTON_POS_1_DEFAULT;
// If running in context of the browser chrome, window does not exist.
- var targetWindow = typeof window === 'undefined' ? null : window;
+ var targetWindow = typeof window === "undefined" ? null : window;
let pressed = Services.prompt.confirmEx(targetWindow, title, body, buttonFlags,
continueLabel, null, null, null,
{});
return pressed === 0; // 0 is the "continue" button
}
};
var singleton;
--- a/services/fxaccounts/tests/xpcshell/test_accounts.js
+++ b/services/fxaccounts/tests/xpcshell/test_accounts.js
@@ -17,17 +17,17 @@ var {AccountState} = Cu.import("resource
const ONE_HOUR_MS = 1000 * 60 * 60;
const ONE_DAY_MS = ONE_HOUR_MS * 24;
const TWO_MINUTES_MS = 1000 * 60 * 2;
initTestLogging("Trace");
// XXX until bug 937114 is fixed
-Cu.importGlobalProperties(['atob']);
+Cu.importGlobalProperties(["atob"]);
var log = Log.repository.getLogger("Services.FxAccounts.test");
log.level = Log.Level.Debug;
// See verbose logging from FxAccounts.jsm
Services.prefs.setCharPref("identity.fxaccounts.loglevel", "Trace");
Log.repository.getLogger("FirefoxAccounts").level = Log.Level.Trace;
--- a/services/fxaccounts/tests/xpcshell/test_client.js
+++ b/services/fxaccounts/tests/xpcshell/test_client.js
@@ -222,17 +222,17 @@ add_task(function* test_signUp() {
let result = yield client.signUp(unicodeUsername, unicodePassword);
do_check_eq("uid", result.uid);
do_check_eq("sessionToken", result.sessionToken);
do_check_eq(undefined, result.keyFetchToken);
do_check_eq(result.unwrapBKey,
"de6a2648b78284fcb9ffa81ba95803309cfba7af583c01a8a1a63e567234dd28");
// Try to create an account retrieving optional keys.
- result = yield client.signUp('you@example.org', 'pässwörd', true);
+ result = yield client.signUp("you@example.org", "pässwörd", true);
do_check_eq("uid", result.uid);
do_check_eq("sessionToken", result.sessionToken);
do_check_eq("keyFetchToken", result.keyFetchToken);
do_check_eq(result.unwrapBKey,
"f589225b609e56075d76eb74f771ff9ab18a4dc0e901e131ba8f984c7fb0ca8c");
// Try to create an existing account. Triggers error path.
try {
@@ -296,31 +296,31 @@ add_task(function* test_signIn() {
response.bodyOutputStream.write(errorMessage_notExistent,
errorMessage_notExistent.length);
}
},
});
// Login without retrieving optional keys
let client = new FxAccountsClient(server.baseURI);
- let result = yield client.signIn(unicodeUsername, 'bigsecret');
+ let result = yield client.signIn(unicodeUsername, "bigsecret");
do_check_eq(FAKE_SESSION_TOKEN, result.sessionToken);
do_check_eq(result.unwrapBKey,
"c076ec3f4af123a615157154c6e1d0d6293e514fd7b0221e32d50517ecf002b8");
do_check_eq(undefined, result.keyFetchToken);
// Login with retrieving optional keys
- result = yield client.signIn('you@example.com', 'bigsecret', true);
+ result = yield client.signIn("you@example.com", "bigsecret", true);
do_check_eq(FAKE_SESSION_TOKEN, result.sessionToken);
do_check_eq(result.unwrapBKey,
"65970516211062112e955d6420bebe020269d6b6a91ebd288319fc8d0cb49624");
do_check_eq("keyFetchToken", result.keyFetchToken);
// Retry due to wrong email capitalization
- result = yield client.signIn('You@example.com', 'bigsecret', true);
+ result = yield client.signIn("You@example.com", "bigsecret", true);
do_check_eq(FAKE_SESSION_TOKEN, result.sessionToken);
do_check_eq(result.unwrapBKey,
"65970516211062112e955d6420bebe020269d6b6a91ebd288319fc8d0cb49624");
do_check_eq("keyFetchToken", result.keyFetchToken);
// Trigger error path
try {
result = yield client.signIn("yøü@bad.example.org", "nofear");
@@ -677,17 +677,17 @@ add_task(function* test_registerDevice()
});
const client = new FxAccountsClient(server.baseURI);
const result = yield client.registerDevice(FAKE_SESSION_TOKEN, DEVICE_NAME, DEVICE_TYPE);
do_check_true(result);
do_check_eq(Object.keys(result).length, 4);
do_check_eq(result.id, DEVICE_ID);
- do_check_eq(typeof result.createdAt, 'number');
+ do_check_eq(typeof result.createdAt, "number");
do_check_true(result.createdAt > 0);
do_check_eq(result.name, DEVICE_NAME);
do_check_eq(result.type, DEVICE_TYPE);
try {
yield client.registerDevice(FAKE_SESSION_TOKEN, ERROR_NAME, DEVICE_TYPE);
do_throw("Expected to catch an exception");
} catch (unexpectedError) {
--- a/services/fxaccounts/tests/xpcshell/test_credentials.js
+++ b/services/fxaccounts/tests/xpcshell/test_credentials.js
@@ -44,28 +44,28 @@ add_task(function* test_onepw_setup_cred
let pbkdf2Rounds = 1000;
let pbkdf2Len = 32;
let quickStretchedPW = pbkdf2(password, saltyEmail, pbkdf2Rounds, pbkdf2Len, Ci.nsICryptoHMAC.SHA256, 32);
let quickStretchedActual = "6b88094c1c73bbf133223f300d101ed70837af48d9d2c1b6e7d38804b20cdde4";
do_check_eq(b2h(quickStretchedPW), quickStretchedActual);
// obtain hkdf info
- let authKeyInfo = Credentials.keyWord('authPW');
+ let authKeyInfo = Credentials.keyWord("authPW");
do_check_eq(b2h(authKeyInfo), "6964656e746974792e6d6f7a696c6c612e636f6d2f7069636c2f76312f617574685057");
// derive auth password
let hkdfSalt = h2b("00");
let hkdfLen = 32;
let authPW = hkdf(quickStretchedPW, hkdfSalt, authKeyInfo, hkdfLen);
do_check_eq(b2h(authPW), "4b8dec7f48e7852658163601ff766124c312f9392af6c3d4e1a247eb439be342");
// derive unwrap key
- let unwrapKeyInfo = Credentials.keyWord('unwrapBkey');
+ let unwrapKeyInfo = Credentials.keyWord("unwrapBkey");
let unwrapKey = hkdf(quickStretchedPW, hkdfSalt, unwrapKeyInfo, hkdfLen);
do_check_eq(b2h(unwrapKey), "8ff58975be391338e4ec5d7138b5ed7b65c7d1bfd1f3a4f93e05aa47d5b72be9");
});
add_task(function* test_client_stretch_kdf() {
let pbkdf2 = CryptoUtils.pbkdf2Generate;
let hkdf = CryptoUtils.hkdf;
--- a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js
+++ b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js
@@ -4,17 +4,17 @@
"use strict";
Cu.import("resource://gre/modules/FxAccountsCommon.js");
Cu.import("resource://gre/modules/FxAccountsOAuthGrantClient.jsm");
Cu.import("resource://gre/modules/Services.jsm");
const CLIENT_OPTIONS = {
serverURL: "http://127.0.0.1:9010/v1",
- client_id: 'abc123'
+ client_id: "abc123"
};
const STATUS_SUCCESS = 200;
/**
* Mock request responder
* @param {String} response
* Mocked raw response from the server
--- a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js
+++ b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js
@@ -26,17 +26,17 @@ function destroy(request, response) {
.createInstance(Ci.nsIScriptableInputStream);
sis.init(request.bodyInputStream);
let body = JSON.parse(sis.read(sis.available()));
sis.close();
let token = body.token;
ok(activeTokens.delete(token));
print("after destroy have", activeTokens.size, "tokens left.")
response.setStatusLine("1.1", 200, "OK");
- response.write('{}');
+ response.write("{}");
}
function startServer() {
numTokenFetches = 0;
activeTokens = new Set();
let srv = new HttpServer();
srv.registerPathHandler("/v1/authorization", authorize);
srv.registerPathHandler("/v1/destroy", destroy);
@@ -49,17 +49,17 @@ function promiseStopServer(server) {
server.stop(resolve);
});
}
add_task(function* getAndRevokeToken() {
let server = startServer();
let clientOptions = {
serverURL: "http://localhost:" + server.identity.primaryPort + "/v1",
- client_id: 'abc123',
+ client_id: "abc123",
}
let client = new FxAccountsOAuthGrantClient(clientOptions);
let result = yield client.getTokenFromAssertion("assertion", "scope");
equal(result.access_token, "token0");
equal(numTokenFetches, 1, "we hit the server to fetch a token");
yield client.destroyToken("token0");
equal(activeTokens.size, 0, "We hit the server to revoke it");
--- a/services/fxaccounts/tests/xpcshell/test_web_channel.js
+++ b/services/fxaccounts/tests/xpcshell/test_web_channel.js
@@ -20,96 +20,96 @@ add_test(function() {
"Error: Missing configuration options");
validationHelper({
channel_id: WEBCHANNEL_ID
},
"Error: Missing 'content_uri' option");
validationHelper({
- content_uri: 'bad uri',
+ content_uri: "bad uri",
channel_id: WEBCHANNEL_ID
},
/NS_ERROR_MALFORMED_URI/);
validationHelper({
content_uri: URL_STRING
},
- 'Error: Missing \'channel_id\' option');
+ "Error: Missing 'channel_id' option");
run_next_test();
});
add_task(function* test_rejection_reporting() {
let mockMessage = {
- command: 'fxaccounts:login',
- messageId: '1234',
- data: { email: 'testuser@testuser.com' },
+ command: "fxaccounts:login",
+ messageId: "1234",
+ data: { email: "testuser@testuser.com" },
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
login(accountData) {
- equal(accountData.email, 'testuser@testuser.com',
- 'Should forward incoming message data to the helper');
- return Promise.reject(new Error('oops'));
+ equal(accountData.email, "testuser@testuser.com",
+ "Should forward incoming message data to the helper");
+ return Promise.reject(new Error("oops"));
},
},
});
let promiseSend = new Promise(resolve => {
channel._channel.send = (message, context) => {
resolve({ message, context });
};
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
let { message, context } = yield promiseSend;
- equal(context, mockSendingContext, 'Should forward the original context');
- equal(message.command, 'fxaccounts:login',
- 'Should include the incoming command');
- equal(message.messageId, '1234', 'Should include the message ID');
- equal(message.data.error.message, 'Error: oops',
- 'Should convert the error message to a string');
+ equal(context, mockSendingContext, "Should forward the original context");
+ equal(message.command, "fxaccounts:login",
+ "Should include the incoming command");
+ equal(message.messageId, "1234", "Should include the message ID");
+ equal(message.data.error.message, "Error: oops",
+ "Should convert the error message to a string");
notStrictEqual(message.data.error.stack, null,
- 'Should include the stack for JS error rejections');
+ "Should include the stack for JS error rejections");
});
add_test(function test_exception_reporting() {
let mockMessage = {
- command: 'fxaccounts:sync_preferences',
- messageId: '5678',
- data: { entryPoint: 'fxa:verification_complete' }
+ command: "fxaccounts:sync_preferences",
+ messageId: "5678",
+ data: { entryPoint: "fxa:verification_complete" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
openSyncPreferences(browser, entryPoint) {
- equal(entryPoint, 'fxa:verification_complete',
- 'Should forward incoming message data to the helper');
- throw new TypeError('splines not reticulated');
+ equal(entryPoint, "fxa:verification_complete",
+ "Should forward incoming message data to the helper");
+ throw new TypeError("splines not reticulated");
},
},
});
channel._channel.send = (message, context) => {
- equal(context, mockSendingContext, 'Should forward the original context');
- equal(message.command, 'fxaccounts:sync_preferences',
- 'Should include the incoming command');
- equal(message.messageId, '5678', 'Should include the message ID');
- equal(message.data.error.message, 'TypeError: splines not reticulated',
- 'Should convert the exception to a string');
+ equal(context, mockSendingContext, "Should forward the original context");
+ equal(message.command, "fxaccounts:sync_preferences",
+ "Should include the incoming command");
+ equal(message.messageId, "5678", "Should include the message ID");
+ equal(message.data.error.message, "TypeError: splines not reticulated",
+ "Should convert the exception to a string");
notStrictEqual(message.data.error.stack, null,
- 'Should include the stack for JS exceptions');
+ "Should include the stack for JS exceptions");
run_next_test();
};
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_profile_image_change_message() {
@@ -128,121 +128,121 @@ add_test(function test_profile_image_cha
content_uri: URL_STRING
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_login_message() {
let mockMessage = {
- command: 'fxaccounts:login',
- data: { email: 'testuser@testuser.com' }
+ command: "fxaccounts:login",
+ data: { email: "testuser@testuser.com" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
login(accountData) {
- do_check_eq(accountData.email, 'testuser@testuser.com');
+ do_check_eq(accountData.email, "testuser@testuser.com");
run_next_test();
return Promise.resolve();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_logout_message() {
let mockMessage = {
- command: 'fxaccounts:logout',
+ command: "fxaccounts:logout",
data: { uid: "foo" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
logout(uid) {
- do_check_eq(uid, 'foo');
+ do_check_eq(uid, "foo");
run_next_test();
return Promise.resolve();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_delete_message() {
let mockMessage = {
- command: 'fxaccounts:delete',
+ command: "fxaccounts:delete",
data: { uid: "foo" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
logout(uid) {
- do_check_eq(uid, 'foo');
+ do_check_eq(uid, "foo");
run_next_test();
return Promise.resolve();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_can_link_account_message() {
let mockMessage = {
- command: 'fxaccounts:can_link_account',
- data: { email: 'testuser@testuser.com' }
+ command: "fxaccounts:can_link_account",
+ data: { email: "testuser@testuser.com" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
shouldAllowRelink(email) {
- do_check_eq(email, 'testuser@testuser.com');
+ do_check_eq(email, "testuser@testuser.com");
run_next_test();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_sync_preferences_message() {
let mockMessage = {
- command: 'fxaccounts:sync_preferences',
- data: { entryPoint: 'fxa:verification_complete' }
+ command: "fxaccounts:sync_preferences",
+ data: { entryPoint: "fxa:verification_complete" }
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING,
helpers: {
openSyncPreferences(browser, entryPoint) {
- do_check_eq(entryPoint, 'fxa:verification_complete');
+ do_check_eq(entryPoint, "fxa:verification_complete");
do_check_eq(browser, mockSendingContext.browser);
run_next_test();
}
}
});
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
});
add_test(function test_unrecognized_message() {
let mockMessage = {
- command: 'fxaccounts:unrecognized',
+ command: "fxaccounts:unrecognized",
data: {}
};
let channel = new FxAccountsWebChannel({
channel_id: WEBCHANNEL_ID,
content_uri: URL_STRING
});
@@ -250,114 +250,114 @@ add_test(function test_unrecognized_mess
channel._channelCallback(WEBCHANNEL_ID, mockMessage, mockSendingContext);
run_next_test();
});
add_test(function test_helpers_should_allow_relink_same_email() {
let helpers = new FxAccountsWebChannelHelpers();
- helpers.setPreviousAccountNameHashPref('testuser@testuser.com');
- do_check_true(helpers.shouldAllowRelink('testuser@testuser.com'));
+ helpers.setPreviousAccountNameHashPref("testuser@testuser.com");
+ do_check_true(helpers.shouldAllowRelink("testuser@testuser.com"));
run_next_test();
});
add_test(function test_helpers_should_allow_relink_different_email() {
let helpers = new FxAccountsWebChannelHelpers();
- helpers.setPreviousAccountNameHashPref('testuser@testuser.com');
+ helpers.setPreviousAccountNameHashPref("testuser@testuser.com");
helpers._promptForRelink = (acctName) => {
- return acctName === 'allowed_to_relink@testuser.com';
+ return acctName === "allowed_to_relink@testuser.com";
};
- do_check_true(helpers.shouldAllowRelink('allowed_to_relink@testuser.com'));
- do_check_false(helpers.shouldAllowRelink('not_allowed_to_relink@testuser.com'));
+ do_check_true(helpers.shouldAllowRelink("allowed_to_relink@testuser.com"));
+ do_check_false(helpers.shouldAllowRelink("not_allowed_to_relink@testuser.com"));
run_next_test();
});
add_task(function* test_helpers_login_without_customize_sync() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
setSignedInUser(accountData) {
return new Promise(resolve => {
// ensure fxAccounts is informed of the new user being signed in.
- do_check_eq(accountData.email, 'testuser@testuser.com');
+ do_check_eq(accountData.email, "testuser@testuser.com");
// verifiedCanLinkAccount should be stripped in the data.
- do_check_false('verifiedCanLinkAccount' in accountData);
+ do_check_false("verifiedCanLinkAccount" in accountData);
// the customizeSync pref should not update
do_check_false(helpers.getShowCustomizeSyncPref());
// previously signed in user preference is updated.
- do_check_eq(helpers.getPreviousAccountNameHashPref(), helpers.sha256('testuser@testuser.com'));
+ do_check_eq(helpers.getPreviousAccountNameHashPref(), helpers.sha256("testuser@testuser.com"));
resolve();
});
}
}
});
// the show customize sync pref should stay the same
helpers.setShowCustomizeSyncPref(false);
// ensure the previous account pref is overwritten.
- helpers.setPreviousAccountNameHashPref('lastuser@testuser.com');
+ helpers.setPreviousAccountNameHashPref("lastuser@testuser.com");
yield helpers.login({
- email: 'testuser@testuser.com',
+ email: "testuser@testuser.com",
verifiedCanLinkAccount: true,
customizeSync: false
});
});
add_task(function* test_helpers_login_with_customize_sync() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
setSignedInUser(accountData) {
return new Promise(resolve => {
// ensure fxAccounts is informed of the new user being signed in.
- do_check_eq(accountData.email, 'testuser@testuser.com');
+ do_check_eq(accountData.email, "testuser@testuser.com");
// customizeSync should be stripped in the data.
- do_check_false('customizeSync' in accountData);
+ do_check_false("customizeSync" in accountData);
// the customizeSync pref should not update
do_check_true(helpers.getShowCustomizeSyncPref());
resolve();
});
}
}
});
// the customize sync pref should be overwritten
helpers.setShowCustomizeSyncPref(false);
yield helpers.login({
- email: 'testuser@testuser.com',
+ email: "testuser@testuser.com",
verifiedCanLinkAccount: true,
customizeSync: true
});
});
add_task(function* test_helpers_login_with_customize_sync_and_declined_engines() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
setSignedInUser(accountData) {
return new Promise(resolve => {
// ensure fxAccounts is informed of the new user being signed in.
- do_check_eq(accountData.email, 'testuser@testuser.com');
+ do_check_eq(accountData.email, "testuser@testuser.com");
// customizeSync should be stripped in the data.
- do_check_false('customizeSync' in accountData);
- do_check_false('declinedSyncEngines' in accountData);
+ do_check_false("customizeSync" in accountData);
+ do_check_false("declinedSyncEngines" in accountData);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.addons"), false);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.bookmarks"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.history"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.passwords"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.prefs"), false);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.tabs"), true);
// the customizeSync pref should be disabled
@@ -374,20 +374,20 @@ add_task(function* test_helpers_login_wi
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.addons"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.bookmarks"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.history"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.passwords"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.prefs"), true);
do_check_eq(Services.prefs.getBoolPref("services.sync.engine.tabs"), true);
yield helpers.login({
- email: 'testuser@testuser.com',
+ email: "testuser@testuser.com",
verifiedCanLinkAccount: true,
customizeSync: true,
- declinedSyncEngines: ['addons', 'prefs']
+ declinedSyncEngines: ["addons", "prefs"]
});
});
add_test(function test_helpers_open_sync_preferences() {
let helpers = new FxAccountsWebChannelHelpers({
fxAccounts: {
}
});
@@ -451,17 +451,17 @@ add_task(function* test_helpers_change_p
updateDeviceRegistration() {
wasCalled.updateDeviceRegistration = true;
return Promise.resolve()
}
}
});
try {
yield helpers.changePassword({});
- do_check_false('changePassword should have rejected');
+ do_check_false("changePassword should have rejected");
} catch (_) {
do_check_true(wasCalled.updateUserAccountData);
do_check_false(wasCalled.updateDeviceRegistration);
}
});
function run_test() {
run_next_test();
@@ -484,16 +484,16 @@ function makeObserver(aObserveTopic, aOb
Services.obs.addObserver(callback, aObserveTopic, false);
return removeMe;
}
function validationHelper(params, expected) {
try {
new FxAccountsWebChannel(params);
} catch (e) {
- if (typeof expected === 'string') {
+ if (typeof expected === "string") {
return do_check_eq(e.toString(), expected);
} else {
return do_check_true(e.toString().match(expected));
}
}
throw new Error("Validation helper error");
}
--- a/services/sync/Weave.js
+++ b/services/sync/Weave.js
@@ -102,17 +102,17 @@ WeaveService.prototype = {
*
* @return bool
*/
get fxAccountsEnabled() {
try {
// Old sync guarantees '@' will never appear in the username while FxA
// uses the FxA email address - so '@' is the flag we use.
let username = Services.prefs.getCharPref(SYNC_PREFS_BRANCH + "username");
- return !username || username.includes('@');
+ return !username || username.includes("@");
} catch (_) {
return true; // No username == only allow FxA to be configured.
}
},
/**
* Whether Sync appears to be enabled.
*
--- a/services/sync/modules-testing/utils.js
+++ b/services/sync/modules-testing/utils.js
@@ -149,21 +149,21 @@ this.setBasicCredentials =
this.makeIdentityConfig = function(overrides) {
// first setup the defaults.
let result = {
// Username used in both fxaccount and sync identity configs.
username: "foo",
// fxaccount specific credentials.
fxaccount: {
user: {
- assertion: 'assertion',
- email: 'email',
- kA: 'kA',
- kB: 'kB',
- sessionToken: 'sessionToken',
+ assertion: "assertion",
+ email: "email",
+ kA: "kA",
+ kB: "kB",
+ sessionToken: "sessionToken",
uid: "a".repeat(32),
verified: true,
},
token: {
endpoint: null,
duration: 300,
id: "id",
key: "key",
--- a/services/sync/modules/bookmark_validator.js
+++ b/services/sync/modules/bookmark_validator.js
@@ -222,30 +222,30 @@ class BookmarkValidator {
let syncedRoots = SYNCED_ROOTS;
function traverse(treeNode, synced) {
if (!synced) {
synced = syncedRoots.includes(treeNode.guid);
} else if (isNodeIgnored(treeNode)) {
synced = false;
}
let guid = PlacesSyncUtils.bookmarks.guidToSyncId(treeNode.guid);
- let itemType = 'item';
+ let itemType = "item";
treeNode.ignored = !synced;
treeNode.id = guid;
switch (treeNode.type) {
case PlacesUtils.TYPE_X_MOZ_PLACE:
let query = null;
if (treeNode.annos && treeNode.uri.startsWith("place:")) {
query = treeNode.annos.find(({name}) =>
name === PlacesSyncUtils.bookmarks.SMART_BOOKMARKS_ANNO);
}
if (query && query.value) {
- itemType = 'query';
+ itemType = "query";
} else {
- itemType = 'bookmark';
+ itemType = "bookmark";
}
break;
case PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER:
let isLivemark = false;
if (treeNode.annos) {
for (let anno of treeNode.annos) {
if (anno.name === PlacesUtils.LMANNO_FEEDURI) {
isLivemark = true;
@@ -254,46 +254,46 @@ class BookmarkValidator {
isLivemark = true;
treeNode.siteUri = anno.value;
}
}
}
itemType = isLivemark ? "livemark" : "folder";
break;
case PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR:
- itemType = 'separator';
+ itemType = "separator";
break;
}
if (treeNode.tags) {
treeNode.tags = treeNode.tags.split(",");
} else {
treeNode.tags = [];
}
treeNode.type = itemType;
treeNode.pos = treeNode.index;
treeNode.bmkUri = treeNode.uri;
records.push(treeNode);
// We want to use the "real" guid here.
recordsByGuid.set(treeNode.guid, treeNode);
- if (treeNode.type === 'folder') {
+ if (treeNode.type === "folder") {
treeNode.childGUIDs = [];
if (!treeNode.children) {
treeNode.children = [];
}
for (let child of treeNode.children) {
traverse(child, synced);
child.parent = treeNode;
child.parentid = guid;
treeNode.childGUIDs.push(child.guid);
}
}
}
traverse(clientTree, false);
- clientTree.id = 'places';
+ clientTree.id = "places";
this._followQueries(recordsByGuid);
return records;
}
/**
* Process the server-side list. Mainly this builds the records into a tree,
* but it also records information about problems, and produces arrays of the
* deleted and non-deleted nodes.
@@ -373,24 +373,24 @@ class BookmarkValidator {
for (let deletedId of deletedItemIds) {
let record = idToRecord.get(deletedId);
if (record && !record.isDeleted) {
deletedRecords.push(record);
record.isDeleted = true;
}
}
- let root = idToRecord.get('places');
+ let root = idToRecord.get("places");
if (!root) {
// Fabricate a root. We want to remember that it's fake so that we can
// avoid complaining about stuff like it missing it's childGUIDs later.
- root = { id: 'places', children: [], type: 'folder', title: '', fake: true };
+ root = { id: "places", children: [], type: "folder", title: "", fake: true };
resultRecords.push(root);
- idToRecord.set('places', root);
+ idToRecord.set("places", root);
} else {
problemData.rootOnServer = true;
}
// Build the tree, find orphans, and record most problems having to do with
// the tree structure.
for (let [id, record] of idToRecord) {
if (record === root) {
@@ -408,17 +408,17 @@ class BookmarkValidator {
}
let parent = idToRecord.get(parentID);
if (!parent) {
problemData.orphans.push({id: record.id, parent: parentID});
continue;
}
- if (parent.type !== 'folder') {
+ if (parent.type !== "folder") {
problemData.parentNotFolder.push(record.id);
if (!parent.children) {
parent.children = [];
}
if (!parent.childGUIDs) {
parent.childGUIDs = [];
}
}
@@ -669,65 +669,65 @@ class BookmarkValidator {
// We want to treat undefined, null and an empty string as identical
if ((client.title || "") !== (server.title || "")) {
differences.push("title");
}
}
if (client.parentid || server.parentid) {
if (client.parentid !== server.parentid) {
- structuralDifferences.push('parentid');
+ structuralDifferences.push("parentid");
}
}
if (client.tags || server.tags) {
let cl = client.tags || [];
let sl = server.tags || [];
if (cl.length !== sl.length || !cl.every((tag, i) => sl.indexOf(tag) >= 0)) {
- differences.push('tags');
+ differences.push("tags");
}
}
let sameType = client.type === server.type;
if (!sameType) {
if (server.type === "query" && client.type === "bookmark" && client.bmkUri.startsWith("place:")) {
sameType = true;
}
}
if (!sameType) {
- differences.push('type');
+ differences.push("type");
} else {
switch (server.type) {
- case 'bookmark':
- case 'query':
+ case "bookmark":
+ case "query":
if (server.bmkUri !== client.bmkUri) {
- differences.push('bmkUri');
+ differences.push("bmkUri");
}
break;
case "livemark":
if (server.feedUri != client.feedUri) {
differences.push("feedUri");
}
if (server.siteUri != client.siteUri) {
differences.push("siteUri");
}
break;
- case 'folder':
- if (server.id === 'places' && !problemData.rootOnServer) {
+ case "folder":
+ if (server.id === "places" && !problemData.rootOnServer) {
// It's the fabricated places root. It won't have the GUIDs, but
// it doesn't matter.
break;
}
if (client.childGUIDs || server.childGUIDs) {
let cl = client.childGUIDs || [];
let sl = server.childGUIDs || [];
if (cl.length !== sl.length || !cl.every((id, i) => sl[i] === id)) {
- structuralDifferences.push('childGUIDs');
+ structuralDifferences.push("childGUIDs");
}
}
break;
}
}
if (differences.length) {
problemData.differences.push({id, differences});
--- a/services/sync/modules/browserid_identity.js
+++ b/services/sync/modules/browserid_identity.js
@@ -27,17 +27,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
"resource://services-sync/main.js");
XPCOMUtils.defineLazyModuleGetter(this, "BulkKeyBundle",
"resource://services-sync/keys.js");
XPCOMUtils.defineLazyModuleGetter(this, "fxAccounts",
"resource://gre/modules/FxAccounts.jsm");
-XPCOMUtils.defineLazyGetter(this, 'log', function() {
+XPCOMUtils.defineLazyGetter(this, "log", function() {
let log = Log.repository.getLogger("Sync.BrowserIDManager");
log.level = Log.Level[Svc.Prefs.get("log.logger.identity")] || Log.Level.Error;
return log;
});
// FxAccountsCommon.js doesn't use a "namespace", so create one here.
var fxAccountsCommon = {};
Cu.import("resource://gre/modules/FxAccountsCommon.js", fxAccountsCommon);
--- a/services/sync/modules/engines/bookmarks.js
+++ b/services/sync/modules/engines/bookmarks.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-this.EXPORTED_SYMBOLS = ['BookmarksEngine', "PlacesItem", "Bookmark",
+this.EXPORTED_SYMBOLS = ["BookmarksEngine", "PlacesItem", "Bookmark",
"BookmarkFolder", "BookmarkQuery",
"Livemark", "BookmarkSeparator"];
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
Cu.import("resource://gre/modules/PlacesUtils.jsm");
--- a/services/sync/modules/engines/extension-storage.js
+++ b/services/sync/modules/engines/extension-storage.js
@@ -1,16 +1,16 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
-this.EXPORTED_SYMBOLS = ['ExtensionStorageEngine', 'EncryptionRemoteTransformer',
- 'KeyRingEncryptionRemoteTransformer'];
+this.EXPORTED_SYMBOLS = ["ExtensionStorageEngine", "EncryptionRemoteTransformer",
+ "KeyRingEncryptionRemoteTransformer"];
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://services-crypto/utils.js");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/keys.js");
Cu.import("resource://services-sync/util.js");
--- a/services/sync/modules/engines/forms.js
+++ b/services/sync/modules/engines/forms.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-this.EXPORTED_SYMBOLS = ['FormEngine', 'FormRec', 'FormValidator'];
+this.EXPORTED_SYMBOLS = ["FormEngine", "FormRec", "FormValidator"];
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/record.js");
--- a/services/sync/modules/engines/history.js
+++ b/services/sync/modules/engines/history.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-this.EXPORTED_SYMBOLS = ['HistoryEngine', 'HistoryRec'];
+this.EXPORTED_SYMBOLS = ["HistoryEngine", "HistoryRec"];
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
var Cr = Components.results;
const HISTORY_TTL = 5184000; // 60 days
--- a/services/sync/modules/engines/passwords.js
+++ b/services/sync/modules/engines/passwords.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-this.EXPORTED_SYMBOLS = ['PasswordEngine', 'LoginRec', 'PasswordValidator'];
+this.EXPORTED_SYMBOLS = ["PasswordEngine", "LoginRec", "PasswordValidator"];
var {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/collection_validator.js");
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/util.js");
--- a/services/sync/modules/engines/prefs.js
+++ b/services/sync/modules/engines/prefs.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-this.EXPORTED_SYMBOLS = ['PrefsEngine', 'PrefRec'];
+this.EXPORTED_SYMBOLS = ["PrefsEngine", "PrefRec"];
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
const PREF_SYNC_PREFS_PREFIX = "services.sync.prefs.sync.";
Cu.import("resource://services-sync/engines.js");
--- a/services/sync/modules/main.js
+++ b/services/sync/modules/main.js
@@ -1,21 +1,21 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-this.EXPORTED_SYMBOLS = ['Weave'];
+this.EXPORTED_SYMBOLS = ["Weave"];
this.Weave = {};
Components.utils.import("resource://services-sync/constants.js", Weave);
var lazies = {
"jpakeclient.js": ["JPAKEClient", "SendCredentialsController"],
"service.js": ["Service"],
"status.js": ["Status"],
- "util.js": ['Utils', 'Svc']
+ "util.js": ["Utils", "Svc"]
};
function lazyImport(module, dest, props) {
function getter(prop) {
return function() {
let ns = {};
Components.utils.import(module, ns);
delete dest[prop];
--- a/services/sync/modules/policies.js
+++ b/services/sync/modules/policies.js
@@ -895,17 +895,17 @@ ErrorHandler.prototype = {
*
* This method also looks for "side-channel" warnings.
*/
checkServerError(resp) {
switch (resp.status) {
case 200:
case 404:
case 513:
- let xwa = resp.headers['x-weave-alert'];
+ let xwa = resp.headers["x-weave-alert"];
// Only process machine-readable alerts.
if (!xwa || !xwa.startsWith("{")) {
this.clearServerAlerts();
return;
}
try {
--- a/services/sync/modules/record.js
+++ b/services/sync/modules/record.js
@@ -606,36 +606,36 @@ Collection.prototype = {
_logName: "Sync.Collection",
_rebuildURL: function Coll__rebuildURL() {
// XXX should consider what happens if it's not a URL...
this.uri.QueryInterface(Ci.nsIURL);
let args = [];
if (this.older)
- args.push('older=' + this.older);
+ args.push("older=" + this.older);
else if (this.newer) {
- args.push('newer=' + this.newer);
+ args.push("newer=" + this.newer);
}
if (this.full)
- args.push('full=1');
+ args.push("full=1");
if (this.sort)
- args.push('sort=' + this.sort);
+ args.push("sort=" + this.sort);
if (this.ids != null)
args.push("ids=" + this.ids);
if (this.limit > 0 && this.limit != Infinity)
args.push("limit=" + this.limit);
if (this._batch)
args.push("batch=" + encodeURIComponent(this._batch));
if (this._commit)
args.push("commit=true");
if (this._offset)
args.push("offset=" + encodeURIComponent(this._offset));
- this.uri.query = (args.length > 0) ? '?' + args.join('&') : '';
+ this.uri.query = (args.length > 0) ? "?" + args.join("&") : "";
},
// get full items
get full() { return this._full; },
set full(value) {
this._full = value;
this._rebuildURL();
},
--- a/services/sync/modules/resource.js
+++ b/services/sync/modules/resource.js
@@ -97,17 +97,17 @@ AsyncResource.prototype = {
// ** {{{ AsyncResource.uri }}} **
//
// URI representing this resource.
get uri() {
return this._uri;
},
set uri(value) {
- if (typeof value == 'string')
+ if (typeof value == "string")
this._uri = CommonUtils.makeURI(value);
else
this._uri = value;
},
// ** {{{ AsyncResource.spec }}} **
//
// Get the string representation of the URI.
@@ -159,17 +159,17 @@ AsyncResource.prototype = {
headers[k.toLowerCase()] = v;
}
}
} else {
this._log.debug("No authenticator found.");
}
for (let [key, value] of Object.entries(headers)) {
- if (key == 'authorization')
+ if (key == "authorization")
this._log.trace("HTTP Header " + key + ": ***** (suppressed)");
else
this._log.trace("HTTP Header " + key + ": " + headers[key]);
channel.setRequestHeader(key, headers[key], false);
}
return channel;
},
@@ -187,18 +187,18 @@ AsyncResource.prototype = {
if ("PUT" == action || "POST" == action) {
// Convert non-string bodies into JSON
if (this._data.constructor.toString() != String)
this._data = JSON.stringify(this._data);
this._log.debug(action + " Length: " + this._data.length);
this._log.trace(action + " Body: " + this._data);
- let type = ('content-type' in this._headers) ?
- this._headers['content-type'] : 'text/plain';
+ let type = ("content-type" in this._headers) ?
+ this._headers["content-type"] : "text/plain";
let stream = Cc["@mozilla.org/io/string-input-stream;1"].
createInstance(Ci.nsIStringInputStream);
stream.setData(this._data, this._data.length);
channel.QueryInterface(Ci.nsIUploadChannel);
channel.setUploadStream(stream, type, this._data.length);
}
@@ -463,17 +463,17 @@ ChannelListener.prototype = {
// Save the latest server timestamp when possible.
try {
AsyncResource.serverTime = channel.getResponseHeader("X-Weave-Timestamp") - 0;
} catch (ex) {}
this._log.trace("onStartRequest: " + channel.requestMethod + " " +
channel.URI.spec);
- this._data = '';
+ this._data = "";
this.delayAbort();
},
onStopRequest: function Channel_onStopRequest(channel, context, status) {
// Clear the abort timer now that the channel is done.
this.abortTimer.clear();
if (!this._onComplete) {
@@ -492,17 +492,17 @@ ChannelListener.prototype = {
return;
}
let statusSuccess = Components.isSuccessCode(status);
let uri = channel && channel.URI && channel.URI.spec || "<unknown>";
this._log.trace("Channel for " + channel.requestMethod + " " + uri + ": " +
"isSuccessCode(" + status + ")? " + statusSuccess);
- if (this._data == '') {
+ if (this._data == "") {
this._data = null;
}
// Pass back the failure code and stop execution. Use Components.Exception()
// instead of Error() so the exception is QI-able and can be passed across
// XPCOM borders while preserving the status code.
if (!statusSuccess) {
let message = Components.Exception("", status).name;
--- a/services/sync/modules/util.js
+++ b/services/sync/modules/util.js
@@ -263,24 +263,24 @@ this.Utils = {
/**
* Turn RFC 4648 base32 into our own user-friendly version.
* ABCDEFGHIJKLMNOPQRSTUVWXYZ234567
* becomes
* abcdefghijk8mn9pqrstuvwxyz234567
*/
base32ToFriendly: function base32ToFriendly(input) {
return input.toLowerCase()
- .replace(/l/g, '8')
- .replace(/o/g, '9');
+ .replace(/l/g, "8")
+ .replace(/o/g, "9");
},
base32FromFriendly: function base32FromFriendly(input) {
return input.toUpperCase()
- .replace(/8/g, 'L')
- .replace(/9/g, 'O');
+ .replace(/8/g, "L")
+ .replace(/9/g, "O");
},
/**
* Key manipulation.
*/
// Return an octet string in friendly base32 *with no trailing =*.
encodeKeyBase32: function encodeKeyBase32(keyData) {
@@ -540,25 +540,25 @@ this.Utils = {
normalizePassphrase: function normalizePassphrase(pp) {
// Short var name... have you seen the lines below?!
// Allow leading and trailing whitespace.
pp = pp.trim().toLowerCase();
// 20-char sync key.
if (pp.length == 23 &&
- [5, 11, 17].every(i => pp[i] == '-')) {
+ [5, 11, 17].every(i => pp[i] == "-")) {
return pp.slice(0, 5) + pp.slice(6, 11)
+ pp.slice(12, 17) + pp.slice(18, 23);
}
// "Modern" 26-char key.
if (pp.length == 31 &&
- [1, 7, 13, 19, 25].every(i => pp[i] == '-')) {
+ [1, 7, 13, 19, 25].every(i => pp[i] == "-")) {
return pp.slice(0, 1) + pp.slice(2, 7)
+ pp.slice(8, 13) + pp.slice(14, 19)
+ pp.slice(20, 25) + pp.slice(26, 31);
}
// Something else -- just return.
return pp;
--- a/services/sync/tests/tps/mozmill_sanity.js
+++ b/services/sync/tests/tps/mozmill_sanity.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-Components.utils.import('resource://tps/tps.jsm');
+Components.utils.import("resource://tps/tps.jsm");
var setupModule = function(module) {
module.controller = mozmill.getBrowserController();
assert.ok(true, "SetupModule passes");
}
var setupTest = function(module) {
assert.ok(true, "SetupTest passes");
--- a/services/sync/tests/tps/mozmill_sanity2.js
+++ b/services/sync/tests/tps/mozmill_sanity2.js
@@ -6,10 +6,10 @@ var setupModule = function(module) {
module.controller = mozmill.getBrowserController();
};
var testGetNode = function() {
controller.open("about:support");
controller.waitForPageLoad();
var appbox = findElement.ID(controller.tabs.activeTab, "application-box");
- assert.waitFor(() => appbox.getNode().textContent == 'Firefox', 'correct app name');
+ assert.waitFor(() => appbox.getNode().textContent == "Firefox", "correct app name");
};
--- a/services/sync/tests/tps/test_bookmarks_in_same_named_folder.js
+++ b/services/sync/tests/tps/test_bookmarks_in_same_named_folder.js
@@ -45,25 +45,25 @@ var bookmarks_initial_2 = {
title: "Bugzilla"
},
{ uri: "http://www.apple.com",
tags: [ "apple" ]
}
]
};
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial_1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial_1],
[Bookmarks.add, bookmarks_initial_2],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
// XXX [Bookmarks.verify, bookmarks_initial_1],
[Bookmarks.verify, bookmarks_initial_2]
]);
--- a/services/sync/tests/tps/test_bug501528.js
+++ b/services/sync/tests/tps/test_bug501528.js
@@ -49,31 +49,31 @@ var passwords_after_first_update = [
password: "secretlogin"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Passwords.add, passwords_initial],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Passwords.add, passwords_initial],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Passwords.verify, passwords_initial],
[Passwords.modify, passwords_initial],
[Passwords.verify, passwords_after_first_update],
[Sync]
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Passwords.verify, passwords_after_first_update],
]);
--- a/services/sync/tests/tps/test_bug530717.js
+++ b/services/sync/tests/tps/test_bug530717.js
@@ -40,30 +40,30 @@ var prefs2 = [
}
];
/*
* Test phases
*/
// Add prefs to profile1 and sync.
-Phase('phase1', [
+Phase("phase1", [
[Prefs.modify, prefs1],
[Prefs.verify, prefs1],
[Sync]
]);
// Sync profile2 and verify same prefs are present.
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Prefs.verify, prefs1]
]);
// Using profile1, change some prefs, then do another sync with wipe-client.
// Verify that the cloud's prefs are restored, and the recent local changes
// discarded.
-Phase('phase3', [
+Phase("phase3", [
[Prefs.modify, prefs2],
[Prefs.verify, prefs2],
[Sync, SYNC_WIPE_CLIENT],
[Prefs.verify, prefs1]
]);
--- a/services/sync/tests/tps/test_bug531489.js
+++ b/services/sync/tests/tps/test_bug531489.js
@@ -36,27 +36,27 @@ var bookmarks_initial = {
]
};
/*
* Test phases
*/
// Add three bookmarks with the same url to different locations and sync.
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial],
[Bookmarks.verify, bookmarks_initial],
[Sync]
]);
// Sync to profile2 and verify that all three bookmarks are present
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
// Sync again to profile1 and verify that all three bookmarks are still
// present.
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
--- a/services/sync/tests/tps/test_bug535326.js
+++ b/services/sync/tests/tps/test_bug535326.js
@@ -113,18 +113,18 @@ var tabs1 = [
profile: "profile1"
},
{ uri: "data:text/html,<html><head><title>Mobile</title></head><body>Mobile</body></html>",
title: "Mobile",
profile: "profile1"
}
];
-Phase('phase1', [
+Phase("phase1", [
[Tabs.add, tabs1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Tabs.verify, tabs1]
]);
--- a/services/sync/tests/tps/test_bug538298.js
+++ b/services/sync/tests/tps/test_bug538298.js
@@ -58,36 +58,36 @@ var bookmarks_after_move = {
]
};
/*
* Test phases
*/
// Add four bookmarks to the toolbar and sync.
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial],
[Bookmarks.verify, bookmarks_initial],
[Sync]
]);
// Sync to profile2 and verify that all four bookmarks are present.
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
// Change the order of the toolbar bookmarks, and sync.
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Bookmarks.verify, bookmarks_initial],
[Bookmarks.modify, bookmarks_initial],
[Bookmarks.verify, bookmarks_after_move],
[Sync],
]);
// Go back to profile2, sync, and verify that the bookmarks are reordered
// as expected.
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Bookmarks.verify, bookmarks_after_move]
]);
--- a/services/sync/tests/tps/test_bug546807.js
+++ b/services/sync/tests/tps/test_bug546807.js
@@ -37,18 +37,18 @@ var tabs_absent = [
profile: "profile1"
},
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Tabs.add, tabs1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Tabs.verifyNot, tabs_absent]
]);
--- a/services/sync/tests/tps/test_bug556509.js
+++ b/services/sync/tests/tps/test_bug556509.js
@@ -26,20 +26,20 @@ var bookmarks_initial = {
]
};
/*
* Test phases
*/
// Add a bookmark folder which has a description, and sync.
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial],
[Bookmarks.verify, bookmarks_initial],
[Sync]
]);
// Sync to profile2 and verify that the bookmark folder is created, along
// with its description.
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
--- a/services/sync/tests/tps/test_bug562515.js
+++ b/services/sync/tests/tps/test_bug562515.js
@@ -72,34 +72,34 @@ var bookmarks_to_delete = {
]
};
/*
* Test phases
*/
// add bookmarks to profile1 and sync
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial],
[Bookmarks.verify, bookmarks_initial],
[Sync]
]);
// sync to profile2 and verify that the bookmarks are present
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
// delete some bookmarks from profile1, then sync with "wipe-client"
// set; finally, verify that the deleted bookmarks were restored.
-Phase('phase3', [
+Phase("phase3", [
[Bookmarks.delete, bookmarks_to_delete],
[Bookmarks.verifyNot, bookmarks_to_delete],
[Sync, SYNC_WIPE_CLIENT],
[Bookmarks.verify, bookmarks_initial]
]);
// sync profile2 again, verify no bookmarks have been deleted
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
--- a/services/sync/tests/tps/test_bug563989.js
+++ b/services/sync/tests/tps/test_bug563989.js
@@ -71,37 +71,37 @@ var bookmarks_to_delete = {
]
};
/*
* Test phases
*/
// Add bookmarks to profile1 and sync.
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial],
[Bookmarks.verify, bookmarks_initial],
[Sync],
]);
// Sync to profile2 and verify that the bookmarks are present. Delete
// some bookmarks, and verify that they're not present, but don't sync again.
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial],
[Bookmarks.delete, bookmarks_to_delete],
[Bookmarks.verifyNot, bookmarks_to_delete],
[Bookmarks.skipValidation]
]);
// Using profile1, sync again with wipe-server set to true. Verify our
// initial bookmarks are still all present.
-Phase('phase3', [
+Phase("phase3", [
[Sync, SYNC_WIPE_REMOTE],
[Bookmarks.verify, bookmarks_initial]
]);
// Back in profile2, do a sync and verify that the bookmarks we had
// deleted earlier are now restored.
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Bookmarks.verify, bookmarks_initial]
]);
--- a/services/sync/tests/tps/test_bug575423.js
+++ b/services/sync/tests/tps/test_bug575423.js
@@ -66,20 +66,20 @@ var history2 = [
}
]
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[History.add, history1],
[Sync],
[History.add, history2],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[History.verify, history2]
]);
--- a/services/sync/tests/tps/test_client_wipe.js
+++ b/services/sync/tests/tps/test_client_wipe.js
@@ -125,36 +125,36 @@ var prefs2 = [
}
];
/*
* Test phases
*/
// Add prefs,passwords and bookmarks to profile1 and sync.
-Phase('phase1', [
+Phase("phase1", [
[Passwords.add, passwords_initial],
[Bookmarks.add, bookmarks_initial],
[Prefs.modify, prefs1],
[Prefs.verify, prefs1],
[Sync]
]);
// Sync profile2 and verify same prefs,passwords and bookmarks are present.
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Prefs.verify, prefs1],
[Passwords.verify, passwords_initial],
[Bookmarks.verify, bookmarks_initial]
]);
// Using profile1, change some prefs,bookmarks and pwds, then do another sync with wipe-client.
// Verify that the cloud's settings are restored, and the recent local changes
// discarded.
-Phase('phase3', [
+Phase("phase3", [
[Prefs.modify, prefs2],
[Passwords.modify, passwords_initial],
[Bookmarks.modify, bookmarks_initial],
[Prefs.verify, prefs2],
[Passwords.verify, passwords_after_change],
[Bookmarks.verify, bookmarks_after_move],
[Sync, SYNC_WIPE_CLIENT],
[Prefs.verify, prefs1],
--- a/services/sync/tests/tps/test_formdata.js
+++ b/services/sync/tests/tps/test_formdata.js
@@ -56,42 +56,42 @@ var formdata_new = [
{ fieldname: "new-field",
value: "new-value"
}
]
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Formdata.add, formdata1],
[Formdata.verify, formdata1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Formdata.verify, formdata1],
]);
/*
* Note: Weave does not support syncing deleted form data, so those
* tests are disabled below. See bug 568363.
*/
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Formdata.delete, formdata_delete],
// [Formdata.verifyNot, formdata_delete],
[Formdata.verify, formdata2],
// add new data after the first Sync, ensuring the tracker works.
[Formdata.add, formdata_new],
[Sync],
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Formdata.verify, formdata2],
[Formdata.verify, formdata_new],
//[Formdata.verifyNot, formdata_delete]
]);
--- a/services/sync/tests/tps/test_history.js
+++ b/services/sync/tests/tps/test_history.js
@@ -146,22 +146,22 @@ var history_not = [
/*
* Test phases
* Note: there is no test phase in which deleted history entries are
* synced to other clients. This functionality is not supported by
* Sync, see bug 446517.
*/
-Phase('phase1', [
+Phase("phase1", [
[History.add, history1],
[Sync],
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[History.verify, history1],
[History.delete, history_to_delete],
[History.verify, history2],
[History.verifyNot, history_not],
[Sync]
]);
--- a/services/sync/tests/tps/test_history_collision.js
+++ b/services/sync/tests/tps/test_history_collision.js
@@ -93,33 +93,33 @@ var history_after_delete = [
]
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[History.add, history1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[History.add, history1],
[Sync, SYNC_WIPE_REMOTE]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[History.verify, history1],
[History.delete, history_to_delete],
[History.verify, history_after_delete],
[History.verifyNot, history_not],
[Sync]
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[History.verify, history_after_delete],
[History.verifyNot, history_not]
]);
--- a/services/sync/tests/tps/test_mozmill_sanity.js
+++ b/services/sync/tests/tps/test_mozmill_sanity.js
@@ -9,16 +9,16 @@
var phases = { "phase1": "profile1",
"phase2": "profile2" };
/*
* Test phases
*/
-Phase('phase1', [
- [RunMozmillTest, 'mozmill_sanity.js'],
+Phase("phase1", [
+ [RunMozmillTest, "mozmill_sanity.js"],
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
- [RunMozmillTest, 'mozmill_sanity2.js'],
+ [RunMozmillTest, "mozmill_sanity2.js"],
]);
--- a/services/sync/tests/tps/test_passwords.js
+++ b/services/sync/tests/tps/test_passwords.js
@@ -79,35 +79,35 @@ var passwords_after_second_update = [
passwordField: "pword"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Passwords.add, passwords_initial],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Passwords.verify, passwords_initial],
[Passwords.modify, passwords_initial],
[Passwords.verify, passwords_after_first_update],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Passwords.verify, passwords_after_first_update],
[Passwords.delete, passwords_to_delete],
[Passwords.verify, passwords_after_second_update],
[Passwords.verifyNot, passwords_absent],
[Sync]
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Passwords.verify, passwords_after_second_update],
[Passwords.verifyNot, passwords_absent]
]);
--- a/services/sync/tests/tps/test_prefs.js
+++ b/services/sync/tests/tps/test_prefs.js
@@ -31,27 +31,27 @@ var prefs2 = [
{ name: "browser.urlbar.maxRichResults",
value: 18
},
{ name: "privacy.clearOnShutdown.siteSettings",
value: false
}
];
-Phase('phase1', [
+Phase("phase1", [
[Prefs.modify, prefs1],
[Prefs.verify, prefs1],
[Sync],
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Prefs.verify, prefs1],
[Prefs.modify, prefs2],
[Prefs.verify, prefs2],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Prefs.verify, prefs2]
]);
--- a/services/sync/tests/tps/test_privbrw_passwords.js
+++ b/services/sync/tests/tps/test_privbrw_passwords.js
@@ -70,35 +70,35 @@ var passwords_after_second_change = [
password: "secretlogin"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Passwords.add, passwords_initial],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Passwords.verify, passwords_initial],
[Passwords.modify, passwords_initial],
[Passwords.verify, passwords_after_first_change],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Windows.add, { private: true }],
[Passwords.verify, passwords_after_first_change],
[Passwords.modify, passwords_after_first_change],
[Passwords.verify, passwords_after_second_change],
[Sync]
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Passwords.verify, passwords_after_second_change]
]);
--- a/services/sync/tests/tps/test_privbrw_tabs.js
+++ b/services/sync/tests/tps/test_privbrw_tabs.js
@@ -57,31 +57,31 @@ var tabs3 = [
profile: "profile1"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Tabs.add, tabs1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Tabs.verify, tabs1],
[Tabs.add, tabs2],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Windows.add, { private: true }],
[Tabs.add, tabs3],
[Sync]
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Tabs.verifyNot, tabs3]
]);
--- a/services/sync/tests/tps/test_special_tabs.js
+++ b/services/sync/tests/tps/test_special_tabs.js
@@ -60,19 +60,19 @@ var tabs3 = [
title: "Credits",
profile: "profile1"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Tabs.add, tabs1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Tabs.verify, tabs2],
[Tabs.verifyNot, tabs3]
]);
--- a/services/sync/tests/tps/test_sync.js
+++ b/services/sync/tests/tps/test_sync.js
@@ -369,55 +369,55 @@ var passwords_after_second_modify = [
passwordField: "pword"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Bookmarks.add, bookmarks_initial],
[Passwords.add, passwords_initial],
[History.add, history_initial],
[Sync],
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Bookmarks.verify, bookmarks_initial],
[Passwords.verify, passwords_initial],
[History.verify, history_initial],
[Bookmarks.modify, bookmarks_initial],
[Passwords.modify, passwords_initial],
[History.delete, history_to_delete],
[Bookmarks.verify, bookmarks_after_first_modify],
[Passwords.verify, passwords_after_first_modify],
[History.verify, history_after_delete],
[History.verifyNot, history_absent],
[Sync],
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Bookmarks.verify, bookmarks_after_first_modify],
[Passwords.verify, passwords_after_first_modify],
[History.verify, history_after_delete],
[Bookmarks.modify, bookmarks_after_first_modify],
[Passwords.modify, passwords_after_first_modify],
[Bookmarks.delete, bookmarks_to_delete],
[Passwords.delete, passwords_to_delete],
[Bookmarks.verify, bookmarks_after_second_modify],
[Passwords.verify, passwords_after_second_modify],
[Bookmarks.verifyNot, bookmarks_absent],
[Passwords.verifyNot, passwords_absent],
[Sync],
]);
-Phase('phase4', [
+Phase("phase4", [
[Sync],
[Bookmarks.verify, bookmarks_after_second_modify],
[Passwords.verify, passwords_after_second_modify],
[Bookmarks.verifyNot, bookmarks_absent],
[Passwords.verifyNot, passwords_absent],
[History.verifyNot, history_absent],
]);
--- a/services/sync/tests/tps/test_tabs.js
+++ b/services/sync/tests/tps/test_tabs.js
@@ -36,24 +36,24 @@ var tabs2 = [
profile: "profile2"
}
];
/*
* Test phases
*/
-Phase('phase1', [
+Phase("phase1", [
[Tabs.add, tabs1],
[Sync]
]);
-Phase('phase2', [
+Phase("phase2", [
[Sync],
[Tabs.verify, tabs1],
[Tabs.add, tabs2],
[Sync]
]);
-Phase('phase3', [
+Phase("phase3", [
[Sync],
[Tabs.verify, tabs2]
]);
--- a/services/sync/tests/unit/head_helpers.js
+++ b/services/sync/tests/unit/head_helpers.js
@@ -2,17 +2,17 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-common/async.js");
Cu.import("resource://testing-common/services/common/utils.js");
Cu.import("resource://testing-common/PlacesTestUtils.jsm");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-XPCOMUtils.defineLazyGetter(this, 'SyncPingSchema', function() {
+XPCOMUtils.defineLazyGetter(this, "SyncPingSchema", function() {
let ns = {};
Cu.import("resource://gre/modules/FileUtils.jsm", ns);
let stream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
let jsonReader = Cc["@mozilla.org/dom/json;1"]
.createInstance(Components.interfaces.nsIJSON);
let schema;
try {
@@ -24,17 +24,17 @@ XPCOMUtils.defineLazyGetter(this, 'SyncP
}
// Allow tests to make whatever engines they want, this shouldn't cause
// validation failure.
schema.definitions.engine.properties.name = { type: "string" };
return schema;
});
-XPCOMUtils.defineLazyGetter(this, 'SyncPingValidator', function() {
+XPCOMUtils.defineLazyGetter(this, "SyncPingValidator", function() {
let ns = {};
Cu.import("resource://testing-common/ajv-4.1.1.js", ns);
let ajv = new ns.Ajv({ async: "co*" });
return ajv.compile(SyncPingSchema);
});
var provider = {
getFile(prop, persistent) {
--- a/services/sync/tests/unit/test_bookmark_invalid.js
+++ b/services/sync/tests/unit/test_bookmark_invalid.js
@@ -52,11 +52,11 @@ add_task(async function test_ignore_miss
});
// Ensure that this doesn't throw even though the DB is now in a bad state (a
// bookmark has an illegal url).
engine._buildGUIDMap();
});
function run_test() {
- initTestLogging('Trace');
+ initTestLogging("Trace");
run_next_test();
}
--- a/services/sync/tests/unit/test_bookmark_store.js
+++ b/services/sync/tests/unit/test_bookmark_store.js
@@ -526,11 +526,11 @@ add_task(async function test_delete_buff
} finally {
_("Clean up.");
store.wipe();
}
});
function run_test() {
- initTestLogging('Trace');
+ initTestLogging("Trace");
run_next_test();
}
--- a/services/sync/tests/unit/test_bookmark_tracker.js
+++ b/services/sync/tests/unit/test_bookmark_tracker.js
@@ -1045,26 +1045,26 @@ add_task(async function test_onItemMoved
let tb_guid = engine._store.GUIDForId(tb_id);
_("Thunderbird GUID: " + tb_guid);
await startTracking();
// Moving within the folder will just track the folder.
PlacesUtils.bookmarks.moveItem(
tb_id, PlacesUtils.bookmarks.bookmarksMenuFolder, 0);
- await verifyTrackedItems(['menu']);
+ await verifyTrackedItems(["menu"]);
do_check_eq(tracker.score, SCORE_INCREMENT_XLARGE);
await resetTracker();
await PlacesTestUtils.markBookmarksAsSynced();
// Moving a bookmark to a different folder will track the old
// folder, the new folder and the bookmark.
PlacesUtils.bookmarks.moveItem(fx_id, PlacesUtils.bookmarks.toolbarFolder,
PlacesUtils.bookmarks.DEFAULT_INDEX);
- await verifyTrackedItems(['menu', 'toolbar', fx_guid]);
+ await verifyTrackedItems(["menu", "toolbar", fx_guid]);
do_check_eq(tracker.score, SCORE_INCREMENT_XLARGE);
} finally {
_("Clean up.");
await cleanup();
}
});
@@ -1090,27 +1090,27 @@ add_task(async function test_async_onIte
await startTracking();
_("Repositioning a bookmark should track the folder");
await PlacesUtils.bookmarks.update({
guid: tbBmk.guid,
parentGuid: PlacesUtils.bookmarks.menuGuid,
index: 0,
});
- await verifyTrackedItems(['menu']);
+ await verifyTrackedItems(["menu"]);
do_check_eq(tracker.score, SCORE_INCREMENT_XLARGE);
await resetTracker();
_("Reparenting a bookmark should track both folders and the bookmark");
await PlacesUtils.bookmarks.update({
guid: tbBmk.guid,
parentGuid: PlacesUtils.bookmarks.toolbarGuid,
index: PlacesUtils.bookmarks.DEFAULT_INDEX,
});
- await verifyTrackedItems(['menu', 'toolbar', tbBmk.guid]);
+ await verifyTrackedItems(["menu", "toolbar", tbBmk.guid]);
do_check_eq(tracker.score, SCORE_INCREMENT_XLARGE);
} finally {
_("Clean up.");
await cleanup();
}
});
add_task(async function test_async_onItemMoved_reorder() {
@@ -1315,17 +1315,17 @@ add_task(async function test_treeMoved()
let tb_guid = engine._store.GUIDForId(tb_id);
await startTracking();
// Move folder 2 to be a sibling of folder1.
PlacesUtils.bookmarks.moveItem(
folder2_id, PlacesUtils.bookmarks.bookmarksMenuFolder, 0);
// the menu and both folders should be tracked, the children should not be.
- await verifyTrackedItems(['menu', folder1_guid, folder2_guid]);
+ await verifyTrackedItems(["menu", folder1_guid, folder2_guid]);
do_check_eq(tracker.score, SCORE_INCREMENT_XLARGE);
} finally {
_("Clean up.");
await cleanup();
}
});
add_task(async function test_onItemDeleted() {
@@ -1345,17 +1345,17 @@ add_task(async function test_onItemDelet
"Get Thunderbird!");
let tb_guid = engine._store.GUIDForId(tb_id);
await startTracking();
// Delete the last item - the item and parent should be tracked.
PlacesUtils.bookmarks.removeItem(tb_id);
- await verifyTrackedItems(['menu', tb_guid]);
+ await verifyTrackedItems(["menu", tb_guid]);
do_check_eq(tracker.score, SCORE_INCREMENT_XLARGE);
} finally {
_("Clean up.");
await cleanup();
}
});
add_task(async function test_async_onItemDeleted() {
--- a/services/sync/tests/unit/test_bookmark_validator.js
+++ b/services/sync/tests/unit/test_bookmark_validator.js
@@ -5,147 +5,147 @@ Components.utils.import("resource://serv
Components.utils.import("resource://services-sync/util.js");
function inspectServerRecords(data) {
return new BookmarkValidator().inspectServerRecords(data);
}
add_test(function test_isr_rootOnServer() {
let c = inspectServerRecords([{
- id: 'places',
- type: 'folder',
+ id: "places",
+ type: "folder",
children: [],
}]);
ok(c.problemData.rootOnServer);
run_next_test();
});
add_test(function test_isr_empty() {
let c = inspectServerRecords([]);
ok(!c.problemData.rootOnServer);
notEqual(c.root, null);
run_next_test();
});
add_test(function test_isr_cycles() {
let c = inspectServerRecords([
- {id: 'C', type: 'folder', children: ['A', 'B'], parentid: 'places'},
- {id: 'A', type: 'folder', children: ['B'], parentid: 'B'},
- {id: 'B', type: 'folder', children: ['A'], parentid: 'A'},
+ {id: "C", type: "folder", children: ["A", "B"], parentid: "places"},
+ {id: "A", type: "folder", children: ["B"], parentid: "B"},
+ {id: "B", type: "folder", children: ["A"], parentid: "A"},
]).problemData;
equal(c.cycles.length, 1);
- ok(c.cycles[0].indexOf('A') >= 0);
- ok(c.cycles[0].indexOf('B') >= 0);
+ ok(c.cycles[0].indexOf("A") >= 0);
+ ok(c.cycles[0].indexOf("B") >= 0);
run_next_test();
});
add_test(function test_isr_orphansMultiParents() {
let c = inspectServerRecords([
- { id: 'A', type: 'bookmark', parentid: 'D' },
- { id: 'B', type: 'folder', parentid: 'places', children: ['A']},
- { id: 'C', type: 'folder', parentid: 'places', children: ['A']},
+ { id: "A", type: "bookmark", parentid: "D" },
+ { id: "B", type: "folder", parentid: "places", children: ["A"]},
+ { id: "C", type: "folder", parentid: "places", children: ["A"]},
]).problemData;
deepEqual(c.orphans, [{ id: "A", parent: "D" }]);
equal(c.multipleParents.length, 1)
- ok(c.multipleParents[0].parents.indexOf('B') >= 0);
- ok(c.multipleParents[0].parents.indexOf('C') >= 0);
+ ok(c.multipleParents[0].parents.indexOf("B") >= 0);
+ ok(c.multipleParents[0].parents.indexOf("C") >= 0);
run_next_test();
});
add_test(function test_isr_orphansMultiParents2() {
let c = inspectServerRecords([
- { id: 'A', type: 'bookmark', parentid: 'D' },
- { id: 'B', type: 'folder', parentid: 'places', children: ['A']},
+ { id: "A", type: "bookmark", parentid: "D" },
+ { id: "B", type: "folder", parentid: "places", children: ["A"]},
]).problemData;
equal(c.orphans.length, 1);
- equal(c.orphans[0].id, 'A');
+ equal(c.orphans[0].id, "A");
equal(c.multipleParents.length, 0);
run_next_test();
});
add_test(function test_isr_deletedParents() {
let c = inspectServerRecords([
- { id: 'A', type: 'bookmark', parentid: 'B' },
- { id: 'B', type: 'folder', parentid: 'places', children: ['A']},
- { id: 'B', type: 'item', deleted: true},
+ { id: "A", type: "bookmark", parentid: "B" },
+ { id: "B", type: "folder", parentid: "places", children: ["A"]},
+ { id: "B", type: "item", deleted: true},
]).problemData;
- deepEqual(c.deletedParents, ['A'])
+ deepEqual(c.deletedParents, ["A"])
run_next_test();
});
add_test(function test_isr_badChildren() {
let c = inspectServerRecords([
- { id: 'A', type: 'bookmark', parentid: 'places', children: ['B', 'C'] },
- { id: 'C', type: 'bookmark', parentid: 'A' }
+ { id: "A", type: "bookmark", parentid: "places", children: ["B", "C"] },
+ { id: "C", type: "bookmark", parentid: "A" }
]).problemData;
- deepEqual(c.childrenOnNonFolder, ['A'])
- deepEqual(c.missingChildren, [{parent: 'A', child: 'B'}]);
- deepEqual(c.parentNotFolder, ['C']);
+ deepEqual(c.childrenOnNonFolder, ["A"])
+ deepEqual(c.missingChildren, [{parent: "A", child: "B"}]);
+ deepEqual(c.parentNotFolder, ["C"]);
run_next_test();
});
add_test(function test_isr_parentChildMismatches() {
let c = inspectServerRecords([
- { id: 'A', type: 'folder', parentid: 'places', children: [] },
- { id: 'B', type: 'bookmark', parentid: 'A' }
+ { id: "A", type: "folder", parentid: "places", children: [] },
+ { id: "B", type: "bookmark", parentid: "A" }
]).problemData;
- deepEqual(c.parentChildMismatches, [{parent: 'A', child: 'B'}]);
+ deepEqual(c.parentChildMismatches, [{parent: "A", child: "B"}]);
run_next_test();
});
add_test(function test_isr_duplicatesAndMissingIDs() {
let c = inspectServerRecords([
- {id: 'A', type: 'folder', parentid: 'places', children: []},
- {id: 'A', type: 'folder', parentid: 'places', children: []},
- {type: 'folder', parentid: 'places', children: []}
+ {id: "A", type: "folder", parentid: "places", children: []},
+ {id: "A", type: "folder", parentid: "places", children: []},
+ {type: "folder", parentid: "places", children: []}
]).problemData;
equal(c.missingIDs, 1);
- deepEqual(c.duplicates, ['A']);
+ deepEqual(c.duplicates, ["A"]);
run_next_test();
});
add_test(function test_isr_duplicateChildren() {
let c = inspectServerRecords([
- {id: 'A', type: 'folder', parentid: 'places', children: ['B', 'B']},
- {id: 'B', type: 'bookmark', parentid: 'A'},
+ {id: "A", type: "folder", parentid: "places", children: ["B", "B"]},
+ {id: "B", type: "bookmark", parentid: "A"},
]).problemData;
- deepEqual(c.duplicateChildren, ['A']);
+ deepEqual(c.duplicateChildren, ["A"]);
run_next_test();
});
// Each compareServerWithClient test mutates these, so we can't just keep them
// global
function getDummyServerAndClient() {
let server = [
{
- id: 'menu',
- parentid: 'places',
- type: 'folder',
- parentName: '',
- title: 'foo',
- children: ['bbbbbbbbbbbb', 'cccccccccccc']
+ id: "menu",
+ parentid: "places",
+ type: "folder",
+ parentName: "",
+ title: "foo",
+ children: ["bbbbbbbbbbbb", "cccccccccccc"]
},
{
- id: 'bbbbbbbbbbbb',
- type: 'bookmark',
- parentid: 'menu',
- parentName: 'foo',
- title: 'bar',
- bmkUri: 'http://baz.com'
+ id: "bbbbbbbbbbbb",
+ type: "bookmark",
+ parentid: "menu",
+ parentName: "foo",
+ title: "bar",
+ bmkUri: "http://baz.com"
},
{
- id: 'cccccccccccc',
- parentid: 'menu',
- parentName: 'foo',
- title: '',
- type: 'query',
- bmkUri: 'place:type=6&sort=14&maxResults=10'
+ id: "cccccccccccc",
+ parentid: "menu",
+ parentName: "foo",
+ title: "",
+ type: "query",
+ bmkUri: "place:type=6&sort=14&maxResults=10"
}
];
let client = {
"guid": "root________",
"title": "",
"id": 1,
"type": "text/x-moz-place-container",
@@ -196,50 +196,50 @@ add_test(function test_cswc_valid() {
add_test(function test_cswc_serverMissing() {
let {server, client} = getDummyServerAndClient();
// remove c
server.pop();
server[0].children.pop();
let c = new BookmarkValidator().compareServerWithClient(server, client).problemData;
- deepEqual(c.serverMissing, ['cccccccccccc']);
+ deepEqual(c.serverMissing, ["cccccccccccc"]);
equal(c.clientMissing.length, 0);
- deepEqual(c.structuralDifferences, [{id: 'menu', differences: ['childGUIDs']}]);
+ deepEqual(c.structuralDifferences, [{id: "menu", differences: ["childGUIDs"]}]);
run_next_test();
});
add_test(function test_cswc_clientMissing() {
let {server, client} = getDummyServerAndClient();
client.children[0].children.pop();
let c = new BookmarkValidator().compareServerWithClient(server, client).problemData;
- deepEqual(c.clientMissing, ['cccccccccccc']);
+ deepEqual(c.clientMissing, ["cccccccccccc"]);
equal(c.serverMissing.length, 0);
- deepEqual(c.structuralDifferences, [{id: 'menu', differences: ['childGUIDs']}]);
+ deepEqual(c.structuralDifferences, [{id: "menu", differences: ["childGUIDs"]}]);
run_next_test();
});
add_test(function test_cswc_differences() {
{
let {server, client} = getDummyServerAndClient();
- client.children[0].children[0].title = 'asdf';
+ client.children[0].children[0].title = "asdf";
let c = new BookmarkValidator().compareServerWithClient(server, client).problemData;
equal(c.clientMissing.length, 0);
equal(c.serverMissing.length, 0);
- deepEqual(c.differences, [{id: 'bbbbbbbbbbbb', differences: ['title']}]);
+ deepEqual(c.differences, [{id: "bbbbbbbbbbbb", differences: ["title"]}]);
}
{
let {server, client} = getDummyServerAndClient();
- server[2].type = 'bookmark';
+ server[2].type = "bookmark";
let c = new BookmarkValidator().compareServerWithClient(server, client).problemData;
equal(c.clientMissing.length, 0);
equal(c.serverMissing.length, 0);
- deepEqual(c.differences, [{id: 'cccccccccccc', differences: ['type']}]);
+ deepEqual(c.differences, [{id: "cccccccccccc", differences: ["type"]}]);
}
run_next_test();
});
add_test(function test_cswc_serverUnexpected() {
let {server, client} = getDummyServerAndClient();
client.children.push({
"guid": "dddddddddddd",
@@ -271,29 +271,29 @@ add_test(function test_cswc_serverUnexpe
"expires": 4,
"value": "History"
}],
"type": "text/x-moz-place",
"uri": "place:type=3&sort=4"
}]
});
server.push({
- id: 'dddddddddddd',
- parentid: 'places',
- parentName: '',
- title: '',
- type: 'folder',
- children: ['eeeeeeeeeeee']
+ id: "dddddddddddd",
+ parentid: "places",
+ parentName: "",
+ title: "",
+ type: "folder",
+ children: ["eeeeeeeeeeee"]
}, {
- id: 'eeeeeeeeeeee',
- parentid: 'dddddddddddd',
- parentName: '',
- title: 'History',
- type: 'query',
- bmkUri: 'place:type=3&sort=4'
+ id: "eeeeeeeeeeee",
+ parentid: "dddddddddddd",
+ parentName: "",
+ title: "History",
+ type: "query",
+ bmkUri: "place:type=3&sort=4"
});
let c = new BookmarkValidator().compareServerWithClient(server, client).problemData;
equal(c.clientMissing.length, 0);
equal(c.serverMissing.length, 0);
equal(c.serverUnexpected.length, 2);
deepEqual(c.serverUnexpected, ["dddddddddddd", "eeeeeeeeeeee"]);
run_next_test();
--- a/services/sync/tests/unit/test_browserid_identity.js
+++ b/services/sync/tests/unit/test_browserid_identity.js
@@ -154,37 +154,37 @@ add_task(async function test_initialiali
add_test(function test_getResourceAuthenticator() {
_("BrowserIDManager supplies a Resource Authenticator callback which returns a Hawk header.");
configureFxAccountIdentity(browseridManager);
let authenticator = browseridManager.getResourceAuthenticator();
do_check_true(!!authenticator);
let req = {uri: CommonUtils.makeURI(
"https://example.net/somewhere/over/the/rainbow"),
- method: 'GET'};
- let output = authenticator(req, 'GET');
- do_check_true('headers' in output);
- do_check_true('authorization' in output.headers);
- do_check_true(output.headers.authorization.startsWith('Hawk'));
+ method: "GET"};
+ let output = authenticator(req, "GET");
+ do_check_true("headers" in output);
+ do_check_true("authorization" in output.headers);
+ do_check_true(output.headers.authorization.startsWith("Hawk"));
_("Expected internal state after successful call.");
do_check_eq(browseridManager._token.uid, identityConfig.fxaccount.token.uid);
run_next_test();
}
);
add_test(function test_getRESTRequestAuthenticator() {
_("BrowserIDManager supplies a REST Request Authenticator callback which sets a Hawk header on a request object.");
let request = new SyncStorageRequest(
"https://example.net/somewhere/over/the/rainbow");
let authenticator = browseridManager.getRESTRequestAuthenticator();
do_check_true(!!authenticator);
- let output = authenticator(request, 'GET');
+ let output = authenticator(request, "GET");
do_check_eq(request.uri, output.uri);
- do_check_true(output._headers.authorization.startsWith('Hawk'));
- do_check_true(output._headers.authorization.includes('nonce'));
+ do_check_true(output._headers.authorization.startsWith("Hawk"));
+ do_check_true(output._headers.authorization.includes("nonce"));
do_check_true(browseridManager.hasValidToken());
run_next_test();
}
);
add_test(function test_resourceAuthenticatorSkew() {
_("BrowserIDManager Resource Authenticator compensates for clock skew in Hawk header.");
@@ -192,17 +192,17 @@ add_test(function test_resourceAuthentic
// We pick a date in the past so we don't risk concealing bugs in code that
// uses new Date() instead of our given date.
let now = new Date("Fri Apr 09 2004 00:00:00 GMT-0700").valueOf() + 12 * HOUR_MS;
let browseridManager = new BrowserIDManager();
let hawkClient = new HawkClient("https://example.net/v1", "/foo");
// mock fxa hawk client skew
hawkClient.now = function() {
- dump("mocked client now: " + now + '\n');
+ dump("mocked client now: " + now + "\n");
return now;
}
// Imagine there's already been one fxa request and the hawk client has
// already detected skew vs the fxa auth server.
let localtimeOffsetMsec = -1 * 12 * HOUR_MS;
hawkClient._localtimeOffsetMsec = localtimeOffsetMsec;
let fxaClient = new MockFxAccountsClient();
@@ -240,20 +240,20 @@ add_test(function test_resourceAuthentic
localtimeOffsetMsec);
do_check_eq(browseridManager._fxaService.now(), now);
do_check_eq(browseridManager._fxaService.localtimeOffsetMsec,
localtimeOffsetMsec);
let request = new SyncStorageRequest("https://example.net/i/like/pie/");
let authenticator = browseridManager.getResourceAuthenticator();
- let output = authenticator(request, 'GET');
+ let output = authenticator(request, "GET");
dump("output" + JSON.stringify(output));
let authHeader = output.headers.authorization;
- do_check_true(authHeader.startsWith('Hawk'));
+ do_check_true(authHeader.startsWith("Hawk"));
// Skew correction is applied in the header and we're within the two-minute
// window.
do_check_eq(getTimestamp(authHeader), now - 12 * HOUR_MS);
do_check_true(
(getTimestampDelta(authHeader, now) - 12 * HOUR_MS) < 2 * MINUTE_MS);
run_next_test();
@@ -287,20 +287,20 @@ add_test(function test_RESTResourceAuthe
fxa.internal.currentAccountState.signedInUser = browseridManager._fxaService.internal.currentAccountState.signedInUser;
browseridManager._fxaService = fxa;
do_check_eq(browseridManager._fxaService.internal.now(), now);
let request = new SyncStorageRequest("https://example.net/i/like/pie/");
let authenticator = browseridManager.getResourceAuthenticator();
- let output = authenticator(request, 'GET');
+ let output = authenticator(request, "GET");
dump("output" + JSON.stringify(output));
let authHeader = output.headers.authorization;
- do_check_true(authHeader.startsWith('Hawk'));
+ do_check_true(authHeader.startsWith("Hawk"));
// Skew correction is applied in the header and we're within the two-minute
// window.
do_check_eq(getTimestamp(authHeader), now - 12 * HOUR_MS);
do_check_true(
(getTimestampDelta(authHeader, now) - 12 * HOUR_MS) < 2 * MINUTE_MS);
run_next_test();
@@ -343,18 +343,18 @@ add_test(function test_tokenExpiration()
_("BrowserIDManager notices token expiration:");
let bimExp = new BrowserIDManager();
configureFxAccountIdentity(bimExp, identityConfig);
let authenticator = bimExp.getResourceAuthenticator();
do_check_true(!!authenticator);
let req = {uri: CommonUtils.makeURI(
"https://example.net/somewhere/over/the/rainbow"),
- method: 'GET'};
- authenticator(req, 'GET');
+ method: "GET"};
+ authenticator(req, "GET");
// Mock the clock.
_("Forcing the token to expire ...");
Object.defineProperty(bimExp, "_now", {
value: function customNow() {
return (Date.now() + 3000001);
},
writable: true,
@@ -694,17 +694,17 @@ add_task(async function test_getKeysMiss
_("BrowserIDManager correctly handles getKeys succeeding but not returning keys.");
let browseridManager = new BrowserIDManager();
let identityConfig = makeIdentityConfig();
// our mock identity config already has kA and kB - remove them or we never
// try and fetch them.
delete identityConfig.fxaccount.user.kA;
delete identityConfig.fxaccount.user.kB;
- identityConfig.fxaccount.user.keyFetchToken = 'keyFetchToken';
+ identityConfig.fxaccount.user.keyFetchToken = "keyFetchToken";
configureFxAccountIdentity(browseridManager, identityConfig);
// Mock a fxAccounts object that returns no keys
let fxa = new FxAccounts({
fetchAndUnwrapKeys() {
return Promise.resolve({});
},
--- a/services/sync/tests/unit/test_collection_inc_get.js
+++ b/services/sync/tests/unit/test_collection_inc_get.js
@@ -19,31 +19,31 @@ function run_test() {
_("Got record:", JSON.stringify(rec));
rec.collection = "uri"; // This would be done by an engine, so do it here.
do_check_eq(rec.collection, "uri");
do_check_eq(rec.id, "hello");
do_check_eq(rec.uri(base).spec, "http://fake/uri/hello");
do_check_eq(rec.payload, "world");
};
coll._onProgress.call(stream);
- do_check_eq(stream._data, '');
+ do_check_eq(stream._data, "");
do_check_true(called);
_("\n");
_("Parse record with payload");
called = false;
stream._data = '{"payload":"{\\"value\\":123}"}\n';
coll.recordHandler = function(rec) {
called = true;
_("Got record:", JSON.stringify(rec));
do_check_eq(rec.payload.value, 123);
};
coll._onProgress.call(stream);
- do_check_eq(stream._data, '');
+ do_check_eq(stream._data, "");
do_check_true(called);
_("\n");
_("Parse multiple records in one go");
called = false;
recCount = 0;
sum = 0;
@@ -77,17 +77,17 @@ function run_test() {
default:
do_throw("unexpected number of record counts", recCount);
break;
}
};
coll._onProgress.call(stream);
do_check_eq(recCount, 3);
do_check_eq(sum, 111);
- do_check_eq(stream._data, '');
+ do_check_eq(stream._data, "");
do_check_true(called);
_("\n");
_("Handle incremental data incoming");
called = false;
recCount = 0;
sum = 0;
@@ -114,17 +114,17 @@ function run_test() {
recCount++;
sum += rec.payload.value;
};
coll._onProgress.call(stream);
_("should have 1 record with sum 100");
do_check_eq(recCount, 1);
do_check_eq(sum, 100);
_("all data should have been consumed including trailing comma");
- do_check_eq(stream._data, '');
+ do_check_eq(stream._data, "");
do_check_true(called);
_();
_("adding more data..");
called = false;
stream._data += '{"payload":"{\\"value\\":10}"';
coll.recordHandler = function(rec) {
called = true;
@@ -161,23 +161,23 @@ function run_test() {
break;
}
};
coll._onProgress.call(stream);
_("should have gotten all 3 records with sum 111");
do_check_eq(recCount, 3);
do_check_eq(sum, 111);
_("should have consumed all data");
- do_check_eq(stream._data, '');
+ do_check_eq(stream._data, "");
do_check_true(called);
_();
_("add no extra data");
called = false;
- stream._data += '';
+ stream._data += "";
coll.recordHandler = function(rec) {
called = true;
do_throw("shouldn't have gotten a record..");
};
coll._onProgress.call(stream);
_("should still have 3 records with sum 111");
do_check_eq(recCount, 3);
do_check_eq(sum, 111);
--- a/services/sync/tests/unit/test_corrupt_keys.js
+++ b/services/sync/tests/unit/test_corrupt_keys.js
@@ -93,17 +93,17 @@ add_task(async function test_locally_cha
let coll_modified = Service.collectionKeys.lastModified;
// Let's create some server side history records.
let liveKeys = Service.collectionKeys.keyForCollection("history");
_("Keys now: " + liveKeys.keyPair);
let visitType = Ci.nsINavHistoryService.TRANSITION_LINK;
let history = johndoe.createCollection("history");
for (let i = 0; i < 5; i++) {
- let id = 'record-no--' + i;
+ let id = "record-no--" + i;
let modified = Date.now() / 1000 - 60 * (i + 10);
let w = new CryptoWrapper("history", "id");
w.cleartext = {
id,
histUri: "http://foo/bar?" + id,
title: id,
sortindex: i,
@@ -150,17 +150,17 @@ add_task(async function test_locally_cha
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--2"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--3"));
do_check_true(await promiseIsURIVisited("http://foo/bar?record-no--4"));
do_check_eq(hmacErrorCount, 1);
_("Busting some new server values.");
// Now what happens if we corrupt the HMAC on the server?
for (let i = 5; i < 10; i++) {
- let id = 'record-no--' + i;
+ let id = "record-no--" + i;
let modified = 1 + (Date.now() / 1000);
let w = new CryptoWrapper("history", "id");
w.cleartext = {
id,
histUri: "http://foo/bar?" + id,
title: id,
sortindex: i,
--- a/services/sync/tests/unit/test_declined.js
+++ b/services/sync/tests/unit/test_declined.js
@@ -17,17 +17,17 @@ PetrolEngine.prototype.name = "petrol";
function DieselEngine() {}
DieselEngine.prototype.name = "diesel";
function DummyEngine() {}
DummyEngine.prototype.name = "dummy";
function ActualEngine() {}
ActualEngine.prototype = {__proto__: Engine.prototype,
- name: 'actual'};
+ name: "actual"};
function getEngineManager() {
let manager = new EngineManager(Service);
Service.engineManager = manager;
manager._engines = {
"petrol": new PetrolEngine(),
"diesel": new DieselEngine(),
"dummy": new DummyEngine(),
--- a/services/sync/tests/unit/test_enginemanager.js
+++ b/services/sync/tests/unit/test_enginemanager.js
@@ -14,44 +14,44 @@ PetrolEngine.prototype.name = "petrol";
function DieselEngine() {}
DieselEngine.prototype.name = "diesel";
function DummyEngine() {}
DummyEngine.prototype.name = "dummy";
function ActualEngine() {}
ActualEngine.prototype = {__proto__: Engine.prototype,
- name: 'actual'};
+ name: "actual"};
add_test(function test_basics() {
_("We start out with a clean slate");
let manager = new EngineManager(Service);
let engines = manager.getAll();
do_check_eq(engines.length, 0);
- do_check_eq(manager.get('dummy'), undefined);
+ do_check_eq(manager.get("dummy"), undefined);
_("Register an engine");
manager.register(DummyEngine);
- let dummy = manager.get('dummy');
+ let dummy = manager.get("dummy");
do_check_true(dummy instanceof DummyEngine);
engines = manager.getAll();
do_check_eq(engines.length, 1);
do_check_eq(engines[0], dummy);
_("Register an already registered engine is ignored");
manager.register(DummyEngine);
- do_check_eq(manager.get('dummy'), dummy);
+ do_check_eq(manager.get("dummy"), dummy);
_("Register multiple engines in one go");
manager.register([PetrolEngine, DieselEngine]);
- let petrol = manager.get('petrol');
- let diesel = manager.get('diesel');
+ let petrol = manager.get("petrol");
+ let diesel = manager.get("diesel");
do_check_true(petrol instanceof PetrolEngine);
do_check_true(diesel instanceof DieselEngine);
engines = manager.getAll();
do_check_eq(engines.length, 3);
do_check_neq(engines.indexOf(petrol), -1);
do_check_neq(engines.indexOf(diesel), -1);
@@ -88,27 +88,27 @@ add_test(function test_basics() {
dummy.syncPriority = 4;
engines = manager.getEnabled();
do_check_array_eq(engines, [petrol, diesel, dummy]);
_("Unregister an engine by name");
- manager.unregister('dummy');
- do_check_eq(manager.get('dummy'), undefined);
+ manager.unregister("dummy");
+ do_check_eq(manager.get("dummy"), undefined);
engines = manager.getAll();
do_check_eq(engines.length, 2);
do_check_eq(engines.indexOf(dummy), -1);
_("Unregister an engine by value");
// manager.unregister() checks for instanceof Engine, so let's make one:
manager.register(ActualEngine);
- let actual = manager.get('actual');
+ let actual = manager.get("actual");
do_check_true(actual instanceof ActualEngine);
do_check_true(actual instanceof Engine);
manager.unregister(actual);
- do_check_eq(manager.get('actual'), undefined);
+ do_check_eq(manager.get("actual"), undefined);
run_next_test();
});
--- a/services/sync/tests/unit/test_errorhandler_1.js
+++ b/services/sync/tests/unit/test_errorhandler_1.js
@@ -22,20 +22,20 @@ do_register_cleanup(function() {
});
});
var fakeServerUrl = "http://localhost:" + fakeServer.port;
const logsdir = FileUtils.getDir("ProfD", ["weave", "logs"], true);
const PROLONGED_ERROR_DURATION =
- (Svc.Prefs.get('errorhandler.networkFailureReportTimeout') * 2) * 1000;
+ (Svc.Prefs.get("errorhandler.networkFailureReportTimeout") * 2) * 1000;
const NON_PROLONGED_ERROR_DURATION =
- (Svc.Prefs.get('errorhandler.networkFailureReportTimeout') / 2) * 1000;
+ (Svc.Prefs.get("errorhandler.networkFailureReportTimeout") / 2) * 1000;
Service.engineManager.clear();
function setLastSync(lastSyncValue) {
Svc.Prefs.set("lastSync", (new Date(Date.now() - lastSyncValue)).toString());
}
var engineManager = Service.engineManager;
--- a/services/sync/tests/unit/test_errorhandler_2.js
+++ b/services/sync/tests/unit/test_errorhandler_2.js
@@ -22,20 +22,20 @@ do_register_cleanup(function() {
});
});
var fakeServerUrl = "http://localhost:" + fakeServer.port;
const logsdir = FileUtils.getDir("ProfD", ["weave", "logs"], true);
const PROLONGED_ERROR_DURATION =
- (Svc.Prefs.get('errorhandler.networkFailureReportTimeout') * 2) * 1000;
+ (Svc.Prefs.get("errorhandler.networkFailureReportTimeout") * 2) * 1000;
const NON_PROLONGED_ERROR_DURATION =
- (Svc.Prefs.get('errorhandler.networkFailureReportTimeout') / 2) * 1000;
+ (Svc.Prefs.get("errorhandler.networkFailureReportTimeout") / 2) * 1000;
Service.engineManager.clear();
function setLastSync(lastSyncValue) {
Svc.Prefs.set("lastSync", (new Date(Date.now() - lastSyncValue)).toString());
}
var engineManager = Service.engineManager;
--- a/services/sync/tests/unit/test_errorhandler_filelog.js
+++ b/services/sync/tests/unit/test_errorhandler_filelog.js
@@ -14,17 +14,17 @@ const logsdir = FileUtils.get
// Delay to wait before cleanup, to allow files to age.
// This is so large because the file timestamp granularity is per-second, and
// so otherwise we can end up with all of our files -- the ones we want to
// keep, and the ones we want to clean up -- having the same modified time.
const CLEANUP_DELAY = 2000;
const DELAY_BUFFER = 500; // Buffer for timers on different OS platforms.
const PROLONGED_ERROR_DURATION =
- (Svc.Prefs.get('errorhandler.networkFailureReportTimeout') * 2) * 1000;
+ (Svc.Prefs.get("errorhandler.networkFailureReportTimeout") * 2) * 1000;
var errorHandler = Service.errorHandler;
function setLastSync(lastSyncValue) {
Svc.Prefs.set("lastSync", (new Date(Date.now() - lastSyncValue)).toString());
}
function run_test() {
--- a/services/sync/tests/unit/test_fxa_node_reassignment.js
+++ b/services/sync/tests/unit/test_fxa_node_reassignment.js
@@ -80,17 +80,17 @@ function prepareServer(cbAfterTokenFetch
let numReassigns = 0;
return configureIdentity(config).then(() => {
Service.identity._tokenServerClient = {
getTokenFromBrowserIDAssertion(uri, assertion, cb) {
// Build a new URL with trailing zeros for the SYNC_VERSION part - this
// will still be seen as equivalent by the test server, but different
// by sync itself.
numReassigns += 1;
- let trailingZeros = new Array(numReassigns + 1).join('0');
+ let trailingZeros = new Array(numReassigns + 1).join("0");
let token = config.fxaccount.token;
token.endpoint = server.baseURI + "1.1" + trailingZeros + "/johndoe";
token.uid = config.username;
numTokenRequests += 1;
cb(null, token);
if (cbAfterTokenFetch) {
cbAfterTokenFetch();
}
--- a/services/sync/tests/unit/test_history_engine.js
+++ b/services/sync/tests/unit/test_history_engine.js
@@ -38,17 +38,17 @@ add_task(async function test_processInco
});
await SyncTestingInfrastructure(server);
// Let's create some 234 server side history records. They're all at least
// 10 minutes old.
let visitType = Ci.nsINavHistoryService.TRANSITION_LINK;
for (var i = 0; i < 234; i++) {
- let id = 'record-no' + ("00" + i).slice(-3);
+ let id = "record-no" + ("00" + i).slice(-3);
let modified = Date.now() / 1000 - 60 * (i + 10);
let payload = encryptPayload({
id,
histUri: "http://foo/bar?" + id,
title: id,
sortindex: i,
visits: [{date: (modified - 5) * 1000000, type: visitType}],
deleted: false});
--- a/services/sync/tests/unit/test_hmac_error.js
+++ b/services/sync/tests/unit/test_hmac_error.js
@@ -23,17 +23,17 @@ function shared_setup() {
// Make sure RotaryEngine is the only one we sync.
Service.engineManager._engines = {};
Service.engineManager.register(RotaryEngine);
let engine = Service.engineManager.get("rotary");
engine.enabled = true;
engine.lastSync = 123; // Needs to be non-zero so that tracker is queried.
engine._store.items = {flying: "LNER Class A3 4472",
scotsman: "Flying Scotsman"};
- engine._tracker.addChangedID('scotsman', 0);
+ engine._tracker.addChangedID("scotsman", 0);
do_check_eq(1, Service.engineManager.getEnabled().length);
let engines = {rotary: {version: engine.version,
syncID: engine.syncID},
clients: {version: Service.clientsEngine.version,
syncID: Service.clientsEngine.syncID}};
// Common server objects.
--- a/services/sync/tests/unit/test_keys.js
+++ b/services/sync/tests/unit/test_keys.js
@@ -223,18 +223,18 @@ add_test(function test_collections_manag
do_check_eq(wbo.collection, "crypto");
do_check_eq(wbo.id, "keys");
do_check_eq(undefined, wbo.modified);
do_check_eq(collectionKeys.lastModified, storage_keys.modified);
do_check_true(!!wbo.cleartext.default);
do_check_keypair_eq(payload.default, wbo.cleartext.default);
do_check_keypair_eq(payload.collections.bookmarks, wbo.cleartext.collections.bookmarks);
- do_check_true('bookmarks' in collectionKeys._collections);
- do_check_false('tabs' in collectionKeys._collections);
+ do_check_true("bookmarks" in collectionKeys._collections);
+ do_check_false("tabs" in collectionKeys._collections);
_("Updating contents twice with the same data doesn't proceed.");
storage_keys.encrypt(keyBundle);
do_check_false(collectionKeys.updateContents(keyBundle, storage_keys));
/*
* Test that we get the right keys out when we ask for
* a collection's tokens.
--- a/services/sync/tests/unit/test_postqueue.js
+++ b/services/sync/tests/unit/test_postqueue.js
@@ -36,17 +36,17 @@ add_test(function test_simple() {
max_post_records: 100,
max_batch_bytes: Infinity,
max_batch_records: Infinity,
}
const time = 11111111;
function* responseGenerator() {
- yield { success: true, status: 200, headers: { 'x-weave-timestamp': time + 100, 'x-last-modified': time + 100 } };
+ yield { success: true, status: 200, headers: { "x-weave-timestamp": time + 100, "x-last-modified": time + 100 } };
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
pq.enqueue(makeRecord(10));
pq.flush(true);
deepEqual(stats.posts, [{
nbytes: 12, // expect our 10 byte record plus "[]" to wrap it.
@@ -64,18 +64,18 @@ add_test(function test_max_post_bytes_no
max_post_bytes: 50,
max_post_records: 4,
max_batch_bytes: Infinity,
max_batch_records: Infinity,
}
const time = 11111111;
function* responseGenerator() {
- yield { success: true, status: 200, headers: { 'x-weave-timestamp': time + 100, 'x-last-modified': time + 100 } };
- yield { success: true, status: 200, headers: { 'x-weave-timestamp': time + 200, 'x-last-modified': time + 200 } };
+ yield { success: true, status: 200, headers: { "x-weave-timestamp": time + 100, "x-last-modified": time + 100 } };
+ yield { success: true, status: 200, headers: { "x-weave-timestamp": time + 200, "x-last-modified": time + 200 } };
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
pq.enqueue(makeRecord(20)); // total size now 22 bytes - "[" + record + "]"
pq.enqueue(makeRecord(20)); // total size now 43 bytes - "[" + record + "," + record + "]"
pq.enqueue(makeRecord(20)); // this will exceed our byte limit, so will be in the 2nd POST.
pq.flush(true);
@@ -104,18 +104,18 @@ add_test(function test_max_post_records_
max_post_records: 2,
max_batch_bytes: Infinity,
max_batch_records: Infinity,
}
const time = 11111111;
function* responseGenerator() {
- yield { success: true, status: 200, headers: { 'x-weave-timestamp': time + 100, 'x-last-modified': time + 100 } };
- yield { success: true, status: 200, headers: { 'x-weave-timestamp': time + 200, 'x-last-modified': time + 200 } };
+ yield { success: true, status: 200, headers: { "x-weave-timestamp": time + 100, "x-last-modified": time + 100 } };
+ yield { success: true, status: 200, headers: { "x-weave-timestamp": time + 200, "x-last-modified": time + 200 } };
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
pq.enqueue(makeRecord(20)); // total size now 22 bytes - "[" + record + "]"
pq.enqueue(makeRecord(20)); // total size now 43 bytes - "[" + record + "," + record + "]"
pq.enqueue(makeRecord(20)); // this will exceed our records limit, so will be in the 2nd POST.
pq.flush(true);
@@ -145,17 +145,17 @@ add_test(function test_single_batch() {
max_post_bytes: 1000,
max_post_records: 100,
max_batch_bytes: 2000,
max_batch_records: 200,
}
const time = 11111111;
function* responseGenerator() {
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time, 'x-weave-timestamp': time + 100 },
+ headers: { "x-last-modified": time, "x-weave-timestamp": time + 100 },
};
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
ok(pq.enqueue(makeRecord(10)).enqueued);
pq.flush(true);
deepEqual(stats.posts, [
@@ -178,40 +178,40 @@ add_test(function test_max_post_bytes_ba
max_post_records: 4,
max_batch_bytes: 5000,
max_batch_records: 100,
}
const time = 11111111;
function* responseGenerator() {
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time, 'x-weave-timestamp': time + 100 },
+ headers: { "x-last-modified": time, "x-weave-timestamp": time + 100 },
};
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time + 200, 'x-weave-timestamp': time + 200 },
+ headers: { "x-last-modified": time + 200, "x-weave-timestamp": time + 200 },
};
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
ok(pq.enqueue(makeRecord(20)).enqueued); // total size now 22 bytes - "[" + record + "]"
ok(pq.enqueue(makeRecord(20)).enqueued); // total size now 43 bytes - "[" + record + "," + record + "]"
ok(pq.enqueue(makeRecord(20)).enqueued); // this will exceed our byte limit, so will be in the 2nd POST.
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time]],
+ headers: [["x-if-unmodified-since", time]],
}, {
nbytes: 22,
commit: true,
batch: 1234,
- headers: [['x-if-unmodified-since', time]],
+ headers: [["x-if-unmodified-since", time]],
}
]);
equal(pq.lastModified, time + 200);
run_next_test();
});
@@ -223,26 +223,26 @@ add_test(function test_max_post_bytes_ba
max_batch_bytes: 70,
max_batch_records: 100,
}
const time0 = 11111111;
const time1 = 22222222;
function* responseGenerator() {
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time0, 'x-weave-timestamp': time0 + 100 },
+ headers: { "x-last-modified": time0, "x-weave-timestamp": time0 + 100 },
};
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time1, 'x-weave-timestamp': time1 },
+ headers: { "x-last-modified": time1, "x-weave-timestamp": time1 },
};
yield { success: true, status: 202, obj: { batch: 5678 },
- headers: { 'x-last-modified': time1, 'x-weave-timestamp': time1 + 100 },
+ headers: { "x-last-modified": time1, "x-weave-timestamp": time1 + 100 },
};
yield { success: true, status: 202, obj: { batch: 5678 },
- headers: { 'x-last-modified': time1 + 200, 'x-weave-timestamp': time1 + 200 },
+ headers: { "x-last-modified": time1 + 200, "x-weave-timestamp": time1 + 200 },
};
}
let { pq, stats } = makePostQueue(config, time0, responseGenerator());
ok(pq.enqueue(makeRecord(20)).enqueued); // total size now 22 bytes - "[" + record + "]"
ok(pq.enqueue(makeRecord(20)).enqueued); // total size now 43 bytes - "[" + record + "," + record + "]"
// this will exceed our POST byte limit, so will be in the 2nd POST - but still in the first batch.
ok(pq.enqueue(makeRecord(20)).enqueued); // 22 bytes for 2nd post, 55 bytes in the batch.
@@ -253,35 +253,35 @@ add_test(function test_max_post_bytes_ba
ok(pq.enqueue(makeRecord(20)).enqueued); // 22 bytes for 4th post/2nd batch
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time0]],
+ headers: [["x-if-unmodified-since", time0]],
}, {
// second post of 22 bytes in the first batch, committing it.
nbytes: 22,
commit: true,
batch: 1234,
- headers: [['x-if-unmodified-since', time0]],
+ headers: [["x-if-unmodified-since", time0]],
}, {
// 3rd post of 43 bytes in a new batch, not yet committing it.
nbytes: 43,
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time1]],
+ headers: [["x-if-unmodified-since", time1]],
}, {
// 4th post of 22 bytes in second batch, committing it.
nbytes: 22,
commit: true,
batch: 5678,
- headers: [['x-if-unmodified-since', time1]],
+ headers: [["x-if-unmodified-since", time1]],
},
]);
equal(pq.lastModified, time1 + 200);
run_next_test();
});
@@ -293,40 +293,40 @@ add_test(function test_max_post_bytes_ba
max_post_records: 2,
max_batch_bytes: 5000,
max_batch_records: 100,
}
const time = 11111111;
function* responseGenerator() {
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time, 'x-weave-timestamp': time + 100 },
+ headers: { "x-last-modified": time, "x-weave-timestamp": time + 100 },
};
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time + 200, 'x-weave-timestamp': time + 200 },
+ headers: { "x-last-modified": time + 200, "x-weave-timestamp": time + 200 },
};
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
ok(pq.enqueue(makeRecord(20)).enqueued); // total size now 22 bytes - "[" + record + "]"
ok(pq.enqueue(makeRecord(20)).enqueued); // total size now 43 bytes - "[" + record + "," + record + "]"
ok(pq.enqueue(makeRecord(20)).enqueued); // will exceed record limit, so will be in 2nd post.
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time]],
+ headers: [["x-if-unmodified-since", time]],
}, {
nbytes: 22,
commit: true,
batch: 1234,
- headers: [['x-if-unmodified-since', time]],
+ headers: [["x-if-unmodified-since", time]],
}
]);
equal(pq.lastModified, time + 200);
run_next_test();
});
@@ -337,20 +337,20 @@ add_test(function test_huge_record() {
max_post_records: 100,
max_batch_bytes: 5000,
max_batch_records: 100,
}
const time = 11111111;
function* responseGenerator() {
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time, 'x-weave-timestamp': time + 100 },
+ headers: { "x-last-modified": time, "x-weave-timestamp": time + 100 },
};
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time + 200, 'x-weave-timestamp': time + 200 },
+ headers: { "x-last-modified": time + 200, "x-weave-timestamp": time + 200 },
};
}
let { pq, stats } = makePostQueue(config, time, responseGenerator());
ok(pq.enqueue(makeRecord(20)).enqueued);
let { enqueued, error } = pq.enqueue(makeRecord(1000));
ok(!enqueued);
@@ -363,22 +363,22 @@ add_test(function test_huge_record() {
pq.flush(true);
deepEqual(stats.posts, [
{
nbytes: 43, // 43 for the first post
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time]],
+ headers: [["x-if-unmodified-since", time]],
}, {
nbytes: 22,
commit: true,
batch: 1234,
- headers: [['x-if-unmodified-since', time]],
+ headers: [["x-if-unmodified-since", time]],
}
]);
equal(pq.lastModified, time + 200);
run_next_test();
});
@@ -390,26 +390,26 @@ add_test(function test_max_records_batch
max_batch_bytes: 10000,
max_batch_records: 5,
}
const time0 = 11111111;
const time1 = 22222222;
function* responseGenerator() {
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time0, 'x-weave-timestamp': time0 + 100 },
+ headers: { "x-last-modified": time0, "x-weave-timestamp": time0 + 100 },
};
yield { success: true, status: 202, obj: { batch: 1234 },
- headers: { 'x-last-modified': time1, 'x-weave-timestamp': time1 },
+ headers: { "x-last-modified": time1, "x-weave-timestamp": time1 },
};
yield { success: true, status: 202, obj: { batch: 5678 },
- headers: { 'x-last-modified': time1, 'x-weave-timestamp': time1 + 100 },
+ headers: { "x-last-modified": time1, "x-weave-timestamp": time1 + 100 },
};
yield { success: true, status: 202, obj: { batch: 5678 },
- headers: { 'x-last-modified': time1 + 200, 'x-weave-timestamp': time1 + 200 },
+ headers: { "x-last-modified": time1 + 200, "x-weave-timestamp": time1 + 200 },
};
}
let { pq, stats } = makePostQueue(config, time0, responseGenerator());
ok(pq.enqueue(makeRecord(20)).enqueued);
ok(pq.enqueue(makeRecord(20)).enqueued);
ok(pq.enqueue(makeRecord(20)).enqueued);
@@ -425,31 +425,31 @@ add_test(function test_max_records_batch
pq.flush(true);
deepEqual(stats.posts, [
{ // 3 records
nbytes: 64,
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time0]],
+ headers: [["x-if-unmodified-since", time0]],
}, { // 2 records -- end batch1
nbytes: 43,
commit: true,
batch: 1234,
- headers: [['x-if-unmodified-since', time0]],
+ headers: [["x-if-unmodified-since", time0]],
}, { // 3 records
nbytes: 64,
commit: false,
batch: "true",
- headers: [['x-if-unmodified-since', time1]],
+ headers: [["x-if-unmodified-since", time1]],
}, { // 1 record -- end batch2
nbytes: 22,
commit: true,
batch: 5678,
- headers: [['x-if-unmodified-since', time1]],
+ headers: [["x-if-unmodified-since", time1]],
},
]);
equal(pq.lastModified, time1 + 200);
run_next_test();
});
--- a/services/sync/tests/unit/test_resource.js
+++ b/services/sync/tests/unit/test_resource.js
@@ -64,17 +64,17 @@ var sample_data = {
function server_upload(metadata, response) {
let body;
let input = readBytesFromInputStream(metadata.bodyInputStream);
if (input == JSON.stringify(sample_data)) {
body = "Valid data upload via " + metadata.method;
response.setStatusLine(metadata.httpVersion, 200, "OK");
} else {
- body = "Invalid data upload via " + metadata.method + ': ' + input;
+ body = "Invalid data upload via " + metadata.method + ": " + input;
response.setStatusLine(metadata.httpVersion, 500, "Internal Server Error");
}
response.bodyOutputStream.write(body, body.length);
}
function server_delete(metadata, response) {
let body;
@@ -93,38 +93,38 @@ function server_json(metadata, response)
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
const TIMESTAMP = 1274380461;
function server_timestamp(metadata, response) {
let body = "Thank you for your request";
- response.setHeader("X-Weave-Timestamp", '' + TIMESTAMP, false);
+ response.setHeader("X-Weave-Timestamp", "" + TIMESTAMP, false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_backoff(metadata, response) {
let body = "Hey, back off!";
- response.setHeader("X-Weave-Backoff", '600', false);
+ response.setHeader("X-Weave-Backoff", "600", false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_quota_notice(request, response) {
let body = "You're approaching quota.";
- response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
+ response.setHeader("X-Weave-Quota-Remaining", "1048576", false);
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_quota_error(request, response) {
let body = "14";
- response.setHeader("X-Weave-Quota-Remaining", '-1024', false);
+ response.setHeader("X-Weave-Quota-Remaining", "-1024", false);
response.setStatusLine(request.httpVersion, 400, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_headers(metadata, response) {
let ignore_headers = ["host", "user-agent", "accept", "accept-language",
"accept-encoding", "accept-charset", "keep-alive",
"connection", "pragma", "cache-control",
@@ -148,17 +148,17 @@ function server_headers(metadata, respon
response.bodyOutputStream.write(body, body.length);
}
function run_test() {
initTestLogging("Trace");
do_test_pending();
- let logger = Log.repository.getLogger('Test');
+ let logger = Log.repository.getLogger("Test");
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
let server = httpd_setup({
"/open": server_open,
"/protected": server_protected,
"/404": server_404,
"/upload": server_upload,
"/delete": server_delete,
@@ -336,52 +336,52 @@ function run_test() {
do_check_eq(AsyncResource.serverTime, null);
let res8 = new Resource(server.baseURI + "/timestamp");
content = res8.get();
do_check_eq(AsyncResource.serverTime, TIMESTAMP);
_("GET: no special request headers");
let res9 = new Resource(server.baseURI + "/headers");
content = res9.get();
- do_check_eq(content, '{}');
+ do_check_eq(content, "{}");
_("PUT: Content-Type defaults to text/plain");
- content = res9.put('data');
+ content = res9.put("data");
do_check_eq(content, JSON.stringify({"content-type": "text/plain"}));
_("POST: Content-Type defaults to text/plain");
- content = res9.post('data');
+ content = res9.post("data");
do_check_eq(content, JSON.stringify({"content-type": "text/plain"}));
_("setHeader(): setting simple header");
- res9.setHeader('X-What-Is-Weave', 'awesome');
- do_check_eq(res9.headers['x-what-is-weave'], 'awesome');
+ res9.setHeader("X-What-Is-Weave", "awesome");
+ do_check_eq(res9.headers["x-what-is-weave"], "awesome");
content = res9.get();
do_check_eq(content, JSON.stringify({"x-what-is-weave": "awesome"}));
_("setHeader(): setting multiple headers, overwriting existing header");
- res9.setHeader('X-WHAT-is-Weave', 'more awesomer');
- res9.setHeader('X-Another-Header', 'hello world');
- do_check_eq(res9.headers['x-what-is-weave'], 'more awesomer');
- do_check_eq(res9.headers['x-another-header'], 'hello world');
+ res9.setHeader("X-WHAT-is-Weave", "more awesomer");
+ res9.setHeader("X-Another-Header", "hello world");
+ do_check_eq(res9.headers["x-what-is-weave"], "more awesomer");
+ do_check_eq(res9.headers["x-another-header"], "hello world");
content = res9.get();
do_check_eq(content, JSON.stringify({"x-another-header": "hello world",
"x-what-is-weave": "more awesomer"}));
_("Setting headers object");
res9.headers = {};
content = res9.get();
do_check_eq(content, "{}");
_("PUT/POST: override default Content-Type");
- res9.setHeader('Content-Type', 'application/foobar');
- do_check_eq(res9.headers['content-type'], 'application/foobar');
- content = res9.put('data');
+ res9.setHeader("Content-Type", "application/foobar");
+ do_check_eq(res9.headers["content-type"], "application/foobar");
+ content = res9.put("data");
do_check_eq(content, JSON.stringify({"content-type": "application/foobar"}));
- content = res9.post('data');
+ content = res9.post("data");
do_check_eq(content, JSON.stringify({"content-type": "application/foobar"}));
_("X-Weave-Backoff header notifies observer");
let backoffInterval;
function onBackoff(subject, data) {
backoffInterval = subject;
}
--- a/services/sync/tests/unit/test_resource_async.js
+++ b/services/sync/tests/unit/test_resource_async.js
@@ -64,17 +64,17 @@ var sample_data = {
function server_upload(metadata, response) {
let body;
let input = readBytesFromInputStream(metadata.bodyInputStream);
if (input == JSON.stringify(sample_data)) {
body = "Valid data upload via " + metadata.method;
response.setStatusLine(metadata.httpVersion, 200, "OK");
} else {
- body = "Invalid data upload via " + metadata.method + ': ' + input;
+ body = "Invalid data upload via " + metadata.method + ": " + input;
response.setStatusLine(metadata.httpVersion, 500, "Internal Server Error");
}
response.bodyOutputStream.write(body, body.length);
}
function server_delete(metadata, response) {
let body;
@@ -93,38 +93,38 @@ function server_json(metadata, response)
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
const TIMESTAMP = 1274380461;
function server_timestamp(metadata, response) {
let body = "Thank you for your request";
- response.setHeader("X-Weave-Timestamp", '' + TIMESTAMP, false);
+ response.setHeader("X-Weave-Timestamp", "" + TIMESTAMP, false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_backoff(metadata, response) {
let body = "Hey, back off!";
- response.setHeader("X-Weave-Backoff", '600', false);
+ response.setHeader("X-Weave-Backoff", "600", false);
response.setStatusLine(metadata.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_quota_notice(request, response) {
let body = "You're approaching quota.";
- response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
+ response.setHeader("X-Weave-Quota-Remaining", "1048576", false);
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_quota_error(request, response) {
let body = "14";
- response.setHeader("X-Weave-Quota-Remaining", '-1024', false);
+ response.setHeader("X-Weave-Quota-Remaining", "-1024", false);
response.setStatusLine(request.httpVersion, 400, "OK");
response.bodyOutputStream.write(body, body.length);
}
function server_headers(metadata, response) {
let ignore_headers = ["host", "user-agent", "accept", "accept-language",
"accept-encoding", "accept-charset", "keep-alive",
"connection", "pragma", "cache-control",
@@ -148,17 +148,17 @@ function server_headers(metadata, respon
response.bodyOutputStream.write(body, body.length);
}
var quotaValue;
Observers.add("weave:service:quota:remaining",
function(subject) { quotaValue = subject; });
function run_test() {
- logger = Log.repository.getLogger('Test');
+ logger = Log.repository.getLogger("Test");
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
Svc.Prefs.set("network.numRetries", 1); // speed up test
run_next_test();
}
// This apparently has to come first in order for our PAC URL to be hit.
// Don't put any other HTTP requests earlier in the file!
@@ -488,60 +488,60 @@ add_test(function test_weave_timestamp()
});
});
add_test(function test_get_no_headers() {
_("GET: no special request headers");
let res_headers = new AsyncResource(server.baseURI + "/headers");
res_headers.get(function(error, content) {
do_check_eq(error, null);
- do_check_eq(content, '{}');
+ do_check_eq(content, "{}");
run_next_test();
});
});
add_test(function test_put_default_content_type() {
_("PUT: Content-Type defaults to text/plain");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.put('data', function(error, content) {
+ res_headers.put("data", function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "text/plain"}));
run_next_test();
});
});
add_test(function test_post_default_content_type() {
_("POST: Content-Type defaults to text/plain");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.post('data', function(error, content) {
+ res_headers.post("data", function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "text/plain"}));
run_next_test();
});
});
add_test(function test_setHeader() {
_("setHeader(): setting simple header");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.setHeader('X-What-Is-Weave', 'awesome');
- do_check_eq(res_headers.headers['x-what-is-weave'], 'awesome');
+ res_headers.setHeader("X-What-Is-Weave", "awesome");
+ do_check_eq(res_headers.headers["x-what-is-weave"], "awesome");
res_headers.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"x-what-is-weave": "awesome"}));
run_next_test();
});
});
add_test(function test_setHeader_overwrite() {
_("setHeader(): setting multiple headers, overwriting existing header");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.setHeader('X-WHAT-is-Weave', 'more awesomer');
- res_headers.setHeader('X-Another-Header', 'hello world');
- do_check_eq(res_headers.headers['x-what-is-weave'], 'more awesomer');
- do_check_eq(res_headers.headers['x-another-header'], 'hello world');
+ res_headers.setHeader("X-WHAT-is-Weave", "more awesomer");
+ res_headers.setHeader("X-Another-Header", "hello world");
+ do_check_eq(res_headers.headers["x-what-is-weave"], "more awesomer");
+ do_check_eq(res_headers.headers["x-another-header"], "hello world");
res_headers.get(function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"x-another-header": "hello world",
"x-what-is-weave": "more awesomer"}));
run_next_test();
});
});
@@ -555,30 +555,30 @@ add_test(function test_headers_object()
do_check_eq(content, "{}");
run_next_test();
});
});
add_test(function test_put_override_content_type() {
_("PUT: override default Content-Type");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.setHeader('Content-Type', 'application/foobar');
- do_check_eq(res_headers.headers['content-type'], 'application/foobar');
- res_headers.put('data', function(error, content) {
+ res_headers.setHeader("Content-Type", "application/foobar");
+ do_check_eq(res_headers.headers["content-type"], "application/foobar");
+ res_headers.put("data", function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "application/foobar"}));
run_next_test();
});
});
add_test(function test_post_override_content_type() {
_("POST: override default Content-Type");
let res_headers = new AsyncResource(server.baseURI + "/headers");
- res_headers.setHeader('Content-Type', 'application/foobar');
- res_headers.post('data', function(error, content) {
+ res_headers.setHeader("Content-Type", "application/foobar");
+ res_headers.post("data", function(error, content) {
do_check_eq(error, null);
do_check_eq(content, JSON.stringify({"content-type": "application/foobar"}));
run_next_test();
});
});
add_test(function test_weave_backoff() {
_("X-Weave-Backoff header notifies observer");
--- a/services/sync/tests/unit/test_resource_ua.js
+++ b/services/sync/tests/unit/test_resource_ua.js
@@ -24,17 +24,17 @@ function uaHandler(f) {
ua = request.getHeader("User-Agent");
return f(request, response);
};
}
add_task(async function setup() {
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
- meta_global = new ServerWBO('global');
+ meta_global = new ServerWBO("global");
server = httpd_setup({
"/1.1/johndoe/info/collections": uaHandler(collectionsHelper.handler),
"/1.1/johndoe/storage/meta/global": uaHandler(meta_global.handler()),
});
await configureIdentity({ username: "johndoe" }, server);
_("Server URL: " + server.baseURI);
--- a/services/sync/tests/unit/test_service_detect_upgrade.js
+++ b/services/sync/tests/unit/test_service_detect_upgrade.js
@@ -12,17 +12,17 @@ Cu.import("resource://services-sync/util
Cu.import("resource://testing-common/services/sync/utils.js");
Service.engineManager.register(TabEngine);
add_test(function v4_upgrade() {
let passphrase = "abcdeabcdeabcdeabcdeabcdea";
let clients = new ServerCollection();
- let meta_global = new ServerWBO('global');
+ let meta_global = new ServerWBO("global");
// Tracking info/collections.
let collectionsHelper = track_collections_helper();
let upd = collectionsHelper.with_updated_collection;
let collections = collectionsHelper.collections;
let keysWBO = new ServerWBO("keys");
let server = httpd_setup({
@@ -194,17 +194,17 @@ add_test(function v5_upgrade() {
// Tracking info/collections.
let collectionsHelper = track_collections_helper();
let upd = collectionsHelper.with_updated_collection;
let collections = collectionsHelper.collections;
let keysWBO = new ServerWBO("keys");
let bulkWBO = new ServerWBO("bulk");
let clients = new ServerCollection();
- let meta_global = new ServerWBO('global');
+ let meta_global = new ServerWBO("global");
let server = httpd_setup({
// Special.
"/1.1/johndoe/storage/meta/global": upd("meta", meta_global.handler()),
"/1.1/johndoe/info/collections": collectionsHelper.handler,
"/1.1/johndoe/storage/crypto/keys": upd("crypto", keysWBO.handler()),
"/1.1/johndoe/storage/crypto/bulk": upd("crypto", bulkWBO.handler()),
--- a/services/sync/tests/unit/test_service_startup.js
+++ b/services/sync/tests/unit/test_service_startup.js
@@ -26,17 +26,17 @@ function run_test() {
Cu.import("resource://services-sync/service.js");
_("Service is enabled.");
do_check_eq(Service.enabled, true);
_("Engines are registered.");
let engines = Service.engineManager.getAll();
do_check_true(Utils.deepEquals(engines.map(engine => engine.name),
- ['tabs', 'bookmarks', 'forms', 'history']));
+ ["tabs", "bookmarks", "forms", "history"]));
_("Observers are notified of startup");
do_test_pending();
do_check_false(Service.status.ready);
do_check_false(xps.ready);
Observers.add("weave:service:ready", function(subject, data) {
do_check_true(Service.status.ready);
--- a/services/sync/tests/unit/test_service_sync_remoteSetup.js
+++ b/services/sync/tests/unit/test_service_sync_remoteSetup.js
@@ -11,17 +11,17 @@ Cu.import("resource://testing-common/ser
function run_test() {
validate_all_future_pings();
let logger = Log.repository.rootLogger;
Log.repository.rootLogger.addAppender(new Log.DumpAppender());
let guidSvc = new FakeGUIDService();
let clients = new ServerCollection();
- let meta_global = new ServerWBO('global');
+ let meta_global = new ServerWBO("global");
let collectionsHelper = track_collections_helper();
let upd = collectionsHelper.with_updated_collection;
let collections = collectionsHelper.collections;
function wasCalledHandler(wbo) {
let handler = wbo.handler();
return function() {
--- a/services/sync/tests/unit/test_status.js
+++ b/services/sync/tests/unit/test_status.js
@@ -7,17 +7,17 @@ function run_test() {
do_check_false(Status.enforceBackoff);
do_check_eq(Status.backoffInterval, 0);
do_check_eq(Status.minimumNextSync, 0);
do_check_eq(Status.service, STATUS_OK);
do_check_eq(Status.sync, SYNC_SUCCEEDED);
do_check_eq(Status.login, LOGIN_SUCCEEDED);
for (let name in Status.engines) {
- do_throw('Status.engines should be empty.');
+ do_throw("Status.engines should be empty.");
}
do_check_eq(Status.partial, false);
// Check login status
for (let code of [LOGIN_FAILED_NO_USERNAME,
LOGIN_FAILED_NO_PASSWORD,
LOGIN_FAILED_NO_PASSPHRASE]) {
@@ -69,17 +69,17 @@ function run_test() {
// Check resetSync
Status.sync = SYNC_FAILED;
Status.resetSync();
do_check_eq(Status.service, STATUS_OK);
do_check_eq(Status.sync, SYNC_SUCCEEDED);
for (name in Status.engines) {
- do_throw('Status.engines should be empty.');
+ do_throw("Status.engines should be empty.");
}
// Check resetBackoff
Status.enforceBackoff = true;
Status.backOffInterval = 4815162342;
Status.backOffInterval = 42;
Status.resetBackoff();
--- a/services/sync/tests/unit/test_syncengine.js
+++ b/services/sync/tests/unit/test_syncengine.js
@@ -2,17 +2,17 @@
http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js");
function makeSteamEngine() {
- return new SyncEngine('Steam', Service);
+ return new SyncEngine("Steam", Service);
}
var server = httpd_setup({});
add_task(async function test_url_attributes() {
_("SyncEngine url attributes");
let syncTesting = await SyncTestingInfrastructure(server);
--- a/services/sync/tests/unit/test_syncengine_sync.js
+++ b/services/sync/tests/unit/test_syncengine_sync.js
@@ -81,21 +81,21 @@ function run_test() {
* different scenarios below.
*/
add_task(async function test_syncStartup_emptyOrOutdatedGlobalsResetsSync() {
_("SyncEngine._syncStartup resets sync and wipes server data if there's no or an outdated global record");
// Some server side data that's going to be wiped
let collection = new ServerCollection();
- collection.insert('flying',
- encryptPayload({id: 'flying',
+ collection.insert("flying",
+ encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
- collection.insert('scotsman',
- encryptPayload({id: 'scotsman',
+ collection.insert("scotsman",
+ encryptPayload({id: "scotsman",
denomination: "Flying Scotsman"}));
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
@@ -131,17 +131,17 @@ add_task(async function test_syncStartup
} finally {
await cleanAndGo(engine, server);
}
});
add_task(async function test_syncStartup_serverHasNewerVersion() {
_("SyncEngine._syncStartup ");
- let global = new ServerWBO('global', {engines: {rotary: {version: 23456}}});
+ let global = new ServerWBO("global", {engines: {rotary: {version: 23456}}});
let server = httpd_setup({
"/1.1/foo/storage/meta/global": global.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
let engine = makeRotaryEngine();
@@ -167,33 +167,33 @@ add_task(async function test_syncStartup
_("SyncEngine._syncStartup resets sync if syncIDs don't match");
let server = sync_httpd_setup({});
let syncTesting = await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
// global record with a different syncID than our engine has
let engine = makeRotaryEngine();
- let global = new ServerWBO('global',
+ let global = new ServerWBO("global",
{engines: {rotary: {version: engine.version,
- syncID: 'foobar'}}});
+ syncID: "foobar"}}});
server.registerPathHandler("/1.1/foo/storage/meta/global", global.handler());
try {
// Confirm initial environment
- do_check_eq(engine.syncID, 'fake-guid-00');
+ do_check_eq(engine.syncID, "fake-guid-00");
do_check_eq(engine._tracker.changedIDs["rekolok"], undefined);
engine.lastSync = Date.now() / 1000;
engine.lastSyncLocal = Date.now();
engine._syncStartup();
// The engine has assumed the server's syncID
- do_check_eq(engine.syncID, 'foobar');
+ do_check_eq(engine.syncID, "foobar");
// Sync was reset
do_check_eq(engine.lastSync, 0);
} finally {
await cleanAndGo(engine, server);
}
});
@@ -223,27 +223,27 @@ add_task(async function test_processInco
});
add_task(async function test_processIncoming_createFromServer() {
_("SyncEngine._processIncoming creates new records from server data");
// Some server records that will be downloaded
let collection = new ServerCollection();
- collection.insert('flying',
- encryptPayload({id: 'flying',
+ collection.insert("flying",
+ encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
- collection.insert('scotsman',
- encryptPayload({id: 'scotsman',
+ collection.insert("scotsman",
+ encryptPayload({id: "scotsman",
denomination: "Flying Scotsman"}));
// Two pathological cases involving relative URIs gone wrong.
- let pathologicalPayload = encryptPayload({id: '../pathological',
+ let pathologicalPayload = encryptPayload({id: "../pathological",
denomination: "Pathological Case"});
- collection.insert('../pathological', pathologicalPayload);
+ collection.insert("../pathological", pathologicalPayload);
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler(),
"/1.1/foo/storage/rotary/flying": collection.wbo("flying").handler(),
"/1.1/foo/storage/rotary/scotsman": collection.wbo("scotsman").handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -259,76 +259,76 @@ add_task(async function test_processInco
try {
// Confirm initial environment
do_check_eq(engine.lastSync, 0);
do_check_eq(engine.lastModified, null);
do_check_eq(engine._store.items.flying, undefined);
do_check_eq(engine._store.items.scotsman, undefined);
- do_check_eq(engine._store.items['../pathological'], undefined);
+ do_check_eq(engine._store.items["../pathological"], undefined);
engine._syncStartup();
engine._processIncoming();
// Timestamps of last sync and last server modification are set.
do_check_true(engine.lastSync > 0);
do_check_true(engine.lastModified > 0);
// Local records have been created from the server data.
do_check_eq(engine._store.items.flying, "LNER Class A3 4472");
do_check_eq(engine._store.items.scotsman, "Flying Scotsman");
- do_check_eq(engine._store.items['../pathological'], "Pathological Case");
+ do_check_eq(engine._store.items["../pathological"], "Pathological Case");
} finally {
await cleanAndGo(engine, server);
}
});
add_task(async function test_processIncoming_reconcile() {
_("SyncEngine._processIncoming updates local records");
let collection = new ServerCollection();
// This server record is newer than the corresponding client one,
// so it'll update its data.
- collection.insert('newrecord',
- encryptPayload({id: 'newrecord',
+ collection.insert("newrecord",
+ encryptPayload({id: "newrecord",
denomination: "New stuff..."}));
// This server record is newer than the corresponding client one,
// so it'll update its data.
- collection.insert('newerserver',
- encryptPayload({id: 'newerserver',
+ collection.insert("newerserver",
+ encryptPayload({id: "newerserver",
denomination: "New data!"}));
// This server record is 2 mins older than the client counterpart
// but identical to it, so we're expecting the client record's
// changedID to be reset.
- collection.insert('olderidentical',
- encryptPayload({id: 'olderidentical',
+ collection.insert("olderidentical",
+ encryptPayload({id: "olderidentical",
denomination: "Older but identical"}));
collection._wbos.olderidentical.modified -= 120;
// This item simply has different data than the corresponding client
// record (which is unmodified), so it will update the client as well
- collection.insert('updateclient',
- encryptPayload({id: 'updateclient',
+ collection.insert("updateclient",
+ encryptPayload({id: "updateclient",
denomination: "Get this!"}));
// This is a dupe of 'original'.
- collection.insert('duplication',
- encryptPayload({id: 'duplication',
+ collection.insert("duplication",
+ encryptPayload({id: "duplication",
denomination: "Original Entry"}));
// This record is marked as deleted, so we're expecting the client
// record to be removed.
- collection.insert('nukeme',
- encryptPayload({id: 'nukeme',
+ collection.insert("nukeme",
+ encryptPayload({id: "nukeme",
denomination: "Nuke me!",
deleted: true}));
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
@@ -337,34 +337,34 @@ add_task(async function test_processInco
let engine = makeRotaryEngine();
engine._store.items = {newerserver: "New data, but not as new as server!",
olderidentical: "Older but identical",
updateclient: "Got data?",
original: "Original Entry",
long_original: "Long Original Entry",
nukeme: "Nuke me!"};
// Make this record 1 min old, thus older than the one on the server
- engine._tracker.addChangedID('newerserver', Date.now() / 1000 - 60);
+ engine._tracker.addChangedID("newerserver", Date.now() / 1000 - 60);
// This record has been changed 2 mins later than the one on the server
- engine._tracker.addChangedID('olderidentical', Date.now() / 1000);
+ engine._tracker.addChangedID("olderidentical", Date.now() / 1000);
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
syncID: engine.syncID}};
try {
// Confirm initial environment
do_check_eq(engine._store.items.newrecord, undefined);
do_check_eq(engine._store.items.newerserver, "New data, but not as new as server!");
do_check_eq(engine._store.items.olderidentical, "Older but identical");
do_check_eq(engine._store.items.updateclient, "Got data?");
do_check_eq(engine._store.items.nukeme, "Nuke me!");
- do_check_true(engine._tracker.changedIDs['olderidentical'] > 0);
+ do_check_true(engine._tracker.changedIDs["olderidentical"] > 0);
engine._syncStartup();
engine._processIncoming();
// Timestamps of last sync and last server modification are set.
do_check_true(engine.lastSync > 0);
do_check_true(engine.lastModified > 0);
@@ -372,17 +372,17 @@ add_task(async function test_processInco
do_check_eq(engine._store.items.newrecord, "New stuff...");
// The 'newerserver' record is updated since the server data is newer.
do_check_eq(engine._store.items.newerserver, "New data!");
// The data for 'olderidentical' is identical on the server, so
// it's no longer marked as changed anymore.
do_check_eq(engine._store.items.olderidentical, "Older but identical");
- do_check_eq(engine._tracker.changedIDs['olderidentical'], undefined);
+ do_check_eq(engine._tracker.changedIDs["olderidentical"], undefined);
// Updated with server data.
do_check_eq(engine._store.items.updateclient, "Get this!");
// The incoming ID is preferred.
do_check_eq(engine._store.items.original, undefined);
do_check_eq(engine._store.items.duplication, "Original Entry");
do_check_neq(engine._delete.ids.indexOf("original"), -1);
@@ -617,17 +617,17 @@ add_task(async function test_processInco
collection.get = function(options) {
this.get_log.push(options);
return this._get(options);
};
// Let's create some 234 server side records. They're all at least
// 10 minutes old.
for (let i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + i});
let wbo = new ServerWBO(id, payload);
wbo.modified = Date.now() / 1000 - 60 * (i + 10);
collection.insertWBO(wbo);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
@@ -642,20 +642,20 @@ add_task(async function test_processInco
syncID: engine.syncID}};
try {
_("On a mobile client, we get new records from the server in batches of 50.");
engine._syncStartup();
engine._processIncoming();
do_check_attribute_count(engine._store.items, 234);
- do_check_true('record-no-0' in engine._store.items);
- do_check_true('record-no-49' in engine._store.items);
- do_check_true('record-no-50' in engine._store.items);
- do_check_true('record-no-233' in engine._store.items);
+ do_check_true("record-no-0" in engine._store.items);
+ do_check_true("record-no-49" in engine._store.items);
+ do_check_true("record-no-50" in engine._store.items);
+ do_check_true("record-no-233" in engine._store.items);
// Verify that the right number of GET requests with the right
// kind of parameters were made.
do_check_eq(collection.get_log.length,
Math.ceil(234 / MOBILE_BATCH_SIZE) + 1);
do_check_eq(collection.get_log[0].full, 1);
do_check_eq(collection.get_log[0].limit, MOBILE_BATCH_SIZE);
do_check_eq(collection.get_log[1].full, undefined);
@@ -689,17 +689,17 @@ add_task(async function test_processInco
if (this._get_calls > 3) {
throw "Abort on fourth call!";
}
return this._get.apply(this, arguments);
};
// Let's create three batches worth of server side records.
for (var i = 0; i < MOBILE_BATCH_SIZE * 3; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + id});
let wbo = new ServerWBO(id, payload);
wbo.modified = Date.now() / 1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
collection.insertWBO(wbo);
}
let engine = makeRotaryEngine();
engine.enabled = true;
@@ -745,27 +745,27 @@ add_task(async function test_processInco
add_task(async function test_processIncoming_resume_toFetch() {
_("toFetch and previousFailed items left over from previous syncs are fetched on the next sync, along with new items.");
Service.identity.username = "foo";
const LASTSYNC = Date.now() / 1000;
// Server records that will be downloaded
let collection = new ServerCollection();
- collection.insert('flying',
- encryptPayload({id: 'flying',
+ collection.insert("flying",
+ encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
- collection.insert('scotsman',
- encryptPayload({id: 'scotsman',
+ collection.insert("scotsman",
+ encryptPayload({id: "scotsman",
denomination: "Flying Scotsman"}));
- collection.insert('rekolok',
- encryptPayload({id: 'rekolok',
+ collection.insert("rekolok",
+ encryptPayload({id: "rekolok",
denomination: "Rekonstruktionslokomotive"}));
for (let i = 0; i < 3; i++) {
- let id = 'failed' + i;
+ let id = "failed" + i;
let payload = encryptPayload({id, denomination: "Record No. " + i});
let wbo = new ServerWBO(id, payload);
wbo.modified = LASTSYNC - 10;
collection.insertWBO(wbo);
}
collection.wbo("flying").modified =
collection.wbo("scotsman").modified = LASTSYNC - 10;
@@ -825,17 +825,17 @@ add_task(async function test_processInco
let failed2 = records.pop();
this._applyIncomingBatch(records);
return [failed1.id, failed2.id];
};
// Let's create less than a batch worth of server side records.
let collection = new ServerCollection();
for (let i = 0; i < APPLY_BATCH_SIZE - 1; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
@@ -881,17 +881,17 @@ add_task(async function test_processInco
batchCalls += 1;
do_check_eq(records.length, APPLY_BATCH_SIZE);
this._applyIncomingBatch.apply(this, arguments);
};
// Let's create three batches worth of server side records.
let collection = new ServerCollection();
for (let i = 0; i < APPLY_BATCH_SIZE * 3; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
@@ -933,17 +933,17 @@ add_task(async function test_processInco
engine._store.applyIncomingBatch = function(records) {
engine._store._applyIncomingBatch(records.slice(1));
return [records[0].id];
};
// Create a batch of server side records.
let collection = new ServerCollection();
for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
@@ -1023,17 +1023,17 @@ add_task(async function test_processInco
engine._store.applyIncomingBatch = function(records) {
engine._store._applyIncomingBatch(records.slice(2));
return [records[0].id, records[1].id];
};
// Create a batch of server side records.
let collection = new ServerCollection();
for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + i});
collection.insert(id, payload);
}
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
@@ -1079,35 +1079,35 @@ add_task(async function test_processInco
do_check_attribute_count(engine._store.items, 10);
do_check_eq(engine.previousFailed.length, 4);
do_check_eq(engine.previousFailed[0], "record-no-0");
do_check_eq(engine.previousFailed[1], "record-no-1");
do_check_eq(engine.previousFailed[2], "record-no-8");
do_check_eq(engine.previousFailed[3], "record-no-9");
// Refetched items that didn't fail the second time are in engine._store.items.
- do_check_eq(engine._store.items['record-no-4'], "Record No. 4");
- do_check_eq(engine._store.items['record-no-5'], "Record No. 5");
- do_check_eq(engine._store.items['record-no-12'], "Record No. 12");
- do_check_eq(engine._store.items['record-no-13'], "Record No. 13");
+ do_check_eq(engine._store.items["record-no-4"], "Record No. 4");
+ do_check_eq(engine._store.items["record-no-5"], "Record No. 5");
+ do_check_eq(engine._store.items["record-no-12"], "Record No. 12");
+ do_check_eq(engine._store.items["record-no-13"], "Record No. 13");
} finally {
await cleanAndGo(engine, server);
}
});
add_task(async function test_processIncoming_failed_records() {
_("Ensure that failed records from _reconcile and applyIncomingBatch are refetched.");
Service.identity.username = "foo";
// Let's create three and a bit batches worth of server side records.
let collection = new ServerCollection();
const NUMBER_OF_RECORDS = MOBILE_BATCH_SIZE * 3 + 5;
for (let i = 0; i < NUMBER_OF_RECORDS; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + id});
let wbo = new ServerWBO(id, payload);
wbo.modified = Date.now() / 1000 + 60 * (i - MOBILE_BATCH_SIZE * 3);
collection.insertWBO(wbo);
}
// Engine that batches but likes to throw on a couple of records,
// two in each batch: the even ones fail in reconcile, the odd ones
@@ -1232,22 +1232,22 @@ add_task(async function test_processInco
_("Ensure that records failing to decrypt are either replaced or refetched.");
Service.identity.username = "foo";
// Some good and some bogus records. One doesn't contain valid JSON,
// the other will throw during decrypt.
let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO(
- 'flying', encryptPayload({id: 'flying',
+ "flying", encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
collection._wbos.nojson = new ServerWBO("nojson", "This is invalid JSON");
collection._wbos.nojson2 = new ServerWBO("nojson2", "This is invalid JSON");
collection._wbos.scotsman = new ServerWBO(
- 'scotsman', encryptPayload({id: 'scotsman',
+ "scotsman", encryptPayload({id: "scotsman",
denomination: "Flying Scotsman"}));
collection._wbos.nodecrypt = new ServerWBO("nodecrypt", "Decrypt this!");
collection._wbos.nodecrypt2 = new ServerWBO("nodecrypt2", "Decrypt this!");
// Patch the fake crypto service to throw on the record above.
Svc.Crypto._decrypt = Svc.Crypto.decrypt;
Svc.Crypto.decrypt = function(ciphertext) {
if (ciphertext == "Decrypt this!") {
@@ -1309,34 +1309,34 @@ add_task(async function test_processInco
});
add_task(async function test_uploadOutgoing_toEmptyServer() {
_("SyncEngine._uploadOutgoing uploads new records to server");
Service.identity.username = "foo";
let collection = new ServerCollection();
- collection._wbos.flying = new ServerWBO('flying');
- collection._wbos.scotsman = new ServerWBO('scotsman');
+ collection._wbos.flying = new ServerWBO("flying");
+ collection._wbos.scotsman = new ServerWBO("scotsman");
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler(),
"/1.1/foo/storage/rotary/flying": collection.wbo("flying").handler(),
"/1.1/foo/storage/rotary/scotsman": collection.wbo("scotsman").handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
generateNewKeys(Service.collectionKeys);
let engine = makeRotaryEngine();
engine.lastSync = 123; // needs to be non-zero so that tracker is queried
engine._store.items = {flying: "LNER Class A3 4472",
scotsman: "Flying Scotsman"};
// Mark one of these records as changed
- engine._tracker.addChangedID('scotsman', 0);
+ engine._tracker.addChangedID("scotsman", 0);
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
syncID: engine.syncID}};
try {
@@ -1366,18 +1366,18 @@ add_task(async function test_uploadOutgo
await cleanAndGo(engine, server);
}
});
add_task(async function test_uploadOutgoing_huge() {
Service.identity.username = "foo";
let collection = new ServerCollection();
- collection._wbos.flying = new ServerWBO('flying');
- collection._wbos.scotsman = new ServerWBO('scotsman');
+ collection._wbos.flying = new ServerWBO("flying");
+ collection._wbos.scotsman = new ServerWBO("scotsman");
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler(),
"/1.1/foo/storage/rotary/flying": collection.wbo("flying").handler(),
});
let syncTesting = await SyncTestingInfrastructure(server);
generateNewKeys(Service.collectionKeys);
@@ -1417,65 +1417,65 @@ add_task(async function test_uploadOutgo
add_task(async function test_uploadOutgoing_failed() {
_("SyncEngine._uploadOutgoing doesn't clear the tracker of objects that failed to upload.");
Service.identity.username = "foo";
let collection = new ServerCollection();
// We only define the "flying" WBO on the server, not the "scotsman"
// and "peppercorn" ones.
- collection._wbos.flying = new ServerWBO('flying');
+ collection._wbos.flying = new ServerWBO("flying");
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
let engine = makeRotaryEngine();
engine.lastSync = 123; // needs to be non-zero so that tracker is queried
engine._store.items = {flying: "LNER Class A3 4472",
scotsman: "Flying Scotsman",
peppercorn: "Peppercorn Class"};
// Mark these records as changed
const FLYING_CHANGED = 12345;
const SCOTSMAN_CHANGED = 23456;
const PEPPERCORN_CHANGED = 34567;
- engine._tracker.addChangedID('flying', FLYING_CHANGED);
- engine._tracker.addChangedID('scotsman', SCOTSMAN_CHANGED);
- engine._tracker.addChangedID('peppercorn', PEPPERCORN_CHANGED);
+ engine._tracker.addChangedID("flying", FLYING_CHANGED);
+ engine._tracker.addChangedID("scotsman", SCOTSMAN_CHANGED);
+ engine._tracker.addChangedID("peppercorn", PEPPERCORN_CHANGED);
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
syncID: engine.syncID}};
try {
// Confirm initial environment
do_check_eq(engine.lastSyncLocal, 0);
do_check_eq(collection.payload("flying"), undefined);
- do_check_eq(engine._tracker.changedIDs['flying'], FLYING_CHANGED);
- do_check_eq(engine._tracker.changedIDs['scotsman'], SCOTSMAN_CHANGED);
- do_check_eq(engine._tracker.changedIDs['peppercorn'], PEPPERCORN_CHANGED);
+ do_check_eq(engine._tracker.changedIDs["flying"], FLYING_CHANGED);
+ do_check_eq(engine._tracker.changedIDs["scotsman"], SCOTSMAN_CHANGED);
+ do_check_eq(engine._tracker.changedIDs["peppercorn"], PEPPERCORN_CHANGED);
engine.enabled = true;
await sync_engine_and_validate_telem(engine, true);
// Local timestamp has been set.
do_check_true(engine.lastSyncLocal > 0);
// Ensure the 'flying' record has been uploaded and is no longer marked.
do_check_true(!!collection.payload("flying"));
- do_check_eq(engine._tracker.changedIDs['flying'], undefined);
+ do_check_eq(engine._tracker.changedIDs["flying"], undefined);
// The 'scotsman' and 'peppercorn' records couldn't be uploaded so
// they weren't cleared from the tracker.
- do_check_eq(engine._tracker.changedIDs['scotsman'], SCOTSMAN_CHANGED);
- do_check_eq(engine._tracker.changedIDs['peppercorn'], PEPPERCORN_CHANGED);
+ do_check_eq(engine._tracker.changedIDs["scotsman"], SCOTSMAN_CHANGED);
+ do_check_eq(engine._tracker.changedIDs["peppercorn"], PEPPERCORN_CHANGED);
} finally {
await promiseClean(engine, server);
}
});
/* A couple of "functional" tests to ensure we split records into appropriate
POST requests. More comprehensive unit-tests for this "batching" are in
@@ -1503,17 +1503,17 @@ add_task(async function test_uploadOutgo
noOfUploads++;
return orig.call(this, data, request);
};
}(collection.post));
// Create a bunch of records (and server side handlers)
let engine = makeRotaryEngine();
for (var i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
engine._store.items[id] = "Record No. " + i;
engine._tracker.addChangedID(id, 0);
collection.insert(id);
}
let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL));
meta_global.payload.engines = {rotary: {version: engine.version,
@@ -1530,17 +1530,17 @@ add_task(async function test_uploadOutgo
// Confirm initial environment.
do_check_eq(noOfUploads, 0);
engine._syncStartup();
engine._uploadOutgoing();
// Ensure all records have been uploaded.
for (i = 0; i < 234; i++) {
- do_check_true(!!collection.payload('record-no-' + i));
+ do_check_true(!!collection.payload("record-no-" + i));
}
// Ensure that the uploads were performed in batches of MAX_UPLOAD_RECORDS.
do_check_eq(noOfUploads, Math.ceil(234 / MAX_UPLOAD_RECORDS));
} finally {
await cleanAndGo(engine, server);
}
@@ -1603,33 +1603,33 @@ add_task(async function test_syncFinish_
add_task(async function test_syncFinish_deleteByIds() {
_("SyncEngine._syncFinish deletes server records slated for deletion (list of record IDs).");
Service.identity.username = "foo";
let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO(
- 'flying', encryptPayload({id: 'flying',
+ "flying", encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
collection._wbos.scotsman = new ServerWBO(
- 'scotsman', encryptPayload({id: 'scotsman',
+ "scotsman", encryptPayload({id: "scotsman",
denomination: "Flying Scotsman"}));
collection._wbos.rekolok = new ServerWBO(
- 'rekolok', encryptPayload({id: 'rekolok',
+ "rekolok", encryptPayload({id: "rekolok",
denomination: "Rekonstruktionslokomotive"}));
let server = httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
let engine = makeRotaryEngine();
try {
- engine._delete = {ids: ['flying', 'rekolok']};
+ engine._delete = {ids: ["flying", "rekolok"]};
engine._syncFinish();
// The 'flying' and 'rekolok' records were deleted while the
// 'scotsman' one wasn't.
do_check_eq(collection.payload("flying"), undefined);
do_check_true(!!collection.payload("scotsman"));
do_check_eq(collection.payload("rekolok"), undefined);
@@ -1655,17 +1655,17 @@ add_task(async function test_syncFinish_
noOfUploads++;
return orig.apply(this, arguments);
};
}(collection.delete));
// Create a bunch of records on the server
let now = Date.now();
for (var i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + i});
let wbo = new ServerWBO(id, payload);
wbo.modified = now / 1000 - 60 * (i + 110);
collection.insertWBO(wbo);
}
let server = httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
@@ -1680,25 +1680,25 @@ add_task(async function test_syncFinish_
do_check_eq(noOfUploads, 0);
// Declare what we want to have deleted: all records no. 100 and
// up and all records that are less than 200 mins old (which are
// records 0 thru 90).
engine._delete = {ids: [],
newer: now / 1000 - 60 * 200.5};
for (i = 100; i < 234; i++) {
- engine._delete.ids.push('record-no-' + i);
+ engine._delete.ids.push("record-no-" + i);
}
engine._syncFinish();
// Ensure that the appropriate server data has been wiped while
// preserving records 90 thru 200.
for (i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
if (i <= 90 || i >= 100) {
do_check_eq(collection.payload(id), undefined);
} else {
do_check_true(!!collection.payload(id));
}
}
// The deletion was done in batches
@@ -1737,17 +1737,17 @@ add_task(async function test_sync_partia
throw "FAIL!";
noOfUploads++;
return orig.apply(this, arguments);
};
}(collection.post));
// Create a bunch of records (and server side handlers)
for (let i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
engine._store.items[id] = "Record No. " + i;
engine._tracker.addChangedID(id, i);
// Let two items in the first upload batch fail.
if ((i != 23) && (i != 42)) {
collection.insert(id);
}
}
@@ -1767,17 +1767,17 @@ add_task(async function test_sync_partia
}
ok(!!error);
// The timestamp has been updated.
do_check_true(engine.lastSyncLocal > 456);
for (let i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
// Ensure failed records are back in the tracker:
// * records no. 23 and 42 were rejected by the server,
// * records no. 200 and higher couldn't be uploaded because we failed
// hard on the 3rd upload.
if ((i == 23) || (i == 42) || (i >= 200))
do_check_eq(engine._tracker.changedIDs[id], i);
else
do_check_false(id in engine._tracker.changedIDs);
@@ -1792,17 +1792,17 @@ add_task(async function test_canDecrypt_
_("SyncEngine.canDecrypt returns false if the engine fails to decrypt items on the server, e.g. due to a missing crypto key collection.");
Service.identity.username = "foo";
// Wipe collection keys so we can test the desired scenario.
Service.collectionKeys.clear();
let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO(
- 'flying', encryptPayload({id: 'flying',
+ "flying", encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
let engine = makeRotaryEngine();
@@ -1818,17 +1818,17 @@ add_task(async function test_canDecrypt_
add_task(async function test_canDecrypt_true() {
_("SyncEngine.canDecrypt returns true if the engine can decrypt the items on the server.");
Service.identity.username = "foo";
generateNewKeys(Service.collectionKeys);
let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO(
- 'flying', encryptPayload({id: 'flying',
+ "flying", encryptPayload({id: "flying",
denomination: "LNER Class A3 4472"}));
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
let syncTesting = await SyncTestingInfrastructure(server);
let engine = makeRotaryEngine();
@@ -1847,17 +1847,17 @@ add_task(async function test_syncapplied
const NUMBER_OF_RECORDS = 10;
let engine = makeRotaryEngine();
// Create a batch of server side records.
let collection = new ServerCollection();
for (var i = 0; i < NUMBER_OF_RECORDS; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
let payload = encryptPayload({id, denomination: "Record No. " + id});
collection.insert(id, payload);
}
let server = httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
--- a/services/sync/tests/unit/test_syncscheduler.js
+++ b/services/sync/tests/unit/test_syncscheduler.js
@@ -102,36 +102,36 @@ add_test(function test_prefAttributes()
const TIMESTAMP1 = 1275493471649;
_("The 'nextSync' attribute stores a millisecond timestamp rounded down to the nearest second.");
do_check_eq(scheduler.nextSync, 0);
scheduler.nextSync = TIMESTAMP1;
do_check_eq(scheduler.nextSync, Math.floor(TIMESTAMP1 / 1000) * 1000);
_("'syncInterval' defaults to singleDeviceInterval.");
- do_check_eq(Svc.Prefs.get('syncInterval'), undefined);
+ do_check_eq(Svc.Prefs.get("syncInterval"), undefined);
do_check_eq(scheduler.syncInterval, scheduler.singleDeviceInterval);
_("'syncInterval' corresponds to a preference setting.");
scheduler.syncInterval = INTERVAL;
do_check_eq(scheduler.syncInterval, INTERVAL);
- do_check_eq(Svc.Prefs.get('syncInterval'), INTERVAL);
+ do_check_eq(Svc.Prefs.get("syncInterval"), INTERVAL);
_("'syncThreshold' corresponds to preference, defaults to SINGLE_USER_THRESHOLD");
- do_check_eq(Svc.Prefs.get('syncThreshold'), undefined);
+ do_check_eq(Svc.Prefs.get("syncThreshold"), undefined);
do_check_eq(scheduler.syncThreshold, SINGLE_USER_THRESHOLD);
scheduler.syncThreshold = THRESHOLD;
do_check_eq(scheduler.syncThreshold, THRESHOLD);
_("'globalScore' corresponds to preference, defaults to zero.");
- do_check_eq(Svc.Prefs.get('globalScore'), 0);
+ do_check_eq(Svc.Prefs.get("globalScore"), 0);
do_check_eq(scheduler.globalScore, 0);
scheduler.globalScore = SCORE;
do_check_eq(scheduler.globalScore, SCORE);
- do_check_eq(Svc.Prefs.get('globalScore'), SCORE);
+ do_check_eq(Svc.Prefs.get("globalScore"), SCORE);
_("Intervals correspond to default preferences.");
do_check_eq(scheduler.singleDeviceInterval,
Svc.Prefs.get("scheduler.sync11.singleDeviceInterval") * 1000);
do_check_eq(scheduler.idleInterval,
Svc.Prefs.get("scheduler.idleInterval") * 1000);
do_check_eq(scheduler.activeInterval,
Svc.Prefs.get("scheduler.activeInterval") * 1000);
--- a/services/sync/tests/unit/test_syncstoragerequest.js
+++ b/services/sync/tests/unit/test_syncstoragerequest.js
@@ -99,17 +99,17 @@ add_test(function test_weave_timestamp()
});
});
/**
* The X-Weave-Backoff header notifies an observer.
*/
add_test(function test_weave_backoff() {
function handler(request, response) {
- response.setHeader("X-Weave-Backoff", '600', false);
+ response.setHeader("X-Weave-Backoff", "600", false);
response.setStatusLine(request.httpVersion, 200, "OK");
}
let server = httpd_setup({"/resource": handler});
let backoffInterval;
Svc.Obs.add("weave:service:backoff:interval", function onBackoff(subject) {
Svc.Obs.remove("weave:service:backoff:interval", onBackoff);
backoffInterval = subject;
@@ -124,17 +124,17 @@ add_test(function test_weave_backoff() {
});
});
/**
* X-Weave-Quota-Remaining header notifies observer on successful requests.
*/
add_test(function test_weave_quota_notice() {
function handler(request, response) {
- response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
+ response.setHeader("X-Weave-Quota-Remaining", "1048576", false);
response.setStatusLine(request.httpVersion, 200, "OK");
}
let server = httpd_setup({"/resource": handler});
let quotaValue;
Svc.Obs.add("weave:service:quota:remaining", function onQuota(subject) {
Svc.Obs.remove("weave:service:quota:remaining", onQuota);
quotaValue = subject;
@@ -149,17 +149,17 @@ add_test(function test_weave_quota_notic
});
});
/**
* X-Weave-Quota-Remaining header doesn't notify observer on failed requests.
*/
add_test(function test_weave_quota_error() {
function handler(request, response) {
- response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
+ response.setHeader("X-Weave-Quota-Remaining", "1048576", false);
response.setStatusLine(request.httpVersion, 400, "Bad Request");
}
let server = httpd_setup({"/resource": handler});
let quotaValue;
function onQuota(subject) {
quotaValue = subject;
}
@@ -173,18 +173,18 @@ add_test(function test_weave_quota_error
Svc.Obs.remove("weave:service:quota:remaining", onQuota);
server.stop(run_next_test);
});
});
add_test(function test_abort() {
function handler(request, response) {
response.setHeader("X-Weave-Timestamp", "" + TIMESTAMP, false);
- response.setHeader("X-Weave-Quota-Remaining", '1048576', false);
- response.setHeader("X-Weave-Backoff", '600', false);
+ response.setHeader("X-Weave-Quota-Remaining", "1048576", false);
+ response.setHeader("X-Weave-Backoff", "600", false);
response.setStatusLine(request.httpVersion, 200, "OK");
}
let server = httpd_setup({"/resource": handler});
let request = new SyncStorageRequest(server.baseURI + "/resource");
// Aborting a request that hasn't been sent yet is pointless and will throw.
do_check_throws(function() {
--- a/services/sync/tests/unit/test_telemetry.js
+++ b/services/sync/tests/unit/test_telemetry.js
@@ -194,17 +194,17 @@ add_task(async function test_uploading()
store.wipe();
await cleanAndGo(engine, server);
}
});
add_task(async function test_upload_failed() {
Service.identity.username = "foo";
let collection = new ServerCollection();
- collection._wbos.flying = new ServerWBO('flying');
+ collection._wbos.flying = new ServerWBO("flying");
let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler()
});
await SyncTestingInfrastructure(server);
let engine = new RotaryEngine(Service);
@@ -262,17 +262,17 @@ add_task(async function test_sync_partia
let engine = new RotaryEngine(Service);
engine.lastSync = 123;
engine.lastSyncLocal = 456;
// Create a bunch of records (and server side handlers)
for (let i = 0; i < 234; i++) {
- let id = 'record-no-' + i;
+ let id = "record-no-" + i;
engine._store.items[id] = "Record No. " + i;
engine._tracker.addChangedID(id, i);
// Let two items in the first upload batch fail.
if (i != 23 && i != 42) {
collection.insert(id);
}
}
--- a/services/sync/tests/unit/test_utils_passphrase.js
+++ b/services/sync/tests/unit/test_utils_passphrase.js
@@ -2,27 +2,27 @@ Cu.import("resource://services-sync/util
function run_test() {
_("Generated passphrase has length 26.");
let pp = Utils.generatePassphrase();
do_check_eq(pp.length, 26);
const key = "abcdefghijkmnpqrstuvwxyz23456789";
_("Passphrase only contains [" + key + "].");
- do_check_true(pp.split('').every(chr => key.indexOf(chr) != -1));
+ do_check_true(pp.split("").every(chr => key.indexOf(chr) != -1));
_("Hyphenated passphrase has 5 hyphens.");
let hyphenated = Utils.hyphenatePassphrase(pp);
_("H: " + hyphenated);
do_check_eq(hyphenated.length, 31);
- do_check_eq(hyphenated[1], '-');
- do_check_eq(hyphenated[7], '-');
- do_check_eq(hyphenated[13], '-');
- do_check_eq(hyphenated[19], '-');
- do_check_eq(hyphenated[25], '-');
+ do_check_eq(hyphenated[1], "-");
+ do_check_eq(hyphenated[7], "-");
+ do_check_eq(hyphenated[13], "-");
+ do_check_eq(hyphenated[19], "-");
+ do_check_eq(hyphenated[25], "-");
do_check_eq(pp,
hyphenated.slice(0, 1) + hyphenated.slice(2, 7)
+ hyphenated.slice(8, 13) + hyphenated.slice(14, 19)
+ hyphenated.slice(20, 25) + hyphenated.slice(26, 31));
_("Arbitrary hyphenation.");
// We don't allow invalid characters for our base32 character set.
do_check_eq(Utils.hyphenatePassphrase("1234567"), "2-34567"); // Not partial, so no trailing dash.
--- a/services/sync/tps/extensions/tps/components/tps-cmdline.js
+++ b/services/sync/tps/extensions/tps/components/tps-cmdline.js
@@ -2,17 +2,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const CC = Components.classes;
const CI = Components.interfaces;
const TPS_ID = "tps@mozilla.org";
const TPS_CMDLINE_CONTRACTID = "@mozilla.org/commandlinehandler/general-startup;1?type=tps";
-const TPS_CMDLINE_CLSID = Components.ID('{4e5bd3f0-41d3-11df-9879-0800200c9a66}');
+const TPS_CMDLINE_CLSID = Components.ID("{4e5bd3f0-41d3-11df-9879-0800200c9a66}");
const CATMAN_CONTRACTID = "@mozilla.org/categorymanager;1";
const nsISupports = Components.interfaces.nsISupports;
const nsICategoryManager = Components.interfaces.nsICategoryManager;
const nsICmdLineHandler = Components.interfaces.nsICmdLineHandler;
const nsICommandLine = Components.interfaces.nsICommandLine;
const nsICommandLineHandler = Components.interfaces.nsICommandLineHandler;
const nsIComponentRegistrar = Components.interfaces.nsIComponentRegistrar;
--- a/services/sync/tps/extensions/tps/resource/modules/addons.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/addons.jsm
@@ -53,17 +53,17 @@ Addon.prototype = {
addon: null,
uninstall: function uninstall() {
// find our addon locally
let cb = Async.makeSyncCallback();
AddonManager.getAddonByID(this.id, cb);
let addon = Async.waitForSyncCallback(cb);
- Logger.AssertTrue(!!addon, 'could not find addon ' + this.id + ' to uninstall');
+ Logger.AssertTrue(!!addon, "could not find addon " + this.id + " to uninstall");
cb = Async.makeSpinningCallback();
AddonUtils.uninstallAddon(addon, cb);
cb.wait();
},
find: function find(state) {
let cb = Async.makeSyncCallback();
--- a/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm
+++ b/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm
@@ -89,17 +89,17 @@ PlacesItem.prototype = {
"menu": "bookmarksMenuFolder",
"tags": "tagFolder",
"unfiled": "unfiledBookmarksFolder",
"toolbar": "toolbarFolder",
},
toString() {
var that = this;
- var props = ['uri', 'title', 'location', 'folder', 'feedUri', 'siteUri', 'livemark'];
+ var props = ["uri", "title", "location", "folder", "feedUri", "siteUri", "livemark"];
var string = (this.props.type ? this.props.type + " " : "") +
"(" +
(function() {
var ret = [];
for (var i in props) {
if (that.props[props[i]]) {
ret.push(props[i] + ": " + that.props[props[i]])
}
--- a/services/sync/tps/extensions/tps/resource/quit.js
+++ b/services/sync/tps/extensions/tps/resource/quit.js
@@ -26,34 +26,34 @@ function canQuitApplication() {
return true;
}
function goQuitApplication() {
if (!canQuitApplication()) {
return false;
}
- const kAppStartup = '@mozilla.org/toolkit/app-startup;1';
- const kAppShell = '@mozilla.org/appshell/appShellService;1';
+ const kAppStartup = "@mozilla.org/toolkit/app-startup;1";
+ const kAppShell = "@mozilla.org/appshell/appShellService;1";
var appService;
var forceQuit;
if (kAppStartup in Components.classes) {
appService = Components.classes[kAppStartup]
.getService(Components.interfaces.nsIAppStartup);
forceQuit = Components.interfaces.nsIAppStartup.eForceQuit;
} else if (kAppShell in Components.classes) {
appService = Components.classes[kAppShell].
getService(Components.interfaces.nsIAppShellService);
forceQuit = Components.interfaces.nsIAppShellService.eForceQuit;
} else {
- throw new Error('goQuitApplication: no AppStartup/appShell');
+ throw new Error("goQuitApplication: no AppStartup/appShell");
}
try {
appService.quit(forceQuit);
} catch (ex) {
- throw new Error('goQuitApplication: ' + ex);
+ throw new Error("goQuitApplication: " + ex);
}
return true;
}
--- a/services/sync/tps/extensions/tps/resource/tps.jsm
+++ b/services/sync/tps/extensions/tps/resource/tps.jsm
@@ -43,17 +43,17 @@ Cu.import("resource://tps/modules/tabs.j
Cu.import("resource://tps/modules/windows.jsm");
var hh = Cc["@mozilla.org/network/protocol;1?name=http"]
.getService(Ci.nsIHttpProtocolHandler);
var prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
var mozmillInit = {};
-Cu.import('resource://mozmill/driver/mozmill.js', mozmillInit);
+Cu.import("resource://mozmill/driver/mozmill.js", mozmillInit);
XPCOMUtils.defineLazyGetter(this, "fileProtocolHandler", () => {
let fileHandler = Services.io.getProtocolHandler("file");
return fileHandler.QueryInterface(Ci.nsIFileProtocolHandler);
});
// Options for wiping data during a sync
const SYNC_RESET_CLIENT = "resetClient";
@@ -478,23 +478,23 @@ var TPS = {
switch (action) {
case ACTION_ADD:
addon.install();
break;
case ACTION_DELETE:
addon.uninstall();
break;
case ACTION_VERIFY:
- Logger.AssertTrue(addon.find(state), 'addon ' + addon.id + ' not found');
+ Logger.AssertTrue(addon.find(state), "addon " + addon.id + " not found");
break;
case ACTION_VERIFY_NOT:
- Logger.AssertFalse(addon.find(state), 'addon ' + addon.id + " is present, but it shouldn't be");
+ Logger.AssertFalse(addon.find(state), "addon " + addon.id + " is present, but it shouldn't be");
break;
case ACTION_SET_ENABLED:
- Logger.AssertTrue(addon.setEnabled(state), 'addon ' + addon.id + ' not found');
+ Logger.AssertTrue(addon.setEnabled(state), "addon " + addon.id + " not found");
break;
default:
throw new Error("Unknown action for add-on: " + action);
}
}
Logger.logPass("executing action " + action.toUpperCase() +
" on addons");
},
@@ -503,20 +503,20 @@ var TPS = {
this.shouldValidateBookmarks = true;
try {
let items = [];
for (let folder in bookmarks) {
let last_item_pos = -1;
for (let bookmark of bookmarks[folder]) {
Logger.clearPotentialError();
let placesItem;
- bookmark['location'] = folder;
+ bookmark["location"] = folder;
if (last_item_pos != -1)
- bookmark['last_item_pos'] = last_item_pos;
+ bookmark["last_item_pos"] = last_item_pos;
let item_id = -1;
if (action != ACTION_MODIFY && action != ACTION_DELETE)
Logger.logInfo("executing action " + action.toUpperCase() +
" on bookmark " + JSON.stringify(bookmark));
if ("uri" in bookmark)
placesItem = new Bookmark(bookmark);
@@ -566,19 +566,19 @@ var TPS = {
DumpBookmarks();
throw (e);
}
},
MozmillEndTestListener: function TPS__MozmillEndTestListener(obj) {
Logger.logInfo("mozmill endTest: " + JSON.stringify(obj));
if (obj.failed > 0) {
- this.DumpError('mozmill test failed, name: ' + obj.name + ', reason: ' + JSON.stringify(obj.fails));
- } else if ('skipped' in obj && obj.skipped) {
- this.DumpError('mozmill test failed, name: ' + obj.name + ', reason: ' + obj.skipped_reason);
+ this.DumpError("mozmill test failed, name: " + obj.name + ", reason: " + JSON.stringify(obj.fails));
+ } else if ("skipped" in obj && obj.skipped) {
+ this.DumpError("mozmill test failed, name: " + obj.name + ", reason: " + obj.skipped_reason);
} else {
Utils.namedTimer(function() {
this.FinishAsyncOperation();
}, 2000, this, "postmozmilltest");
}
},
MozmillSetTestListener: function TPS__MozmillSetTestListener(obj) {
@@ -606,17 +606,17 @@ var TPS = {
},
/**
* Use Sync's bookmark validation code to see if we've corrupted the tree.
*/
ValidateBookmarks() {
let getServerBookmarkState = () => {
- let bookmarkEngine = Weave.Service.engineManager.get('bookmarks');
+ let bookmarkEngine = Weave.Service.engineManager.get("bookmarks");
let collection = bookmarkEngine.itemSource();
let collectionKey = bookmarkEngine.service.collectionKeys.keyForCollection(bookmarkEngine.name);
collection.full = true;
let items = [];
collection.recordHandler = function(item) {
item.decrypt(collectionKey);
items.push(item.cleartext);
};
@@ -856,17 +856,17 @@ var TPS = {
let settings = options || {};
Logger.init(logpath);
Logger.logInfo("Sync version: " + WEAVE_VERSION);
Logger.logInfo("Firefox buildid: " + Services.appinfo.appBuildID);
Logger.logInfo("Firefox version: " + Services.appinfo.version);
Logger.logInfo("Firefox source revision: " + (AppConstants.SOURCE_REVISION_URL || "unknown"));
Logger.logInfo("Firefox platform: " + AppConstants.platform);
- Logger.logInfo('Firefox Accounts enabled: ' + this.fxaccounts_enabled);
+ Logger.logInfo("Firefox Accounts enabled: " + this.fxaccounts_enabled);
// do some sync housekeeping
if (Weave.Service.isLoggedIn) {
this.DumpError("Sync logged in on startup...profile may be dirty");
return;
}
// Wait for Sync service to become ready.
@@ -888,17 +888,17 @@ var TPS = {
/**
* Executes a single test phase.
*
* This is called by RunTestPhase() after the environment is validated.
*/
_executeTestPhase: function _executeTestPhase(file, phase, settings) {
try {
- this.config = JSON.parse(prefs.getCharPref('tps.config'));
+ this.config = JSON.parse(prefs.getCharPref("tps.config"));
// parse the test file
Services.scriptloader.loadSubScript(file, this);
this._currentPhase = phase;
if (this._currentPhase.startsWith("cleanup-")) {
let profileToClean = Cc["@mozilla.org/toolkit/profile-service;1"]
.getService(Ci.nsIToolkitProfileService)
.selectedProfile.name;
this.phases[this._currentPhase] = profileToClean;
@@ -1029,28 +1029,28 @@ var TPS = {
}
this._enabledEngines = names;
},
RunMozmillTest: function TPS__RunMozmillTest(testfile) {
var mozmillfile = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsILocalFile);
- if (hh.oscpu.toLowerCase().indexOf('windows') > -1) {
+ if (hh.oscpu.toLowerCase().indexOf("windows") > -1) {
let re = /\/(\w)\/(.*)/;
this.config.testdir = this.config.testdir.replace(re, "$1://$2").replace(/\//g, "\\");
}
mozmillfile.initWithPath(this.config.testdir);
mozmillfile.appendRelativePath(testfile);
Logger.logInfo("Running mozmill test " + mozmillfile.path);
var frame = {};
- Cu.import('resource://mozmill/modules/frame.js', frame);
- frame.events.addListener('setTest', this.MozmillSetTestListener.bind(this));
- frame.events.addListener('endTest', this.MozmillEndTestListener.bind(this));
+ Cu.import("resource://mozmill/modules/frame.js", frame);
+ frame.events.addListener("setTest", this.MozmillSetTestListener.bind(this));
+ frame.events.addListener("endTest", this.MozmillEndTestListener.bind(this));
this.StartAsyncOperation();
frame.runTestFile(mozmillfile.path, null);
},
/**
* Return an object that when called, will block until the named event
* is observed. This is similar to waitForEvent, although is typically safer
* if you need to do some other work that may make the event fire.
--- a/storage/test/unit/test_bug-365166.js
+++ b/storage/test/unit/test_bug-365166.js
@@ -1,14 +1,14 @@
// Testcase for bug 365166 - crash [@ strlen] calling
// mozIStorageStatement::getColumnName of a statement created with
// "PRAGMA user_version" or "PRAGMA schema_version"
function run_test() {
- test('user');
- test('schema');
+ test("user");
+ test("schema");
function test(param) {
var colName = param + "_version";
var sql = "PRAGMA " + colName;
var file = getTestDB();
var storageService = Components.classes["@mozilla.org/storage/service;1"].
getService(Components.interfaces.mozIStorageService);
--- a/storage/test/unit/test_connection_asyncClose.js
+++ b/storage/test/unit/test_connection_asyncClose.js
@@ -78,48 +78,48 @@ add_task(function* test_double_asyncClos
* tell the difference between this happening and the method secretly shunting
* to close().
*/
add_task(function* test_asyncClose_on_sync_db() {
let db = getService().openDatabase(getTestDB());
// Branch coverage: (!asyncThread && mDBConn)
yield asyncClose(db);
- ok(true, 'closed sync connection asynchronously');
+ ok(true, "closed sync connection asynchronously");
});
/**
* Fail to asynchronously open a DB in order to get an async thread existing
* without having an open database and asyncClose invoked. As per the file
* doc-block, note that asyncClose will automatically be invoked by the
* AsyncInitDatabase when it fails to open the database. We will never be
* provided with a reference to the connection and so cannot call AsyncClose on
* it ourselves.
*/
add_task(function* test_asyncClose_failed_open() {
// This will fail and the promise will be rejected.
let openPromise = openAsyncDatabase(getFakeDB());
yield openPromise.then(
() => {
- ok(false, 'we should have failed to open the db; this test is broken!');
+ ok(false, "we should have failed to open the db; this test is broken!");
},
() => {
- ok(true, 'correctly failed to open db; bg asyncClose should happen');
+ ok(true, "correctly failed to open db; bg asyncClose should happen");
}
);
// (NB: we are unable to observe the thread shutdown, but since we never open
// a database, this test is not going to interfere with other tests so much.)
});
// THE TEST BELOW WANTS TO BE THE LAST TEST WE RUN. DO NOT MAKE IT SAD.
/**
* Verify that asyncClose without a callback does not explode. Without a
* callback the shutdown is not actually observable, so we run this test last
* in order to avoid weird overlaps.
*/
add_task(function* test_asyncClose_does_not_throw_without_callback() {
let db = yield openAsyncDatabase(getTestDB());
// Branch coverage: (asyncThread && mDBConn)
db.asyncClose();
- ok(true, 'if we shutdown cleanly and do not crash, then we succeeded');
+ ok(true, "if we shutdown cleanly and do not crash, then we succeeded");
});
// OBEY SHOUTING UPPER-CASE COMMENTS.
// ADD TESTS ABOVE THE FORMER TEST, NOT BELOW IT.
--- a/storage/test/unit/test_connection_executeAsync.js
+++ b/storage/test/unit/test_connection_executeAsync.js
@@ -48,20 +48,20 @@ add_task(function* test_first_create_and
stmts[1].bindByIndex(2, null);
stmts[1].bindBlobByIndex(3, BLOB, BLOB.length);
// asynchronously execute the statements
let execResult = yield executeMultipleStatementsAsync(
db,
stmts,
function(aResultSet) {
- ok(false, 'we only did inserts so we should not have gotten results!');
+ ok(false, "we only did inserts so we should not have gotten results!");
});
equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, execResult,
- 'execution should have finished successfully.');
+ "execution should have finished successfully.");
// Check that the result is in the table
let stmt = db.createStatement(
"SELECT string, number, nuller, blober FROM test WHERE id = ?"
);
stmt.bindByIndex(0, INTEGER);
try {
do_check_true(stmt.executeStep());
@@ -136,20 +136,20 @@ add_task(function* test_last_multiple_bi
countStmt.reset();
}
// Execute asynchronously.
let execResult = yield executeMultipleStatementsAsync(
db,
stmts,
function(aResultSet) {
- ok(false, 'we only did inserts so we should not have gotten results!');
+ ok(false, "we only did inserts so we should not have gotten results!");
});
equal(Ci.mozIStorageStatementCallback.REASON_FINISHED, execResult,
- 'execution should have finished successfully.');
+ "execution should have finished successfully.");
// Check to make sure we added all of our rows.
try {
do_check_true(countStmt.executeStep());
do_check_eq(currentRows + (ITERATIONS * AMOUNT_TO_ADD),
countStmt.row.count);
} finally {
countStmt.finalize();
--- a/storage/test/unit/test_like.js
+++ b/storage/test/unit/test_like.js
@@ -61,116 +61,116 @@ function test_count() {
do_check_true(stmt.executeStep());
do_check_eq(stmt.getInt32(0), 12);
stmt.reset();
stmt.finalize();
}
function test_like_1() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'abc');
+ stmt.bindByIndex(0, "abc");
var solutions = ["abc", "ABC"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_2() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'ABC');
+ stmt.bindByIndex(0, "ABC");
var solutions = ["abc", "ABC"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_3() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'aBc');
+ stmt.bindByIndex(0, "aBc");
var solutions = ["abc", "ABC"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_4() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'abc%');
+ stmt.bindByIndex(0, "abc%");
var solutions = ["abc", "abcd", "ABC", "ABC abc xyz"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_5() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'a_c');
+ stmt.bindByIndex(0, "a_c");
var solutions = ["abc", "ABC"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_6() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'ab%d');
+ stmt.bindByIndex(0, "ab%d");
var solutions = ["abcd", "abd"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_7() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, 'a_c%');
+ stmt.bindByIndex(0, "a_c%");
var solutions = ["abc", "abcd", "ABC", "ABC abc xyz"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
}
function test_like_8() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?;");
- stmt.bindByIndex(0, '%bcd');
+ stmt.bindByIndex(0, "%bcd");
var solutions = ["abcd", "bcd"];
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_true(stmt.executeStep());
do_check_true(solutions.indexOf(stmt.getString(0)) != -1);
do_check_false(stmt.executeStep());
stmt.reset();
stmt.finalize();
--- a/storage/test/unit/test_like_escape.js
+++ b/storage/test/unit/test_like_escape.js
@@ -16,29 +16,29 @@ function setup() {
// insert LATIN_ae, but search on LATIN_AE
stmt.bindByIndex(0, "foo%20" + LATIN1_ae + "/_bar");
stmt.execute();
stmt.finalize();
}
function test_escape_for_like_ascii() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?1 ESCAPE '/'");
- var paramForLike = stmt.escapeStringForLIKE("oo/bar_baz%20chees", '/');
+ var paramForLike = stmt.escapeStringForLIKE("oo/bar_baz%20chees", "/");
// verify that we escaped / _ and %
do_check_eq(paramForLike, "oo//bar/_baz/%20chees");
// prepend and append with % for "contains"
stmt.bindByIndex(0, "%" + paramForLike + "%");
stmt.executeStep();
do_check_eq("foo/bar_baz%20cheese", stmt.getString(0));
stmt.finalize();
}
function test_escape_for_like_non_ascii() {
var stmt = createStatement("SELECT x FROM t1 WHERE x LIKE ?1 ESCAPE '/'");
- var paramForLike = stmt.escapeStringForLIKE("oo%20" + LATIN1_AE + "/_ba", '/');
+ var paramForLike = stmt.escapeStringForLIKE("oo%20" + LATIN1_AE + "/_ba", "/");
// verify that we escaped / _ and %
do_check_eq(paramForLike, "oo/%20" + LATIN1_AE + "///_ba");
// prepend and append with % for "contains"
stmt.bindByIndex(0, "%" + paramForLike + "%");
stmt.executeStep();
do_check_eq("foo%20" + LATIN1_ae + "/_bar", stmt.getString(0));
stmt.finalize();
}
--- a/toolkit/.eslintrc.js
+++ b/toolkit/.eslintrc.js
@@ -197,16 +197,20 @@ module.exports = {
"no-useless-return": "error",
// No using with
"no-with": "error",
// Require object-literal shorthand with ES6 method syntax
"object-shorthand": ["error", "always", { "avoidQuotes": true }],
+ // Require double-quotes everywhere, except where quotes are escaped
+ // or template literals are used.
+ "quotes": ["error", "double", { "avoidEscape": true, "allowTemplateLiterals": true }],
+
// No spacing inside rest or spread expressions
"rest-spread-spacing": "error",
// Always require semicolon at end of statement
// "semi": ["error", "always"],
// Require space before blocks
"space-before-blocks": "error",
--- a/toolkit/components/aboutcache/content/aboutCache.js
+++ b/toolkit/components/aboutcache/content/aboutCache.js
@@ -1,43 +1,43 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// First, parse and save the incoming arguments ("?storage=name&context=key")
// Note: window.location.search doesn't work with nsSimpleURIs used for about:* addresses.
var search = window.location.href.match(/^.*\?(.*)$/);
-var searchParams = new URLSearchParams(search ? search[1] : '');
-var storage = searchParams.get('storage');
-var cacheContext = searchParams.get('context');
+var searchParams = new URLSearchParams(search ? search[1] : "");
+var storage = searchParams.get("storage");
+var cacheContext = searchParams.get("context");
// The context is in a format as used by the HTTP cache v2 back end
if (cacheContext)
var [context, isAnon, isInBrowser, appId, isPrivate] = cacheContext.match(/(a,)?(b,)?(i\d+,)?(p,)?/);
if (appId)
appId = appId.match(/i(\d+),/)[1];
function $(id) { return document.getElementById(id) || {}; }
// Initialize the context UI controls at the start according what we got in the "context=" argument
-addEventListener('DOMContentLoaded', function() {
- $('anon').checked = !!isAnon;
- $('inbrowser').checked = !!isInBrowser;
- $('appid').value = appId || '';
- $('priv').checked = !!isPrivate;
+addEventListener("DOMContentLoaded", function() {
+ $("anon").checked = !!isAnon;
+ $("inbrowser").checked = !!isInBrowser;
+ $("appid").value = appId || "";
+ $("priv").checked = !!isPrivate;
}, false);
// When user presses the [Update] button, we build a new context key according the UI control
// values and navigate to a new about:cache?storage=<name>&context=<key> URL.
function navigate() {
- context = '';
- if ($('anon').checked)
- context += 'a,';
- if ($('inbrowser').checked)
- context += 'b,';
- if ($('appid').value)
- context += 'i' + $('appid').value + ',';
- if ($('priv').checked)
- context += 'p,';
+ context = "";
+ if ($("anon").checked)
+ context += "a,";
+ if ($("inbrowser").checked)
+ context += "b,";
+ if ($("appid").value)
+ context += "i" + $("appid").value + ",";
+ if ($("priv").checked)
+ context += "p,";
- window.location.href = 'about:cache?storage=' + storage + '&context=' + context;
+ window.location.href = "about:cache?storage=" + storage + "&context=" + context;
}
--- a/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js
+++ b/toolkit/components/aboutcheckerboard/content/aboutCheckerboard.js
@@ -4,39 +4,39 @@
"use strict";
var trace;
var service;
var reports;
function onLoad() {
- trace = document.getElementById('trace');
+ trace = document.getElementById("trace");
service = new CheckerboardReportService();
updateEnabled();
reports = service.getReports();
for (var i = 0; i < reports.length; i++) {
let text = "Severity " + reports[i].severity + " at " + new Date(reports[i].timestamp).toString();
- let link = document.createElement('a');
- link.href = 'javascript:showReport(' + i + ')';
+ let link = document.createElement("a");
+ link.href = "javascript:showReport(" + i + ")";
link.textContent = text;
- let bullet = document.createElement('li');
+ let bullet = document.createElement("li");
bullet.appendChild(link);
document.getElementById(reports[i].reason).appendChild(bullet);
}
}
function updateEnabled() {
- let enabled = document.getElementById('enabled');
+ let enabled = document.getElementById("enabled");
if (service.isRecordingEnabled()) {
- enabled.textContent = 'enabled';
- enabled.style.color = 'green';
+ enabled.textContent = "enabled";
+ enabled.style.color = "green";
} else {
- enabled.textContent = 'disabled';
- enabled.style.color = 'red';
+ enabled.textContent = "disabled";
+ enabled.style.color = "red";
}
}
function toggleEnabled() {
service.setRecordingEnabled(!service.isRecordingEnabled());
updateEnabled();
}
@@ -137,17 +137,17 @@ function loadData() {
var color = tokens[j++];
renderData[destIndex].rects[color] = rect;
rect.x = parseFloat(tokens[j++]);
rect.y = parseFloat(tokens[j++]);
rect.width = parseFloat(tokens[j++]);
rect.height = parseFloat(tokens[j++]);
rect.dataText = trace.value.substring(charPos, charPos + lines[i].length);
- if (!getFlag('excludePageFromZoom') || color != 'brown') {
+ if (!getFlag("excludePageFromZoom") || color != "brown") {
if (typeof minX == "undefined") {
minX = rect.x;
minY = rect.y;
maxX = rect.x + rect.width;
maxY = rect.y + rect.height;
} else {
minX = Math.min(minX, rect.x);
minY = Math.min(minY, rect.y);
@@ -172,22 +172,22 @@ function loadData() {
// returns false if currentFrame is out of bounds, true otherwise
function renderFrame() {
var frame = currentFrame;
if (frame < 0 || frame >= renderData.length) {
log("Invalid frame index");
return false;
}
- var canvas = document.getElementById('canvas');
+ var canvas = document.getElementById("canvas");
if (!canvas.getContext) {
log("No canvas context");
}
- var context = canvas.getContext('2d');
+ var context = canvas.getContext("2d");
// midpoint of the bounding box
var midX = (minX + maxX) / 2.0;
var midY = (minY + maxY) / 2.0;
// midpoint of the canvas
var cmx = canvas.width / 2.0;
var cmy = canvas.height / 2.0;
@@ -208,29 +208,29 @@ function renderFrame() {
context.strokeRect(
projectX(rect.x),
projectY(rect.y),
rect.width * scale,
rect.height * scale);
}
// clear canvas
- context.fillStyle = 'white';
+ context.fillStyle = "white";
context.fillRect(0, 0, canvas.width, canvas.height);
- var activeData = '';
+ var activeData = "";
// draw rects
for (var i in renderData[frame].rects) {
drawRect(i, renderData[frame].rects[i]);
activeData += "\n" + renderData[frame].rects[i].dataText;
}
// draw timestamp and frame counter
- context.fillStyle = 'black';
+ context.fillStyle = "black";
context.fillText((frame + 1) + "/" + renderData.length + ": " + renderData[frame].timestamp, 5, 15);
- document.getElementById('active').textContent = activeData;
+ document.getElementById("active").textContent = activeData;
return true;
}
// -- Player controls --
function reset(beginning) {
currentFrame = (beginning ? 0 : renderData.length - 1);
--- a/toolkit/components/aboutmemory/content/aboutMemory.js
+++ b/toolkit/components/aboutmemory/content/aboutMemory.js
@@ -49,33 +49,33 @@ XPCOMUtils.defineLazyGetter(this, "nsFil
"nsIFile", "initWithPath"));
XPCOMUtils.defineLazyGetter(this, "nsGzipConverter",
() => CC("@mozilla.org/streamconv;1?from=gzip&to=uncompressed",
"nsIStreamConverter"));
var gMgr = Cc["@mozilla.org/memory-reporter-manager;1"]
.getService(Ci.nsIMemoryReporterManager);
-const gPageName = 'about:memory';
+const gPageName = "about:memory";
document.title = gPageName;
const gUnnamedProcessStr = "Main Process";
var gIsDiff = false;
// ---------------------------------------------------------------------------
// Forward slashes in URLs in paths are represented with backslashes to avoid
// being mistaken for path separators. Paths/names where this hasn't been
// undone are prefixed with "unsafe"; the rest are prefixed with "safe".
function flipBackslashes(aUnsafeStr) {
// Save memory by only doing the replacement if it's necessary.
- return (aUnsafeStr.indexOf('\\') === -1)
+ return (aUnsafeStr.indexOf("\\") === -1)
? aUnsafeStr
- : aUnsafeStr.replace(/\\/g, '/');
+ : aUnsafeStr.replace(/\\/g, "/");
}
const gAssertionFailureMsgPrefix = "aboutMemory.js assertion failed: ";
// This is used for things that should never fail, and indicate a defect in
// this file if they do.
function assert(aCond, aMsg) {
if (!aCond) {
@@ -105,17 +105,17 @@ function handleException(ex) {
function reportAssertionFailure(aMsg) {
let debug = Cc["@mozilla.org/xpcom/debug;1"].getService(Ci.nsIDebug2);
if (debug.isDebugBuild) {
debug.assertion(aMsg, "false", "aboutMemory.js", 0);
}
}
function debug(x) {
- let section = appendElement(document.body, 'div', 'section');
+ let section = appendElement(document.body, "div", "section");
appendElementWithText(section, "div", "debug", JSON.stringify(x));
}
// ---------------------------------------------------------------------------
function onUnload() {
}
@@ -144,35 +144,35 @@ function updateTitleMainAndFooter(aTitle
document.title += " (" + aTitleNote + ")";
}
// Clear gMain by replacing it with an empty node.
let tmp = gMain.cloneNode(false);
gMain.parentNode.replaceChild(tmp, gMain);
gMain = tmp;
- gMain.classList.remove('hidden');
- gMain.classList.remove('verbose');
- gMain.classList.remove('non-verbose');
+ gMain.classList.remove("hidden");
+ gMain.classList.remove("verbose");
+ gMain.classList.remove("non-verbose");
if (gVerbose) {
- gMain.classList.add(gVerbose.checked ? 'verbose' : 'non-verbose');
+ gMain.classList.add(gVerbose.checked ? "verbose" : "non-verbose");
}
let msgElement;
if (aMsg) {
let className = "section"
if (aClassName) {
className = className + " " + aClassName;
}
- msgElement = appendElementWithText(gMain, 'div', className, aMsg);
+ msgElement = appendElementWithText(gMain, "div", className, aMsg);
}
switch (aFooterAction) {
- case HIDE_FOOTER: gFooter.classList.add('hidden'); break;
- case SHOW_FOOTER: gFooter.classList.remove('hidden'); break;
+ case HIDE_FOOTER: gFooter.classList.add("hidden"); break;
+ case SHOW_FOOTER: gFooter.classList.remove("hidden"); break;
default: assert(false, "bad footer action in updateTitleMainAndFooter");
}
return msgElement;
}
function updateMainAndFooter(aMsg, aFooterAction, aClassName) {
return updateTitleMainAndFooter("", aMsg, aFooterAction, aClassName);
}
@@ -343,19 +343,19 @@ function onLoad() {
appendButton(row3, GCDesc, doGC, "GC");
appendButton(row3, CCDesc, doCC, "CC");
appendButton(row3, MMDesc, doMMU, "Minimize memory usage");
let row4 = appendElement(ops, "div", "opsRow");
appendElementWithText(row4, "div", "opsRowLabel", "Save GC & CC logs");
appendButton(row4, GCAndCCLogDesc,
- saveGCLogAndConciseCCLog, "Save concise", 'saveLogsConcise');
+ saveGCLogAndConciseCCLog, "Save concise", "saveLogsConcise");
appendButton(row4, GCAndCCAllLogDesc,
- saveGCLogAndVerboseCCLog, "Save verbose", 'saveLogsVerbose');
+ saveGCLogAndVerboseCCLog, "Save verbose", "saveLogsVerbose");
// Three cases here:
// - DMD is disabled (i.e. not built): don't show the button.
// - DMD is enabled but is not running: show the button, but disable it.
// - DMD is enabled and is running: show the button and enable it.
if (gMgr.isDMDEnabled) {
let row5 = appendElement(ops, "div", "opsRow");
@@ -366,44 +366,44 @@ function onLoad() {
appendButton(row5, enableButtons ? DMDEnabledDesc : DMDDisabledDesc,
doDMD, "Save");
dmdButton.disabled = !enableButtons;
}
// Generate the main div, where content ("section" divs) will go. It's
// hidden at first.
- gMain = appendElement(document.body, 'div', '');
- gMain.id = 'mainDiv';
+ gMain = appendElement(document.body, "div", "");
+ gMain.id = "mainDiv";
// Generate the footer. It's hidden at first.
- gFooter = appendElement(document.body, 'div', 'ancillary hidden');
+ gFooter = appendElement(document.body, "div", "ancillary hidden");
let a = appendElementWithText(gFooter, "a", "option",
"Troubleshooting information");
a.href = "about:support";
let legendText1 = "Click on a non-leaf node in a tree to expand ('++') " +
"or collapse ('--') its children.";
let legendText2 = "Hover the pointer over the name of a memory report " +
"to see a description of what it measures.";
appendElementWithText(gFooter, "div", "legend", legendText1);
appendElementWithText(gFooter, "div", "legend hiddenOnMobile", legendText2);
// See if we're loading from a file. (Because about:memory is a non-standard
// URL, location.search is undefined, so we have to use location.href
// instead.)
- let search = location.href.split('?')[1];
+ let search = location.href.split("?")[1];
if (search) {
- let searchSplit = search.split('&');
+ let searchSplit = search.split("&");
for (let i = 0; i < searchSplit.length; i++) {
- if (searchSplit[i].toLowerCase().startsWith('file=')) {
- let filename = searchSplit[i].substring('file='.length);
+ if (searchSplit[i].toLowerCase().startsWith("file=")) {
+ let filename = searchSplit[i].substring("file=".length);
updateAboutMemoryFromFile(decodeURIComponent(filename));
return;
}
}
}
}
// ---------------------------------------------------------------------------
@@ -457,24 +457,24 @@ function doDMD() {
}
}
function dumpGCLogAndCCLog(aVerbose) {
let dumper = Cc["@mozilla.org/memory-info-dumper;1"]
.getService(Ci.nsIMemoryInfoDumper);
let inProgress = updateMainAndFooter("Saving logs...", HIDE_FOOTER);
- let section = appendElement(gMain, 'div', "section");
+ let section = appendElement(gMain, "div", "section");
function displayInfo(gcLog, ccLog, isParent) {
- appendElementWithText(section, 'div', "",
+ appendElementWithText(section, "div", "",
"Saved GC log to " + gcLog.path);
let ccLogType = aVerbose ? "verbose" : "concise";
- appendElementWithText(section, 'div', "",
+ appendElementWithText(section, "div", "",
"Saved " + ccLogType + " CC log to " + ccLog.path);
}
dumper.dumpGCAndCCLogsToFile("", aVerbose, /* dumpChildProcesses = */ true,
{ onDump: displayInfo,
onFinish() {
inProgress.remove();
}
@@ -939,17 +939,17 @@ function appendAboutMemoryMain(aProcessR
}
assert(aPresence === undefined ||
aPresence == DReport.PRESENT_IN_FIRST_ONLY ||
aPresence == DReport.PRESENT_IN_SECOND_ONLY,
"bad presence");
let process = aProcess === "" ? gUnnamedProcessStr : aProcess;
- let unsafeNames = aUnsafePath.split('/');
+ let unsafeNames = aUnsafePath.split("/");
let unsafeName0 = unsafeNames[0];
let isDegenerate = unsafeNames.length === 1;
// Get the PColl table for the process, creating it if necessary.
let pcoll = pcollsByProcess[process];
if (!pcollsByProcess[process]) {
pcoll = pcollsByProcess[process] = new PColl();
}
@@ -1011,18 +1011,18 @@ function appendAboutMemoryMain(aProcessR
if (aProcessA == gUnnamedProcessStr) {
return -1;
}
if (aProcessB == gUnnamedProcessStr) {
return 1;
}
// Then sort by resident size.
- let nodeA = pcollsByProcess[aProcessA]._degenerates['resident'];
- let nodeB = pcollsByProcess[aProcessB]._degenerates['resident'];
+ let nodeA = pcollsByProcess[aProcessA]._degenerates["resident"];
+ let nodeB = pcollsByProcess[aProcessB]._degenerates["resident"];
let residentA = nodeA ? nodeA._amount : -1;
let residentB = nodeB ? nodeB._amount : -1;
if (residentA > residentB) {
return -1;
}
if (residentA < residentB) {
return 1;
@@ -1037,17 +1037,17 @@ function appendAboutMemoryMain(aProcessR
}
return 0;
});
// Generate output for each process.
for (let i = 0; i < processes.length; i++) {
let process = processes[i];
- let section = appendElement(gMain, 'div', 'section');
+ let section = appendElement(gMain, "div", "section");
appendProcessAboutMemoryElements(section, i, process,
pcollsByProcess[process]._trees,
pcollsByProcess[process]._degenerates,
pcollsByProcess[process]._heapTotal,
aHasMozMallocUsableSize);
}
}
@@ -1103,17 +1103,17 @@ TreeNode.prototype = {
// instead look at the maximum absolute value of the node and all of its
// descendants.
maxAbsDescendant() {
if (!this._kids) {
// No kids? Just return the absolute value of the amount.
return Math.abs(this._amount);
}
- if ('_maxAbsDescendant' in this) {
+ if ("_maxAbsDescendant" in this) {
// We've computed this before? Return the saved value.
return this._maxAbsDescendant;
}
// Compute the maximum absolute value of all descendants.
let max = Math.abs(this._amount);
for (let i = 0; i < this._kids.length; i++) {
max = Math.max(max, this._kids[i].maxAbsDescendant());
@@ -1173,17 +1173,17 @@ function fillInTree(aRoot) {
if (!aT._kids) {
// Leaf node. Has already been filled in.
} else if (aT._kids.length === 1 && aT != aRoot) {
// Non-root, non-leaf node with one child. Merge the child with the node
// to avoid redundant entries.
let kid = aT._kids[0];
let kidBytes = fillInNonLeafNodes(kid);
- aT._unsafeName += '/' + kid._unsafeName;
+ aT._unsafeName += "/" + kid._unsafeName;
if (kid._kids) {
aT._kids = kid._kids;
} else {
delete aT._kids;
}
aT._amount = kidBytes;
aT._description = kid._description;
if (kid._nMerged !== undefined) {
@@ -1203,17 +1203,17 @@ function fillInTree(aRoot) {
// if one set has a node with children and the other has the same node
// but without children -- e.g. the first has "a/b/c" and "a/b/d", but
// the second only has "a/b" -- we need to add a fake node "a/b/(fake)"
// to the second to make the trees comparable. It's ugly, but it works.
if (aT._amount !== undefined &&
(aT._presence === DReport.PRESENT_IN_FIRST_ONLY ||
aT._presence === DReport.PRESENT_IN_SECOND_ONLY)) {
aT._amount += kidsBytes;
- let fake = new TreeNode('(fake child)', aT._units);
+ let fake = new TreeNode("(fake child)", aT._units);
fake._presence = DReport.ADDED_FOR_BALANCE;
fake._amount = aT._amount - kidsBytes;
aT._kids.push(fake);
delete aT._presence;
} else {
assert(aT._amount === undefined,
"_amount already set for non-leaf node")
aT._amount = kidsBytes;
@@ -1495,17 +1495,17 @@ function appendProcessAboutMemoryElement
let pre = appendSectionHeader(aP, "Other Measurements");
for (let i = 0; i < otherTrees.length; i++) {
let t = otherTrees[i];
appendTreeElements(pre, t, aProcess, "");
appendTextNode(pre, "\n"); // blank lines after non-degenerate trees
}
for (let i = 0; i < otherDegenerates.length; i++) {
let t = otherDegenerates[i];
- let padText = pad("", maxStringLength - t.toString().length, ' ');
+ let padText = pad("", maxStringLength - t.toString().length, " ");
appendTreeElements(pre, t, aProcess, padText);
}
appendTextNode(aP, "\n"); // gives nice spacing when we copy and paste
// Add any warnings about inaccuracies in the "explicit" tree due to platform
// limitations. These must be computed after generating all the text. The
// newlines give nice spacing if we copy+paste into a text buffer.
if (hasExplicitTree) {
@@ -1676,25 +1676,25 @@ function appendMrNameSpan(aP, aDescripti
"This value is the sum of " + aNMerged +
" memory reports that all have the same path.";
}
if (aPresence) {
let c, title;
switch (aPresence) {
case DReport.PRESENT_IN_FIRST_ONLY:
- c = '-';
+ c = "-";
title = "This value was only present in the first set of memory reports.";
break;
case DReport.PRESENT_IN_SECOND_ONLY:
- c = '+';
+ c = "+";
title = "This value was only present in the second set of memory reports.";
break;
case DReport.ADDED_FOR_BALANCE:
- c = '!';
+ c = "!";
title = "One of the sets of memory reports lacked children for this " +
"node's parent. This is a fake child node added to make the " +
"two memory sets comparable.";
break;
default: assert(false, "bad presence");
break;
}
let noteSpan = appendElementWithText(aP, "span", "mrNote",
--- a/toolkit/components/addoncompat/CompatWarning.jsm
+++ b/toolkit/components/addoncompat/CompatWarning.jsm
@@ -49,17 +49,17 @@ var CompatWarning = {
if (addon) {
let histogram = Services.telemetry.getKeyedHistogramById("ADDON_SHIM_USAGE");
histogram.add(addon, warning ? warning.number : 0);
}
if (!Preferences.get("dom.ipc.shims.enabledWarnings", false))
return;
- let error = Cc['@mozilla.org/scripterror;1'].createInstance(Ci.nsIScriptError);
+ let error = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError);
if (!error || !Services.console) {
// Too late during shutdown to use the nsIConsole
return;
}
let message = `Warning: ${msg}`;
if (warning)
message += `\nMore info at: ${warning.url}`;
--- a/toolkit/components/addoncompat/RemoteAddonsParent.jsm
+++ b/toolkit/components/addoncompat/RemoteAddonsParent.jsm
@@ -6,17 +6,17 @@ this.EXPORTED_SYMBOLS = ["RemoteAddonsPa
const Ci = Components.interfaces;
const Cc = Components.classes;
const Cu = Components.utils;
const Cr = Components.results;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/RemoteWebProgress.jsm");
-Cu.import('resource://gre/modules/Services.jsm');
+Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "BrowserUtils",
"resource://gre/modules/BrowserUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Prefetcher",
"resource://gre/modules/Prefetcher.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "CompatWarning",
--- a/toolkit/components/captivedetect/captivedetect.js
+++ b/toolkit/components/captivedetect/captivedetect.js
@@ -1,41 +1,41 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-Cu.import('resource://gre/modules/Services.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyServiceGetter(this, "gSysMsgr",
"@mozilla.org/system-message-internal;1",
"nsISystemMessagesInternal");
const DEBUG = false; // set to true to show debug messages
-const kCAPTIVEPORTALDETECTOR_CONTRACTID = '@mozilla.org/toolkit/captive-detector;1';
-const kCAPTIVEPORTALDETECTOR_CID = Components.ID('{d9cd00ba-aa4d-47b1-8792-b1fe0cd35060}');
+const kCAPTIVEPORTALDETECTOR_CONTRACTID = "@mozilla.org/toolkit/captive-detector;1";
+const kCAPTIVEPORTALDETECTOR_CID = Components.ID("{d9cd00ba-aa4d-47b1-8792-b1fe0cd35060}");
-const kOpenCaptivePortalLoginEvent = 'captive-portal-login';
-const kAbortCaptivePortalLoginEvent = 'captive-portal-login-abort';
-const kCaptivePortalLoginSuccessEvent = 'captive-portal-login-success';
-const kCaptivePortalCheckComplete = 'captive-portal-check-complete';
+const kOpenCaptivePortalLoginEvent = "captive-portal-login";
+const kAbortCaptivePortalLoginEvent = "captive-portal-login-abort";
+const kCaptivePortalLoginSuccessEvent = "captive-portal-login-success";
+const kCaptivePortalCheckComplete = "captive-portal-check-complete";
-const kCaptivePortalSystemMessage = 'captive-portal';
+const kCaptivePortalSystemMessage = "captive-portal";
function URLFetcher(url, timeout) {
let self = this;
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', url, true);
+ xhr.open("GET", url, true);
// Prevent the request from reading from the cache.
xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE;
// Prevent the request from writing to the cache.
xhr.channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING;
// Prevent privacy leaks
xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS;
// The Cache-Control header is only interpreted by proxies and the
// final destination. It does not help if a resource is already
@@ -80,18 +80,18 @@ function LoginObserver(captivePortalDete
const LOGIN_OBSERVER_STATE_DETACHED = 0; /* Should not monitor network activity since no ongoing login procedure */
const LOGIN_OBSERVER_STATE_IDLE = 1; /* No network activity currently, waiting for a longer enough idle period */
const LOGIN_OBSERVER_STATE_BURST = 2; /* Network activity is detected, probably caused by a login procedure */
const LOGIN_OBSERVER_STATE_VERIFY_NEEDED = 3; /* Verifing network accessiblity is required after a long enough idle */
const LOGIN_OBSERVER_STATE_VERIFYING = 4; /* LoginObserver is probing if public network is available */
let state = LOGIN_OBSERVER_STATE_DETACHED;
- let timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
- let activityDistributor = Cc['@mozilla.org/network/http-activity-distributor;1']
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
+ let activityDistributor = Cc["@mozilla.org/network/http-activity-distributor;1"]
.getService(Ci.nsIHttpActivityDistributor);
let urlFetcher = null;
let waitForNetworkActivity = Services.appinfo.widgetToolkit == "gonk";
let pageCheckingDone = function pageCheckingDone() {
if (state === LOGIN_OBSERVER_STATE_VERIFYING) {
urlFetcher = null;
@@ -129,30 +129,30 @@ function LoginObserver(captivePortalDete
attach: function attach() {
if (state === LOGIN_OBSERVER_STATE_DETACHED) {
activityDistributor.addObserver(this);
state = LOGIN_OBSERVER_STATE_IDLE;
timer.initWithCallback(this,
captivePortalDetector._pollingTime,
timer.TYPE_ONE_SHOT);
- debug('attach HttpObserver for login activity');
+ debug("attach HttpObserver for login activity");
}
},
detach: function detach() {
if (state !== LOGIN_OBSERVER_STATE_DETACHED) {
if (urlFetcher) {
urlFetcher.abort();
urlFetcher = null;
}
activityDistributor.removeObserver(this);
timer.cancel();
state = LOGIN_OBSERVER_STATE_DETACHED;
- debug('detach HttpObserver for login activity');
+ debug("detach HttpObserver for login activity");
}
},
/*
* Treat all HTTP transactions as captive portal login activities.
*/
observeActivity: function observeActivity(aHttpChannel, aActivityType,
aActivitySubtype, aTimestamp,
@@ -205,113 +205,113 @@ function LoginObserver(captivePortalDete
function CaptivePortalDetector() {
// Load preference
this._canonicalSiteURL = null;
this._canonicalSiteExpectedContent = null;
try {
this._canonicalSiteURL =
- Services.prefs.getCharPref('captivedetect.canonicalURL');
+ Services.prefs.getCharPref("captivedetect.canonicalURL");
this._canonicalSiteExpectedContent =
- Services.prefs.getCharPref('captivedetect.canonicalContent');
+ Services.prefs.getCharPref("captivedetect.canonicalContent");
} catch (e) {
- debug('canonicalURL or canonicalContent not set.')
+ debug("canonicalURL or canonicalContent not set.")
}
this._maxWaitingTime =
- Services.prefs.getIntPref('captivedetect.maxWaitingTime');
+ Services.prefs.getIntPref("captivedetect.maxWaitingTime");
this._pollingTime =
- Services.prefs.getIntPref('captivedetect.pollingTime');
+ Services.prefs.getIntPref("captivedetect.pollingTime");
this._maxRetryCount =
- Services.prefs.getIntPref('captivedetect.maxRetryCount');
- debug('Load Prefs {site=' + this._canonicalSiteURL + ',content='
- + this._canonicalSiteExpectedContent + ',time=' + this._maxWaitingTime
- + "max-retry=" + this._maxRetryCount + '}');
+ Services.prefs.getIntPref("captivedetect.maxRetryCount");
+ debug("Load Prefs {site=" + this._canonicalSiteURL + ",content="
+ + this._canonicalSiteExpectedContent + ",time=" + this._maxWaitingTime
+ + "max-retry=" + this._maxRetryCount + "}");
// Create HttpObserver for monitoring the login procedure
this._loginObserver = LoginObserver(this);
this._nextRequestId = 0;
this._runningRequest = null;
this._requestQueue = []; // Maintain a progress table, store callbacks and the ongoing XHR
this._interfaceNames = {}; // Maintain names of the requested network interfaces
- debug('CaptiveProtalDetector initiated, waiting for network connection established');
+ debug("CaptiveProtalDetector initiated, waiting for network connection established");
}
CaptivePortalDetector.prototype = {
classID: kCAPTIVEPORTALDETECTOR_CID,
classInfo: XPCOMUtils.generateCI({classID: kCAPTIVEPORTALDETECTOR_CID,
contractID: kCAPTIVEPORTALDETECTOR_CONTRACTID,
- classDescription: 'Captive Portal Detector',
+ classDescription: "Captive Portal Detector",
interfaces: [Ci.nsICaptivePortalDetector]}),
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalDetector]),
// nsICaptivePortalDetector
checkCaptivePortal: function checkCaptivePortal(aInterfaceName, aCallback) {
if (!this._canonicalSiteURL) {
- throw Components.Exception('No canonical URL set up.');
+ throw Components.Exception("No canonical URL set up.");
}
// Prevent multiple requests on a single network interface
if (this._interfaceNames[aInterfaceName]) {
- throw Components.Exception('Do not allow multiple request on one interface: ' + aInterfaceName);
+ throw Components.Exception("Do not allow multiple request on one interface: " + aInterfaceName);
}
let request = {interfaceName: aInterfaceName};
if (aCallback) {
let callback = aCallback.QueryInterface(Ci.nsICaptivePortalCallback);
- request['callback'] = callback;
- request['retryCount'] = 0;
+ request["callback"] = callback;
+ request["retryCount"] = 0;
}
this._addRequest(request);
},
abort: function abort(aInterfaceName) {
- debug('abort for ' + aInterfaceName);
+ debug("abort for " + aInterfaceName);
this._removeRequest(aInterfaceName);
},
finishPreparation: function finishPreparation(aInterfaceName) {
debug('finish preparation phase for interface "' + aInterfaceName + '"');
if (!this._runningRequest
|| this._runningRequest.interfaceName !== aInterfaceName) {
- debug('invalid finishPreparation for ' + aInterfaceName);
- throw Components.Exception('only first request is allowed to invoke |finishPreparation|');
+ debug("invalid finishPreparation for " + aInterfaceName);
+ throw Components.Exception("only first request is allowed to invoke |finishPreparation|");
}
this._startDetection();
},
cancelLogin: function cancelLogin(eventId) {
debug('login canceled by user for request "' + eventId + '"');
// Captive portal login procedure is canceled by user
- if (this._runningRequest && this._runningRequest.hasOwnProperty('eventId')) {
+ if (this._runningRequest && this._runningRequest.hasOwnProperty("eventId")) {
let id = this._runningRequest.eventId;
if (eventId === id) {
this.executeCallback(false);
}
}
},
_applyDetection: function _applyDetection() {
- debug('enter applyDetection(' + this._runningRequest.interfaceName + ')');
+ debug("enter applyDetection(" + this._runningRequest.interfaceName + ")");
// Execute network interface preparation
- if (this._runningRequest.hasOwnProperty('callback')) {
+ if (this._runningRequest.hasOwnProperty("callback")) {
this._runningRequest.callback.prepare();
} else {
this._startDetection();
}
},
_startDetection: function _startDetection() {
- debug('startDetection {site=' + this._canonicalSiteURL + ',content='
- + this._canonicalSiteExpectedContent + ',time=' + this._maxWaitingTime + '}');
+ debug("startDetection {site=" + this._canonicalSiteURL + ",content="
+ + this._canonicalSiteExpectedContent + ",time=" + this._maxWaitingTime + "}");
let self = this;
let urlFetcher = new URLFetcher(this._canonicalSiteURL, this._maxWaitingTime);
let mayRetry = this._mayRetry.bind(this);
urlFetcher.ontimeout = mayRetry;
urlFetcher.onerror = mayRetry;
@@ -327,73 +327,73 @@ CaptivePortalDetector.prototype = {
if (status >= 300 && status <= 399) {
// The canonical website has been redirected to an unknown location
self._startLogin();
} else {
mayRetry();
}
};
- this._runningRequest['urlFetcher'] = urlFetcher;
+ this._runningRequest["urlFetcher"] = urlFetcher;
},
_startLogin: function _startLogin() {
let id = this._allocateRequestId();
let details = {
type: kOpenCaptivePortalLoginEvent,
id,
url: this._canonicalSiteURL,
};
this._loginObserver.attach();
- this._runningRequest['eventId'] = id;
+ this._runningRequest["eventId"] = id;
this._sendEvent(kOpenCaptivePortalLoginEvent, details);
gSysMsgr.broadcastMessage(kCaptivePortalSystemMessage, {});
},
_mayRetry: function _mayRetry() {
if (this._runningRequest.retryCount++ < this._maxRetryCount) {
- debug('retry-Detection: ' + this._runningRequest.retryCount + '/' + this._maxRetryCount);
+ debug("retry-Detection: " + this._runningRequest.retryCount + "/" + this._maxRetryCount);
this._startDetection();
} else {
this.executeCallback(true);
}
},
executeCallback: function executeCallback(success) {
if (this._runningRequest) {
- debug('callback executed');
- if (this._runningRequest.hasOwnProperty('callback')) {
+ debug("callback executed");
+ if (this._runningRequest.hasOwnProperty("callback")) {
this._runningRequest.callback.complete(success);
}
// Only when the request has a event id and |success| is true
// do we need to notify the login-success event.
- if (this._runningRequest.hasOwnProperty('eventId') && success) {
+ if (this._runningRequest.hasOwnProperty("eventId") && success) {
let details = {
type: kCaptivePortalLoginSuccessEvent,
- id: this._runningRequest['eventId'],
+ id: this._runningRequest["eventId"],
};
this._sendEvent(kCaptivePortalLoginSuccessEvent, details);
}
// Continue the following request
- this._runningRequest['complete'] = true;
+ this._runningRequest["complete"] = true;
this._removeRequest(this._runningRequest.interfaceName);
}
},
_sendEvent: function _sendEvent(topic, details) {
debug('sendEvent "' + JSON.stringify(details) + '"');
Services.obs.notifyObservers(this,
topic,
JSON.stringify(details));
},
validateContent: function validateContent(content) {
- debug('received content: ' + content);
+ debug("received content: " + content);
let valid = content === this._canonicalSiteExpectedContent;
// We need a way to indicate that a check has been performed, and if we are
// still in a captive portal.
this._sendEvent(kCaptivePortalCheckComplete, !valid);
return valid;
},
_allocateRequestId: function _allocateRequestId() {
@@ -425,52 +425,52 @@ CaptivePortalDetector.prototype = {
delete this._interfaceNames[aInterfaceName];
if (this._runningRequest
&& this._runningRequest.interfaceName === aInterfaceName) {
this._loginObserver.detach();
if (!this._runningRequest.complete) {
// Abort the user login procedure
- if (this._runningRequest.hasOwnProperty('eventId')) {
+ if (this._runningRequest.hasOwnProperty("eventId")) {
let details = {
type: kAbortCaptivePortalLoginEvent,
id: this._runningRequest.eventId
};
this._sendEvent(kAbortCaptivePortalLoginEvent, details);
}
// Abort the ongoing HTTP request
- if (this._runningRequest.hasOwnProperty('urlFetcher')) {
+ if (this._runningRequest.hasOwnProperty("urlFetcher")) {
this._runningRequest.urlFetcher.abort();
}
}
- debug('remove running request');
+ debug("remove running request");
this._runningRequest = null;
// Continue next pending reqeust if the ongoing one has been aborted
this._runNextRequest();
return;
}
// Check if a pending request has been aborted
for (let i = 0; i < this._requestQueue.length; i++) {
if (this._requestQueue[i].interfaceName == aInterfaceName) {
this._requestQueue.splice(i, 1);
- debug('remove pending request #' + i + ', remaining ' + this._requestQueue.length);
+ debug("remove pending request #" + i + ", remaining " + this._requestQueue.length);
break;
}
}
},
};
var debug;
if (DEBUG) {
debug = function(s) {
- dump('-*- CaptivePortalDetector component: ' + s + '\n');
+ dump("-*- CaptivePortalDetector component: " + s + "\n");
};
} else {
debug = function(s) {};
}
this.NSGetFactory = XPCOMUtils.generateNSGetFactory([CaptivePortalDetector]);
--- a/toolkit/components/captivedetect/test/unit/head_setprefs.js
+++ b/toolkit/components/captivedetect/test/unit/head_setprefs.js
@@ -1,30 +1,30 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://testing-common/httpd.js');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://testing-common/httpd.js");
-XPCOMUtils.defineLazyServiceGetter(this, 'gCaptivePortalDetector',
- '@mozilla.org/toolkit/captive-detector;1',
- 'nsICaptivePortalDetector');
+XPCOMUtils.defineLazyServiceGetter(this, "gCaptivePortalDetector",
+ "@mozilla.org/toolkit/captive-detector;1",
+ "nsICaptivePortalDetector");
-const kCanonicalSitePath = '/canonicalSite.html';
-const kCanonicalSiteContent = 'true';
-const kPrefsCanonicalURL = 'captivedetect.canonicalURL';
-const kPrefsCanonicalContent = 'captivedetect.canonicalContent';
-const kPrefsMaxWaitingTime = 'captivedetect.maxWaitingTime';
-const kPrefsPollingTime = 'captivedetect.pollingTime';
+const kCanonicalSitePath = "/canonicalSite.html";
+const kCanonicalSiteContent = "true";
+const kPrefsCanonicalURL = "captivedetect.canonicalURL";
+const kPrefsCanonicalContent = "captivedetect.canonicalContent";
+const kPrefsMaxWaitingTime = "captivedetect.maxWaitingTime";
+const kPrefsPollingTime = "captivedetect.pollingTime";
var gServer;
var gServerURL;
function setupPrefs() {
let prefs = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.QueryInterface(Components.interfaces.nsIPrefBranch);
@@ -33,16 +33,16 @@ function setupPrefs() {
prefs.setIntPref(kPrefsMaxWaitingTime, 0);
prefs.setIntPref(kPrefsPollingTime, 1);
}
function run_captivedetect_test(xhr_handler, fakeUIResponse, testfun) {
gServer = new HttpServer();
gServer.registerPathHandler(kCanonicalSitePath, xhr_handler);
gServer.start(-1);
- gServerURL = 'http://localhost:' + gServer.identity.primaryPort;
+ gServerURL = "http://localhost:" + gServer.identity.primaryPort;
setupPrefs();
fakeUIResponse();
testfun();
}
--- a/toolkit/components/captivedetect/test/unit/test_abort.js
+++ b/toolkit/components/captivedetect/test/unit/test_abort.js
@@ -1,50 +1,50 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var server;
var step = 0;
var loginFinished = false;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
if (loginFinished) {
- response.write('true');
+ response.write("true");
} else {
- response.write('false');
+ response.write("false");
}
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- do_throw('should not receive captive-portal-login event');
+ if (topic === "captive-portal-login") {
+ do_throw("should not receive captive-portal-login event");
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
}
function test_abort() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
do_check_eq(++step, 1);
gCaptivePortalDetector.finishPreparation(kInterfaceName);
},
complete: function complete(success) {
- do_throw('should not execute |complete| callback');
+ do_throw("should not execute |complete| callback");
},
};
gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
gCaptivePortalDetector.abort(kInterfaceName);
gServer.stop(do_test_finished);
}
--- a/toolkit/components/captivedetect/test/unit/test_abort_during_user_login.js
+++ b/toolkit/components/captivedetect/test/unit/test_abort_during_user_login.js
@@ -1,65 +1,65 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var server;
var step = 0;
var loginFinished = false;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
if (loginFinished) {
- response.write('true');
+ response.write("true");
} else {
- response.write('false');
+ response.write("false");
}
}
function fakeUIResponse() {
let requestId;
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
loginFinished = true;
do_check_eq(++step, 2);
requestId = JSON.parse(data).id;
gCaptivePortalDetector.abort(kInterfaceName);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-abort') {
+ if (topic === "captive-portal-login-abort") {
do_check_eq(++step, 3);
do_check_eq(JSON.parse(data).id, requestId);
gServer.stop(do_test_finished);
}
- }, 'captive-portal-login-abort', false);
+ }, "captive-portal-login-abort", false);
}
function test_abort() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
do_check_eq(++step, 1);
gCaptivePortalDetector.finishPreparation(kInterfaceName);
},
complete: function complete(success) {
- do_throw('should not execute |complete| callback');
+ do_throw("should not execute |complete| callback");
},
};
gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
}
function run_test() {
run_captivedetect_test(xhr_handler, fakeUIResponse, test_abort);
--- a/toolkit/components/captivedetect/test/unit/test_abort_ongoing_request.js
+++ b/toolkit/components/captivedetect/test/unit/test_abort_ongoing_request.js
@@ -1,56 +1,56 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
-const kOtherInterfaceName = 'ril';
+const kInterfaceName = "wifi";
+const kOtherInterfaceName = "ril";
var server;
var step = 0;
var loginFinished = false;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
if (loginFinished) {
- response.write('true');
+ response.write("true");
} else {
- response.write('false');
+ response.write("false");
}
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
loginFinished = true;
do_check_eq(++step, 3);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
}
function test_multiple_requests_abort() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
do_check_eq(++step, 1);
gCaptivePortalDetector.finishPreparation(kInterfaceName);
},
complete: function complete(success) {
- do_throw('should not execute |complete| callback for ' + kInterfaceName);
+ do_throw("should not execute |complete| callback for " + kInterfaceName);
},
};
let otherCallback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
do_check_eq(++step, 2);
gCaptivePortalDetector.finishPreparation(kOtherInterfaceName);
--- a/toolkit/components/captivedetect/test/unit/test_abort_pending_request.js
+++ b/toolkit/components/captivedetect/test/unit/test_abort_pending_request.js
@@ -1,43 +1,43 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
-const kOtherInterfaceName = 'ril';
+const kInterfaceName = "wifi";
+const kOtherInterfaceName = "ril";
var server;
var step = 0;
var loginFinished = false;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
if (loginFinished) {
- response.write('true');
+ response.write("true");
} else {
- response.write('false');
+ response.write("false");
}
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
loginFinished = true;
do_check_eq(++step, 2);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
}
function test_abort() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
@@ -49,20 +49,20 @@ function test_abort() {
do_check_true(success);
gServer.stop(do_test_finished);
},
};
let otherCallback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
- do_throw('should not execute |prepare| callback for ' + kOtherInterfaceName);
+ do_throw("should not execute |prepare| callback for " + kOtherInterfaceName);
},
complete: function complete(success) {
- do_throw('should not execute |complete| callback for ' + kInterfaceName);
+ do_throw("should not execute |complete| callback for " + kInterfaceName);
}
};
gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
gCaptivePortalDetector.checkCaptivePortal(kOtherInterfaceName, otherCallback);
gCaptivePortalDetector.abort(kOtherInterfaceName);
}
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_found.js
+++ b/toolkit/components/captivedetect/test/unit/test_captive_portal_found.js
@@ -1,49 +1,49 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var server;
var step = 0;
var loginFinished = false;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
if (loginFinished) {
- response.write('true');
+ response.write("true");
} else {
- response.write('false');
+ response.write("false");
}
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
loginFinished = true;
do_check_eq(++step, 2);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-success') {
+ if (topic === "captive-portal-login-success") {
do_check_eq(++step, 4);
gServer.stop(do_test_finished);
}
- }, 'captive-portal-login-success', false);
+ }, "captive-portal-login-success", false);
}
function test_portal_found() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js
+++ b/toolkit/components/captivedetect/test/unit/test_captive_portal_found_303.js
@@ -1,55 +1,55 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var step = 0;
var loginFinished = false;
var gRedirectServer;
var gRedirectServerURL;
function xhr_handler(metadata, response) {
if (loginFinished) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- response.write('true');
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
+ response.write("true");
} else {
response.setStatusLine(metadata.httpVersion, 303, "See Other");
response.setHeader("Location", gRedirectServerURL, false);
response.setHeader("Content-Type", "text/html", false);
}
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
loginFinished = true;
do_check_eq(++step, 2);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-success') {
+ if (topic === "captive-portal-login-success") {
do_check_eq(++step, 4);
gServer.stop(function() {
gRedirectServer.stop(do_test_finished);
});
}
- }, 'captive-portal-login-success', false);
+ }, "captive-portal-login-success", false);
}
function test_portal_found() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
@@ -63,12 +63,12 @@ function test_portal_found() {
};
gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
}
function run_test() {
gRedirectServer = new HttpServer();
gRedirectServer.start(-1);
- gRedirectServerURL = 'http://localhost:' + gRedirectServer.identity.primaryPort;
+ gRedirectServerURL = "http://localhost:" + gRedirectServer.identity.primaryPort;
run_captivedetect_test(xhr_handler, fakeUIResponse, test_portal_found);
}
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found.js
+++ b/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found.js
@@ -1,51 +1,51 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var server;
var step = 0;
var attempt = 0;
function xhr_handler(metadata, response) {
- dump('HTTP activity\n');
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- response.write('true');
+ dump("HTTP activity\n");
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
+ response.write("true");
attempt++;
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic == 'captive-portal-login') {
- do_throw('should not receive captive-portal-login event');
+ if (topic == "captive-portal-login") {
+ do_throw("should not receive captive-portal-login event");
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
}
function test_portal_not_found() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
do_check_eq(++step, 1);
gCaptivePortalDetector.finishPreparation(kInterfaceName);
},
complete: function complete(success) {
do_check_eq(++step, 2);
do_check_true(success);
do_check_eq(attempt, 1);
- gServer.stop(function() { dump('server stop\n'); do_test_finished(); });
+ gServer.stop(function() { dump("server stop\n"); do_test_finished(); });
}
};
gCaptivePortalDetector.checkCaptivePortal(kInterfaceName, callback);
}
function run_test() {
run_captivedetect_test(xhr_handler, fakeUIResponse, test_portal_not_found);
--- a/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found_404.js
+++ b/toolkit/components/captivedetect/test/unit/test_captive_portal_not_found_404.js
@@ -1,32 +1,32 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var server;
var step = 0;
var loginFinished = false;
var attempt = 0;
function xhr_handler(metadata, response) {
response.setStatusLine(metadata.httpVersion, 404, "Page not Found");
attempt++;
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- do_throw('should not receive captive-portal-login event');
+ if (topic === "captive-portal-login") {
+ do_throw("should not receive captive-portal-login event");
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
}
function test_portal_not_found() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
--- a/toolkit/components/captivedetect/test/unit/test_multiple_requests.js
+++ b/toolkit/components/captivedetect/test/unit/test_multiple_requests.js
@@ -1,54 +1,54 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
-const kOtherInterfaceName = 'ril';
+const kInterfaceName = "wifi";
+const kOtherInterfaceName = "ril";
var server;
var step = 0;
var loginFinished = false;
var loginSuccessCount = 0;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
if (loginFinished) {
- response.write('true');
+ response.write("true");
} else {
- response.write('false');
+ response.write("false");
}
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
loginFinished = true;
do_check_eq(++step, 2);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login-success') {
+ if (topic === "captive-portal-login-success") {
loginSuccessCount++;
if (loginSuccessCount > 1) {
throw "We should only receive 'captive-portal-login-success' once";
}
do_check_eq(++step, 4);
}
- }, 'captive-portal-login-success', false);
+ }, "captive-portal-login-success", false);
}
function test_multiple_requests() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
--- a/toolkit/components/captivedetect/test/unit/test_user_cancel.js
+++ b/toolkit/components/captivedetect/test/unit/test_user_cancel.js
@@ -1,38 +1,38 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
-const kInterfaceName = 'wifi';
+const kInterfaceName = "wifi";
var server;
var step = 0;
function xhr_handler(metadata, response) {
- response.setStatusLine(metadata.httpVersion, 200, 'OK');
- response.setHeader('Cache-Control', 'no-cache', false);
- response.setHeader('Content-Type', 'text/plain', false);
- response.write('false');
+ response.setStatusLine(metadata.httpVersion, 200, "OK");
+ response.setHeader("Cache-Control", "no-cache", false);
+ response.setHeader("Content-Type", "text/plain", false);
+ response.write("false");
}
function fakeUIResponse() {
Services.obs.addObserver(function observe(subject, topic, data) {
- if (topic === 'captive-portal-login') {
- let xhr = Cc['@mozilla.org/xmlextras/xmlhttprequest;1']
+ if (topic === "captive-portal-login") {
+ let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
- xhr.open('GET', gServerURL + kCanonicalSitePath, true);
+ xhr.open("GET", gServerURL + kCanonicalSitePath, true);
xhr.send();
do_check_eq(++step, 2);
let details = JSON.parse(data);
gCaptivePortalDetector.cancelLogin(details.id);
}
- }, 'captive-portal-login', false);
+ }, "captive-portal-login", false);
}
function test_cancel() {
do_test_pending();
let callback = {
QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
prepare: function prepare() {
--- a/toolkit/components/contentprefs/ContentPrefInstance.jsm
+++ b/toolkit/components/contentprefs/ContentPrefInstance.jsm
@@ -1,18 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
const Cc = Components.classes;
const Ci = Components.interfaces;
-this.EXPORTED_SYMBOLS = ['ContentPrefInstance'];
+this.EXPORTED_SYMBOLS = ["ContentPrefInstance"];
// This is a wrapper for nsIContentPrefService that alleviates the need to pass
// an nsILoadContext argument to every method. Pass the context to the constructor
// instead and continue on your way in blissful ignorance.
this.ContentPrefInstance = function ContentPrefInstance(aContext) {
this._contentPrefSvc = Cc["@mozilla.org/content-pref/service;1"].
getService(Ci.nsIContentPrefService);
--- a/toolkit/components/contentprefs/nsContentPrefService.js
+++ b/toolkit/components/contentprefs/nsContentPrefService.js
@@ -1157,17 +1157,17 @@ ContentPrefService.prototype = {
* in _createDB) or because some other code created the database file without
* applying the schema. In any case, recover by simply reapplying the schema.
*/
if (aOldVersion == 0) {
this._dbCreateSchema(aDBConnection);
} else {
for (let i = aOldVersion; i < aNewVersion; i++) {
let migrationName = "_dbMigrate" + i + "To" + (i + 1);
- if (typeof this[migrationName] != 'function') {
+ if (typeof this[migrationName] != "function") {
throw ("no migrator function from version " + aOldVersion + " to version " + aNewVersion);
}
this[migrationName](aDBConnection);
}
}
aDBConnection.schemaVersion = aNewVersion;
aDBConnection.commitTransaction();
} catch (ex) {
--- a/toolkit/components/contentprefs/tests/unit/head_contentPrefs.js
+++ b/toolkit/components/contentprefs/tests/unit/head_contentPrefs.js
@@ -4,18 +4,18 @@
// Inspired by the Places infrastructure in head_bookmarks.js
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cr = Components.results;
var Cu = Components.utils;
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://gre/modules/ContentPrefInstance.jsm');
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/ContentPrefInstance.jsm");
const CONTENT_PREFS_DB_FILENAME = "content-prefs.sqlite";
const CONTENT_PREFS_BACKUP_DB_FILENAME = "content-prefs.sqlite.corrupt";
var ContentPrefTest = {
// Convenience Getters
__dirSvc: null,
--- a/toolkit/components/contentprefs/tests/unit_cps2/test_observers.js
+++ b/toolkit/components/contentprefs/tests/unit_cps2/test_observers.js
@@ -4,18 +4,18 @@
let global = this;
function run_test() {
var allTests = [];
for (var i = 0; i < tests.length; i++) {
// Generate two wrappers of each test function that invoke the original test with an
// appropriate privacy context.
- var pub = eval('var f = function* ' + tests[i].name + '() { yield tests[' + i + ']({ usePrivateBrowsing: false }); }; f');
- var priv = eval('var f = function* ' + tests[i].name + '_private() { yield tests[' + i + ']({ usePrivateBrowsing: true }); }; f');
+ var pub = eval("var f = function* " + tests[i].name + "() { yield tests[" + i + "]({ usePrivateBrowsing: false }); }; f");
+ var priv = eval("var f = function* " + tests[i].name + "_private() { yield tests[" + i + "]({ usePrivateBrowsing: true }); }; f");
allTests.push(pub);
allTests.push(priv);
}
allTests = allTests.concat(specialTests);
runAsyncTests(allTests);
}
var tests = [
--- a/toolkit/components/ctypes/tests/unit/test_jsctypes.js
+++ b/toolkit/components/ctypes/tests/unit/test_jsctypes.js
@@ -243,18 +243,18 @@ function run_abstract_class_tests() {
do_check_throws(function() { ctypes.CType.prototype.name; }, TypeError);
do_check_throws(function() { ctypes.CType.prototype.size; }, TypeError);
do_check_throws(function() { ctypes.CType.prototype.ptr; }, TypeError);
do_check_throws(function() { ctypes.CType.prototype.array(); }, TypeError);
// toString and toSource are called by the web console during inspection,
// so we don't want them to throw.
- do_check_eq(typeof ctypes.CType.prototype.toString(), 'string');
- do_check_eq(typeof ctypes.CType.prototype.toSource(), 'string');
+ do_check_eq(typeof ctypes.CType.prototype.toString(), "string");
+ do_check_eq(typeof ctypes.CType.prototype.toSource(), "string");
// Test that ctypes.CData is an abstract constructor that throws.
do_check_throws(function() { ctypes.CData(); }, TypeError);
do_check_throws(function() { new ctypes.CData() }, TypeError);
do_check_true(ctypes.CData.__proto__ === ctypes.CType.prototype);
do_check_true(ctypes.CData instanceof ctypes.CType);
@@ -272,18 +272,18 @@ function run_abstract_class_tests() {
// Check that the shared properties and functions on ctypes.CData.prototype throw.
do_check_throws(function() { ctypes.CData.prototype.value; }, TypeError);
do_check_throws(function() { ctypes.CData.prototype.value = null; }, TypeError);
do_check_throws(function() { ctypes.CData.prototype.address(); }, TypeError);
do_check_throws(function() { ctypes.CData.prototype.readString(); }, TypeError);
// toString and toSource are called by the web console during inspection,
// so we don't want them to throw.
- do_check_eq(ctypes.CData.prototype.toString(), '[CData proto object]');
- do_check_eq(ctypes.CData.prototype.toSource(), '[CData proto object]');
+ do_check_eq(ctypes.CData.prototype.toString(), "[CData proto object]");
+ do_check_eq(ctypes.CData.prototype.toSource(), "[CData proto object]");
}
function run_Int64_tests() {
do_check_throws(function() { ctypes.Int64(); }, TypeError);
do_check_true(ctypes.Int64.hasOwnProperty("prototype"));
do_check_true(ctypes.Int64.prototype.hasOwnProperty("constructor"));
do_check_true(ctypes.Int64.prototype.constructor === ctypes.Int64);
@@ -728,18 +728,18 @@ function run_basic_class_tests(t) {
// Check that the shared properties and functions on 't.prototype' throw.
do_check_throws(function() { t.prototype.value; }, TypeError);
do_check_throws(function() { t.prototype.value = null; }, TypeError);
do_check_throws(function() { t.prototype.address(); }, TypeError);
do_check_throws(function() { t.prototype.readString(); }, TypeError);
// toString and toSource are called by the web console during inspection,
// so we don't want them to throw.
- do_check_eq(t.prototype.toString(), '[CData proto object]');
- do_check_eq(t.prototype.toSource(), '[CData proto object]');
+ do_check_eq(t.prototype.toString(), "[CData proto object]");
+ do_check_eq(t.prototype.toSource(), "[CData proto object]");
// Test that an instance 'd' of 't' is a CData.
let d = t();
do_check_true(d.__proto__ === t.prototype);
do_check_true(d instanceof t);
do_check_true(d.constructor === t);
}
@@ -2741,21 +2741,21 @@ function run_cpp_class_tests(library) {
let OS = get_os();
let ctor_symbol;
let add_symbol;
let abi;
if (OS == "WINNT") {
// for compatibility for Win32 vs Win64
abi = ctypes.thiscall_abi;
if (ctypes.size_t.size == 8) {
- ctor_symbol = '??0TestClass@@QEAA@H@Z';
- add_symbol = '?Add@TestClass@@QEAAHH@Z';
+ ctor_symbol = "??0TestClass@@QEAA@H@Z";
+ add_symbol = "?Add@TestClass@@QEAAHH@Z";
} else {
- ctor_symbol = '??0TestClass@@QAE@H@Z';
- add_symbol = '?Add@TestClass@@QAEHH@Z';
+ ctor_symbol = "??0TestClass@@QAE@H@Z";
+ add_symbol = "?Add@TestClass@@QAEHH@Z";
}
} else {
abi = ctypes.default_abi;
ctor_symbol = "_ZN9TestClassC1Ei";
add_symbol = "_ZN9TestClass3AddEi";
}
let test_class_ctor = library.declare(ctor_symbol, abi, ctypes.void_t,
--- a/toolkit/components/downloads/test/unit/test_app_rep.js
+++ b/toolkit/components/downloads/test/unit/test_app_rep.js
@@ -1,15 +1,15 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-Cu.import('resource://gre/modules/NetUtil.jsm');
+Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const gAppRep = Cc["@mozilla.org/downloads/application-reputation-service;1"].
getService(Ci.nsIApplicationReputationService);
var gHttpServ = null;
var gTables = {};
var ALLOW_LIST = 0;
--- a/toolkit/components/exthelper/extApplication.js
+++ b/toolkit/components/exthelper/extApplication.js
@@ -692,17 +692,17 @@ extApplication.prototype = {
_quitWithFlags: function app__quitWithFlags(aFlags) {
let cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
.createInstance(Components.interfaces.nsISupportsPRBool);
let quitType = aFlags & Components.interfaces.nsIAppStartup.eRestart ? "restart" : null;
this._obs.notifyObservers(cancelQuit, "quit-application-requested", quitType);
if (cancelQuit.data)
return false; // somebody canceled our quit request
- let appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1']
+ let appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"]
.getService(Components.interfaces.nsIAppStartup);
appStartup.quit(aFlags);
return true;
},
quit: function app_quit() {
return this._quitWithFlags(Components.interfaces.nsIAppStartup.eAttemptQuit);
},
--- a/toolkit/components/feeds/FeedProcessor.js
+++ b/toolkit/components/feeds/FeedProcessor.js
@@ -789,17 +789,17 @@ function rssAuthor(s, author) {
author.email = match2;
author.name = match1;
} else {
// put it back together
author.name = match1 + " (" + match2 + ")";
}
} else {
author.name = chars;
- if (chars.indexOf('@'))
+ if (chars.indexOf("@"))
author.email = chars;
}
return author;
}
//
// skipHours and skipDays map to arrays, so we need to change the
// string to an nsISupports in order to stick it in there.
--- a/toolkit/components/feeds/test/head.js
+++ b/toolkit/components/feeds/test/head.js
@@ -17,30 +17,30 @@ function readTestData(testFile) {
istream.init(testFile, 0x01, parseInt("0444", 8), 0);
istream.QueryInterface(Ci.nsILineInputStream);
var hasmore = false;
do {
var line = {};
hasmore = istream.readLine(line);
- if (line.value.indexOf('Description:') > -1) {
- testcase.desc = line.value.substring(line.value.indexOf(':') + 1).trim();
+ if (line.value.indexOf("Description:") > -1) {
+ testcase.desc = line.value.substring(line.value.indexOf(":") + 1).trim();
}
- if (line.value.indexOf('Expect:') > -1) {
- testcase.expect = line.value.substring(line.value.indexOf(':') + 1).trim();
+ if (line.value.indexOf("Expect:") > -1) {
+ testcase.expect = line.value.substring(line.value.indexOf(":") + 1).trim();
}
- if (line.value.indexOf('Base:') > -1) {
- testcase.base = NetUtil.newURI(line.value.substring(line.value.indexOf(':') + 1).trim());
+ if (line.value.indexOf("Base:") > -1) {
+ testcase.base = NetUtil.newURI(line.value.substring(line.value.indexOf(":") + 1).trim());
}
if (testcase.expect && testcase.desc) {
- testcase.path = 'xml/' + testFile.parent.leafName + '/' + testFile.leafName;
+ testcase.path = "xml/" + testFile.parent.leafName + "/" + testFile.leafName;
testcase.file = testFile;
break;
}
} while (hasmore);
} catch (e) {
Assert.ok(false, "FAILED! Error reading testFile case in file " + testFile.leafName + " ---- " + e);
--- a/toolkit/components/feeds/test/test_xml.js
+++ b/toolkit/components/feeds/test/test_xml.js
@@ -51,17 +51,17 @@ FeedListener.prototype = {
}
}
function createTest(data) {
return function() {
var uri;
if (data.base == null) {
- uri = NetUtil.newURI('http://example.org/' + data.path);
+ uri = NetUtil.newURI("http://example.org/" + data.path);
} else {
uri = data.base;
}
do_print("Testing " + data.file.leafName);
var parser = Cc["@mozilla.org/feed-processor;1"].createInstance(Ci.nsIFeedProcessor);
var stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
--- a/toolkit/components/filepicker/content/filepicker.js
+++ b/toolkit/components/filepicker/content/filepicker.js
@@ -729,17 +729,17 @@ function processPath(path) {
while (1) {
var nextQuote;
// Look for an unescaped quote
var quoteSearchStart = curFileStart + 1;
do {
nextQuote = path.indexOf('"', quoteSearchStart);
quoteSearchStart = nextQuote + 1;
- } while (nextQuote != -1 && path[nextQuote - 1] == '\\');
+ } while (nextQuote != -1 && path[nextQuote - 1] == "\\");
if (nextQuote == -1) {
// we have a filename with no trailing quote.
// just assume that the filename ends at the end of the string.
if (!processPathEntry(path.substring(curFileStart), fileArray))
return false;
break;
@@ -776,27 +776,27 @@ function processPathEntry(path, fileArra
file = sfile.clone().QueryInterface(nsILocalFile);
} catch (e) {
dump("Couldn't clone\n" + e);
return false;
}
var tilde_file = file.clone();
tilde_file.append("~");
- if (path[0] == '~' && // Expand ~ to $HOME, except:
+ if (path[0] == "~" && // Expand ~ to $HOME, except:
!(path == "~" && tilde_file.exists()) && // If ~ was entered and such a file exists, don't expand
(path.length == 1 || path[1] == "/")) // We don't want to expand ~file to ${HOME}file
filePath = homeDir.path + path.substring(1);
else
filePath = path;
// Unescape quotes
filePath = filePath.replace(/\\\"/g, "\"");
- if (filePath[0] == '/') /* an absolute path was entered */
+ if (filePath[0] == "/") /* an absolute path was entered */
file.initWithPath(filePath);
else if ((filePath.indexOf("/../") > 0) ||
(filePath.substr(-3) == "/..") ||
(filePath.substr(0, 3) == "../") ||
(filePath == "..")) {
/* appendRelativePath doesn't allow .. */
try {
file.initWithPath(file.path + "/" + filePath);
--- a/toolkit/components/filewatcher/tests/xpcshell/head.js
+++ b/toolkit/components/filewatcher/tests/xpcshell/head.js
@@ -6,17 +6,17 @@
var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
Cu.import("resource://gre/modules/osfile.jsm", this);
Cu.import("resource://gre/modules/Promise.jsm", this);
function makeWatcher() {
let watcher =
- Cc['@mozilla.org/toolkit/filewatcher/native-file-watcher;1']
+ Cc["@mozilla.org/toolkit/filewatcher/native-file-watcher;1"]
.getService(Ci.nsINativeFileWatcherService);
return watcher;
}
function promiseAddPath(watcher, resource, onChange = null, onError = null) {
return new Promise(resolve =>
watcher.addPath(resource, onChange, onError, resolve)
);
--- a/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js
+++ b/toolkit/components/filewatcher/tests/xpcshell/test_arguments.js
@@ -13,17 +13,17 @@ function run_test() {
}
/**
* Test for addPath usage with null arguments.
*/
add_task(function* test_null_args_addPath() {
let watcher = makeWatcher();
- let testPath = 'someInvalidPath';
+ let testPath = "someInvalidPath";
// Define a dummy callback function. In this test no callback is
// expected to be called.
let dummyFunc = function(changed) {
do_throw("Not expected in this test.");
};
// Check for error when passing a null first argument
@@ -46,17 +46,17 @@ add_task(function* test_null_args_addPat
});
/**
* Test for removePath usage with null arguments.
*/
add_task(function* test_null_args_removePath() {
let watcher = makeWatcher();
- let testPath = 'someInvalidPath';
+ let testPath = "someInvalidPath";
// Define a dummy callback function. In this test no callback is
// expected to be called.
let dummyFunc = function(changed) {
do_throw("Not expected in this test.");
};
// Check for error when passing a null first argument
--- a/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js
+++ b/toolkit/components/filewatcher/tests/xpcshell/test_no_error_callback.js
@@ -14,17 +14,17 @@ function run_test() {
/**
* Test the component behaves correctly when no error callback is
* provided and an error occurs.
*/
add_task(function* test_error_with_no_error_callback() {
let watcher = makeWatcher();
- let testPath = 'someInvalidPath';
+ let testPath = "someInvalidPath";
// Define a dummy callback function. In this test no callback is
// expected to be called.
let dummyFunc = function(changed) {
do_throw("Not expected in this test.");
};
// We don't pass an error callback and try to watch an invalid
--- a/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js
+++ b/toolkit/components/filewatcher/tests/xpcshell/test_watch_file_deletion_single.js
@@ -33,17 +33,17 @@ add_task(function* test_watch_single_pat
let tmpFilePath = OS.Path.join(watchedDir, tempFileName);
yield OS.File.writeAtomic(tmpFilePath, "some data");
// Add the profile directory to the watch list and wait for the file watcher
// to start watching it.
yield promiseAddPath(watcher, watchedDir, deferred.resolve, deferred.reject);
// Remove the file we created (should trigger a notification).
- do_print('Removing ' + tmpFilePath);
+ do_print("Removing " + tmpFilePath);
yield OS.File.remove(tmpFilePath);
// Wait until the watcher informs us that the file was deleted.
let changed = yield deferred.promise;
do_check_eq(changed, tmpFilePath);
// Remove the watch and free the associated memory (we need to
// reuse 'deferred.resolve' and 'deferred.reject' to unregister).
--- a/toolkit/components/gfx/SanityTest.js
+++ b/toolkit/components/gfx/SanityTest.js
@@ -2,17 +2,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { utils: Cu, interfaces: Ci, classes: Cc, results: Cr } = Components;
Cu.import("resource://gre/modules/Services.jsm");
-Cu.import('resource://gre/modules/Preferences.jsm');
+Cu.import("resource://gre/modules/Preferences.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
const FRAME_SCRIPT_URL = "chrome://gfxsanity/content/gfxFrameScript.js";
const PAGE_WIDTH = 92;
const PAGE_HEIGHT = 166;
const DRIVER_PREF = "sanity-test.driver-version";
@@ -68,25 +68,25 @@ function reportResult(val) {
function reportTestReason(val) {
let histogram = Services.telemetry.getHistogramById("GRAPHICS_SANITY_TEST_REASON");
histogram.add(val);
}
function annotateCrashReport(value) {
try {
// "1" if we're annotating the crash report, "" to remove the annotation.
- var crashReporter = Cc['@mozilla.org/toolkit/crash-reporter;1'].
+ var crashReporter = Cc["@mozilla.org/toolkit/crash-reporter;1"].
getService(Ci.nsICrashReporter);
crashReporter.annotateCrashReport("GraphicsSanityTest", value ? "1" : "");
} catch (e) {
}
}
function setTimeout(aMs, aCallback) {
- var timer = Cc['@mozilla.org/timer;1'].
+ var timer = Cc["@mozilla.org/timer;1"].
createInstance(Ci.nsITimer);
timer.initWithCallback(aCallback, aMs, Ci.nsITimer.TYPE_ONE_SHOT);
}
function takeWindowSnapshot(win, ctx) {
// TODO: drawWindow reads back from the gpu's backbuffer, which won't catch issues with presenting
// the front buffer via the window manager. Ideally we'd use an OS level API for reading back
// from the desktop itself to get a more accurate test.
--- a/toolkit/components/gfx/content/gfxFrameScript.js
+++ b/toolkit/components/gfx/content/gfxFrameScript.js
@@ -16,17 +16,17 @@ const gfxFrameScript = {
Ci.nsIWebNavigation.LOAD_FLAGS_NONE,
null, null, null);
},
handleEvent(aEvent) {
switch (aEvent.type) {
case "MozAfterPaint":
- sendAsyncMessage('gfxSanity:ContentLoaded');
+ sendAsyncMessage("gfxSanity:ContentLoaded");
removeEventListener("MozAfterPaint", this);
break;
}
},
isSanityTest(aUri) {
if (!aUri) {
return false;
@@ -41,17 +41,17 @@ const gfxFrameScript = {
this.isSanityTest(req.name)) {
webProgress.removeProgressListener(this);
// If no paint is pending, then the test already painted
if (this.domUtils.isMozAfterPaintPending) {
addEventListener("MozAfterPaint", this);
} else {
- sendAsyncMessage('gfxSanity:ContentLoaded');
+ sendAsyncMessage("gfxSanity:ContentLoaded");
}
}
},
// Needed to support web progress listener
QueryInterface: XPCOMUtils.generateQI([
Ci.nsIWebProgressListener,
Ci.nsISupportsWeakReference,
--- a/toolkit/components/jsdownloads/test/unit/test_PrivateTemp.js
+++ b/toolkit/components/jsdownloads/test/unit/test_PrivateTemp.js
@@ -11,14 +11,14 @@
*/
add_task(function* test_private_temp() {
let download = yield promiseStartExternalHelperAppServiceDownload(
httpUrl("empty.txt"));
yield promiseDownloadStopped(download);
- var targetFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
+ var targetFile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
targetFile.initWithPath(download.target.path);
// 488 is the decimal value of 0o700.
equal(targetFile.parent.permissions, 448);
});
--- a/toolkit/components/microformats/microformat-shiv.js
+++ b/toolkit/components/microformats/microformat-shiv.js
@@ -5,64 +5,64 @@
Copyright (c) 2016 Glenn Jones
Licensed MIT
*/
var Microformats; // jshint ignore:line
(function(root, factory) {
- if (typeof define === 'function' && define.amd) {
+ if (typeof define === "function" && define.amd) {
define([], factory);
- } else if (typeof exports === 'object') {
+ } else if (typeof exports === "object") {
module.exports = factory();
} else {
root.Microformats = factory();
}
}(this, function() {
var modules = {};
- modules.version = '1.4.0';
- modules.livingStandard = '2015-09-25T12:26:04Z';
+ modules.version = "1.4.0";
+ modules.livingStandard = "2015-09-25T12:26:04Z";
/**
* constructor
*
*/
modules.Parser = function() {
- this.rootPrefix = 'h-';
- this.propertyPrefixes = ['p-', 'dt-', 'u-', 'e-'];
- this.excludeTags = ['br', 'hr'];
+ this.rootPrefix = "h-";
+ this.propertyPrefixes = ["p-", "dt-", "u-", "e-"];
+ this.excludeTags = ["br", "hr"];
};
// create objects incase the v1 map modules don't load
modules.maps = (modules.maps) ? modules.maps : {};
modules.rels = (modules.rels) ? modules.rels : {};
modules.Parser.prototype = {
init() {
this.rootNode = null;
this.document = null;
this.options = {
- 'baseUrl': '',
- 'filters': [],
- 'textFormat': 'whitespacetrimmed',
- 'dateFormat': 'auto', // html5 for testing
- 'overlappingVersions': false,
- 'impliedPropertiesByVersion': true,
- 'parseLatLonGeo': false
+ "baseUrl": "",
+ "filters": [],
+ "textFormat": "whitespacetrimmed",
+ "dateFormat": "auto", // html5 for testing
+ "overlappingVersions": false,
+ "impliedPropertiesByVersion": true,
+ "parseLatLonGeo": false
};
this.rootID = 0;
this.errors = [];
- this.noContentErr = 'No options.node or options.html was provided and no document object could be found.';
+ this.noContentErr = "No options.node or options.html was provided and no document object could be found.";
},
/**
* internal parse function
*
* @param {Object} options
* @return {Object}
@@ -102,17 +102,17 @@ var Microformats; // jshint ignore:line
this.clearUpDom(this.rootNode);
}
}
// find any rels
if (this.findRels) {
rels = this.findRels(this.rootNode);
out.rels = rels.rels;
- out['rel-urls'] = rels['rel-urls'];
+ out["rel-urls"] = rels["rel-urls"];
}
}
if (this.errors.length > 0) {
return this.formatError();
}
return out;
@@ -152,26 +152,26 @@ var Microformats; // jshint ignore:line
i;
this.init();
options = (options) ? options : {};
this.getDOMContext( options );
// if we do not have any context create error
if (!this.rootNode || !this.document) {
- return {'errors': [this.noContentErr]};
+ return {"errors": [this.noContentErr]};
}
items = this.findRootNodes( this.rootNode, true );
i = items.length;
while (i--) {
- classItems = modules.domUtils.getAttributeList(items[i], 'class');
+ classItems = modules.domUtils.getAttributeList(items[i], "class");
x = classItems.length;
while (x--) {
// find v2 names
- if (modules.utils.startWith( classItems[x], 'h-' )) {
+ if (modules.utils.startWith( classItems[x], "h-" )) {
this.appendCount(classItems[x], 1, out);
}
// find v1 names
for (var key in modules.maps) {
// dont double count if v1 and v2 roots are present
if (modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) {
this.appendCount(key, 1, out);
}
@@ -275,17 +275,17 @@ var Microformats; // jshint ignore:line
* @param {Int} recursive
* @return {Object}
*/
getParentTreeWalk(node, options, recursive) {
options = (options) ? options : {};
// recursive calls
if (recursive === undefined) {
- if (node.parentNode && node.nodeName !== 'HTML') {
+ if (node.parentNode && node.nodeName !== "HTML") {
return this.getParentTreeWalk(node.parentNode, options, true);
}
return this.formatEmpty();
}
if (node !== null && node !== undefined && node.parentNode) {
if (this.isMicroformat( node, options )) {
// if we have a match return microformat
options.node = node;
@@ -326,19 +326,19 @@ var Microformats; // jshint ignore:line
this.options.baseUrl = this.document.location.href;
}
} catch (e) {
// there is no alt action
}
// find base tag to set baseUrl
- baseTag = modules.domUtils.querySelector(this.document, 'base');
+ baseTag = modules.domUtils.querySelector(this.document, "base");
if (baseTag) {
- href = modules.domUtils.getAttribute(baseTag, 'href');
+ href = modules.domUtils.getAttribute(baseTag, "href");
if (href) {
this.options.baseUrl = href;
}
}
// get path to rootNode
// then clone document
// then reset the rootNode to its cloned version in a new document
@@ -379,29 +379,29 @@ var Microformats; // jshint ignore:line
/**
* returns an empty structure
*
* @return {Object}
*/
formatEmpty() {
return {
- 'items': [],
- 'rels': {},
- 'rel-urls': {}
+ "items": [],
+ "rels": {},
+ "rel-urls": {}
};
},
// find microformats of a given type and return node structures
findFilterNodes(rootNode, filters) {
if (modules.utils.isString(filters)) {
filters = [filters];
}
- var newRootNode = modules.domUtils.createNode('div'),
+ var newRootNode = modules.domUtils.createNode("div"),
items = this.findRootNodes(rootNode, true),
i = 0,
x = 0,
y = 0;
// add v1 names
y = filters.length;
while (y--) {
@@ -412,17 +412,17 @@ var Microformats; // jshint ignore:line
}
if (items) {
i = items.length;
while (x < i) {
// append matching nodes into newRootNode
y = filters.length;
while (y--) {
- if (modules.domUtils.hasAttributeValue(items[x], 'class', filters[y])) {
+ if (modules.domUtils.hasAttributeValue(items[x], "class", filters[y])) {
var clone = modules.domUtils.clone(items[x]);
modules.domUtils.appendChild(newRootNode, clone);
break;
}
}
x++;
}
}
@@ -493,39 +493,39 @@ var Microformats; // jshint ignore:line
if (modules.maps.hasOwnProperty(key)) {
classList.push(modules.maps[key].root);
}
}
// get all elements that have a class attribute
includeRoot = (includeRoot) ? includeRoot : false;
if (includeRoot && rootNode.parentNode) {
- arr = modules.domUtils.getNodesByAttribute(rootNode.parentNode, 'class');
+ arr = modules.domUtils.getNodesByAttribute(rootNode.parentNode, "class");
} else {
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'class');
+ arr = modules.domUtils.getNodesByAttribute(rootNode, "class");
}
// loop elements that have a class attribute
x = 0;
i = arr.length;
while (x < i) {
- items = modules.domUtils.getAttributeList(arr[x], 'class');
+ items = modules.domUtils.getAttributeList(arr[x], "class");
// loop classes on an element
y = items.length;
while (y--) {
// match v1 root names
if (classList.indexOf(items[y]) > -1) {
out.push(arr[x]);
break;
}
// match v2 root name prefix
- if (modules.utils.startWith(items[y], 'h-')) {
+ if (modules.utils.startWith(items[y], "h-")) {
out.push(arr[x]);
break;
}
}
x++;
}
return out;
@@ -734,19 +734,19 @@ var Microformats; // jshint ignore:line
modules.text.parse(this.document, child, context.options.textFormat)
);
// add the microformat as an array of properties
if (!out.children) {
out.children = [];
}
- if (!context.hasRootID(child, rootID, 'child-root')) {
+ if (!context.hasRootID(child, rootID, "child-root")) {
out.children.push( rootItem );
- context.appendRootID(child, rootID, 'child-root');
+ context.appendRootID(child, rootID, "child-root");
context.rootID++;
}
x = 0;
i = rootItem.type.length;
itemRootID = context.rootID;
while (x < i) {
context.walkChildren(child, rootItem, rootItem.type, itemRootID, classes);
@@ -773,178 +773,178 @@ var Microformats; // jshint ignore:line
* gets the value of a property from a node
*
* @param {DOM Node} node
* @param {String} className
* @param {Object} uf
* @return {String || Object}
*/
getValue(node, className, uf) {
- var value = '';
-
- if (modules.utils.startWith(className, 'p-')) {
+ var value = "";
+
+ if (modules.utils.startWith(className, "p-")) {
value = this.getPValue(node, true);
}
- if (modules.utils.startWith(className, 'e-')) {
+ if (modules.utils.startWith(className, "e-")) {
value = this.getEValue(node);
}
- if (modules.utils.startWith(className, 'u-')) {
+ if (modules.utils.startWith(className, "u-")) {
value = this.getUValue(node, true);
}
- if (modules.utils.startWith(className, 'dt-')) {
+ if (modules.utils.startWith(className, "dt-")) {
value = this.getDTValue(node, className, uf, true);
}
return value;
},
/**
* gets the value of a node which contains a 'p-' property
*
* @param {DOM Node} node
* @param {Boolean} valueParse
* @return {String}
*/
getPValue(node, valueParse) {
- var out = '';
+ var out = "";
if (valueParse) {
- out = this.getValueClass(node, 'p');
+ out = this.getValueClass(node, "p");
}
if (!out && valueParse) {
out = this.getValueTitle(node);
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
+ out = modules.domUtils.getAttrValFromTagList(node, ["abbr"], "title");
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['data', 'input'], 'value');
+ out = modules.domUtils.getAttrValFromTagList(node, ["data", "input"], "value");
}
- if (node.name === 'br' || node.name === 'hr') {
- out = '';
+ if (node.name === "br" || node.name === "hr") {
+ out = "";
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['img', 'area'], 'alt');
+ out = modules.domUtils.getAttrValFromTagList(node, ["img", "area"], "alt");
}
if (!out) {
out = modules.text.parse(this.document, node, this.options.textFormat);
}
- return (out) ? out : '';
+ return (out) ? out : "";
},
/**
* gets the value of a node which contains the 'e-' property
*
* @param {DOM Node} node
* @return {Object}
*/
getEValue(node) {
- var out = {value: '', html: ''};
-
- this.expandURLs(node, 'src', this.options.baseUrl);
- this.expandURLs(node, 'href', this.options.baseUrl);
+ var out = {value: "", html: ""};
+
+ this.expandURLs(node, "src", this.options.baseUrl);
+ this.expandURLs(node, "href", this.options.baseUrl);
out.value = modules.text.parse(this.document, node, this.options.textFormat);
out.html = modules.html.parse(node);
return out;
},
/**
* gets the value of a node which contains the 'u-' property
*
* @param {DOM Node} node
* @param {Boolean} valueParse
* @return {String}
*/
getUValue(node, valueParse) {
- var out = '';
+ var out = "";
if (valueParse) {
- out = this.getValueClass(node, 'u');
+ out = this.getValueClass(node, "u");
}
if (!out && valueParse) {
out = this.getValueTitle(node);
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['a', 'area'], 'href');
+ out = modules.domUtils.getAttrValFromTagList(node, ["a", "area"], "href");
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['img', 'audio', 'video', 'source'], 'src');
+ out = modules.domUtils.getAttrValFromTagList(node, ["img", "audio", "video", "source"], "src");
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['object'], 'data');
+ out = modules.domUtils.getAttrValFromTagList(node, ["object"], "data");
}
// if we have no protocol separator, turn relative url to absolute url
- if (out && out !== '' && out.indexOf('://') === -1) {
+ if (out && out !== "" && out.indexOf("://") === -1) {
out = modules.url.resolve(out, this.options.baseUrl);
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
+ out = modules.domUtils.getAttrValFromTagList(node, ["abbr"], "title");
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['data', 'input'], 'value');
+ out = modules.domUtils.getAttrValFromTagList(node, ["data", "input"], "value");
}
if (!out) {
out = modules.text.parse(this.document, node, this.options.textFormat);
}
- return (out) ? out : '';
+ return (out) ? out : "";
},
/**
* gets the value of a node which contains the 'dt-' property
*
* @param {DOM Node} node
* @param {String} className
* @param {Object} uf
* @param {Boolean} valueParse
* @return {String}
*/
getDTValue(node, className, uf, valueParse) {
- var out = '';
+ var out = "";
if (valueParse) {
- out = this.getValueClass(node, 'dt');
+ out = this.getValueClass(node, "dt");
}
if (!out && valueParse) {
out = this.getValueTitle(node);
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['time', 'ins', 'del'], 'datetime');
+ out = modules.domUtils.getAttrValFromTagList(node, ["time", "ins", "del"], "datetime");
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
+ out = modules.domUtils.getAttrValFromTagList(node, ["abbr"], "title");
}
if (!out) {
- out = modules.domUtils.getAttrValFromTagList(node, ['data', 'input'], 'value');
+ out = modules.domUtils.getAttrValFromTagList(node, ["data", "input"], "value");
}
if (!out) {
out = modules.text.parse(this.document, node, this.options.textFormat);
}
if (out) {
if (modules.dates.isDuration(out)) {
@@ -958,54 +958,54 @@ var Microformats; // jshint ignore:line
return modules.dates.parseAmPmTime(out, this.options.dateFormat);
}
// returns a date - microformat profile
if (uf) {
uf.dates.push([className, new modules.ISODate(out).toString( this.options.dateFormat )]);
}
return new modules.ISODate(out).toString( this.options.dateFormat );
}
- return '';
+ return "";
},
/**
* appends a new rootid to a given node
*
* @param {DOM Node} node
* @param {String} id
* @param {String} propertyName
*/
appendRootID(node, id, propertyName) {
if (this.hasRootID(node, id, propertyName) === false) {
var rootids = [];
- if (modules.domUtils.hasAttribute(node, 'rootids')) {
- rootids = modules.domUtils.getAttributeList(node, 'rootids');
+ if (modules.domUtils.hasAttribute(node, "rootids")) {
+ rootids = modules.domUtils.getAttributeList(node, "rootids");
}
- rootids.push('id' + id + '-' + propertyName);
- modules.domUtils.setAttribute(node, 'rootids', rootids.join(' '));
+ rootids.push("id" + id + "-" + propertyName);
+ modules.domUtils.setAttribute(node, "rootids", rootids.join(" "));
}
},
/**
* does a given node already have a rootid
*
* @param {DOM Node} node
* @param {String} id
* @param {String} propertyName
* @return {Boolean}
*/
hasRootID(node, id, propertyName) {
var rootids = [];
- if (!modules.domUtils.hasAttribute(node, 'rootids')) {
+ if (!modules.domUtils.hasAttribute(node, "rootids")) {
return false;
}
- rootids = modules.domUtils.getAttributeList(node, 'rootids');
- return (rootids.indexOf('id' + id + '-' + propertyName) > -1);
+ rootids = modules.domUtils.getAttributeList(node, "rootids");
+ return (rootids.indexOf("id" + id + "-" + propertyName) > -1);
},
/**
* gets the text of any child nodes with a class value
*
* @param {DOM Node} node
@@ -1022,42 +1022,42 @@ var Microformats; // jshint ignore:line
children = modules.domUtils.getChildren( node );
x = 0;
i = children.length;
while (x < i) {
child = children[x];
var value = null;
- if (modules.domUtils.hasAttributeValue(child, 'class', 'value')) {
+ if (modules.domUtils.hasAttributeValue(child, "class", "value")) {
switch (propertyType) {
- case 'p':
+ case "p":
value = context.getPValue(child, false);
break;
- case 'u':
+ case "u":
value = context.getUValue(child, false);
break;
- case 'dt':
- value = context.getDTValue(child, '', null, false);
+ case "dt":
+ value = context.getDTValue(child, "", null, false);
break;
}
if (value) {
out.push(modules.utils.trim(value));
}
}
x++;
}
if (out.length > 0) {
- if (propertyType === 'p') {
- return modules.text.parseText( this.document, out.join(' '), this.options.textFormat);
+ if (propertyType === "p") {
+ return modules.text.parseText( this.document, out.join(" "), this.options.textFormat);
}
- if (propertyType === 'u') {
- return out.join('');
+ if (propertyType === "u") {
+ return out.join("");
}
- if (propertyType === 'dt') {
+ if (propertyType === "dt") {
return modules.dates.concatFragments(out, this.options.dateFormat).toString(this.options.dateFormat);
}
return undefined;
}
return null;
},
@@ -1069,26 +1069,26 @@ var Microformats; // jshint ignore:line
* @return {String}
*/
getValueTitle(node) {
var out = [],
items,
i,
x;
- items = modules.domUtils.getNodesByAttributeValue(node, 'class', 'value-title');
+ items = modules.domUtils.getNodesByAttributeValue(node, "class", "value-title");
x = 0;
i = items.length;
while (x < i) {
- if (modules.domUtils.hasAttribute(items[x], 'title')) {
- out.push(modules.domUtils.getAttribute(items[x], 'title'));
+ if (modules.domUtils.hasAttribute(items[x], "title")) {
+ out.push(modules.domUtils.getAttribute(items[x], "title"));
}
x++;
}
- return out.join('');
+ return out.join("");
},
/**
* finds out whether a node has h-* class v1 and v2
*
* @param {DOM Node} node
* @return {Boolean}
@@ -1107,18 +1107,18 @@ var Microformats; // jshint ignore:line
*
* @param {DOM Node} node
* @param {Array} ufNameArr
* @return {Object}
*/
getUfClassNames(node, ufNameArr) {
var context = this,
out = {
- 'root': [],
- 'properties': []
+ "root": [],
+ "properties": []
},
classNames,
key,
items,
item,
i,
x,
z,
@@ -1129,54 +1129,54 @@ var Microformats; // jshint ignore:line
v2Name,
impiedRel,
ufName;
// don't get classes from excluded list of tags
if (modules.domUtils.hasTagName(node, this.excludeTags) === false) {
// find classes for node
- classNames = modules.domUtils.getAttribute(node, 'class');
+ classNames = modules.domUtils.getAttribute(node, "class");
if (classNames) {
- items = classNames.split(' ');
+ items = classNames.split(" ");
x = 0;
i = items.length;
while (x < i) {
item = modules.utils.trim(items[x]);
// test for root prefix - v2
if (modules.utils.startWith(item, context.rootPrefix)) {
if (out.root.indexOf(item) === -1) {
out.root.push(item);
}
- out.typeVersion = 'v2';
+ out.typeVersion = "v2";
}
// test for property prefix - v2
z = context.propertyPrefixes.length;
while (z--) {
if (modules.utils.startWith(item, context.propertyPrefixes[z])) {
- out.properties.push([item, 'v2']);
+ out.properties.push([item, "v2"]);
}
}
// test for mapped root classnames v1
for (key in modules.maps) {
if (modules.maps.hasOwnProperty(key)) {
// only add a root once
if (modules.maps[key].root === item && out.root.indexOf(key) === -1) {
// if root map has subTree set to true
// test to see if we should create a property or root
if (modules.maps[key].subTree) {
- out.properties.push(['p-' + modules.maps[key].root, 'v1']);
+ out.properties.push(["p-" + modules.maps[key].root, "v1"]);
} else {
out.root.push(key);
if (!out.typeVersion) {
- out.typeVersion = 'v1';
+ out.typeVersion = "v1";
}
}
}
}
}
// test for mapped property classnames v1
@@ -1185,39 +1185,39 @@ var Microformats; // jshint ignore:line
ufName = ufNameArr[a];
// get mapped property v1 microformat
map = context.getMapping(ufName);
if (map) {
for (key in map.properties) {
if (map.properties.hasOwnProperty(key)) {
prop = map.properties[key];
- propName = (prop.map) ? prop.map : 'p-' + key;
+ propName = (prop.map) ? prop.map : "p-" + key;
if (key === item) {
if (prop.uf) {
// loop all the classList make sure
// 1. this property is a root
// 2. that there is not already an equivalent v2 property i.e. url and u-url on the same element
y = 0;
while (y < i) {
v2Name = context.getV2RootName(items[y]);
// add new root
if (prop.uf.indexOf(v2Name) > -1 && out.root.indexOf(v2Name) === -1) {
out.root.push(v2Name);
- out.typeVersion = 'v1';
+ out.typeVersion = "v1";
}
y++;
}
// only add property once
if (out.properties.indexOf(propName) === -1) {
- out.properties.push([propName, 'v1']);
+ out.properties.push([propName, "v1"]);
}
} else if (out.properties.indexOf(propName) === -1) {
- out.properties.push([propName, 'v1']);
+ out.properties.push([propName, "v1"]);
}
}
}
}
}
}
@@ -1231,17 +1231,17 @@ var Microformats; // jshint ignore:line
// finds any alt rel=* mappings for a given node/microformat
if (ufNameArr && this.findRelImpied) {
for (var b = 0; b < ufNameArr.length; b++) {
ufName = ufNameArr[b];
impiedRel = this.findRelImpied(node, ufName);
if (impiedRel && out.properties.indexOf(impiedRel) === -1) {
- out.properties.push([impiedRel, 'v1']);
+ out.properties.push([impiedRel, "v1"]);
}
}
}
// if(out.root.length === 1 && out.properties.length === 1) {
// if(out.root[0].replace('h-','') === this.removePropPrefix(out.properties[0][0])) {
// out.typeVersion = 'v2';
@@ -1380,17 +1380,17 @@ var Microformats; // jshint ignore:line
attr;
nodes = modules.domUtils.getNodesByAttribute(node, attrName);
i = nodes.length;
while (i--) {
try {
// the url parser can blow up if the format is not right
attr = modules.domUtils.getAttribute(nodes[i], attrName);
- if (attr && attr !== '' && baseUrl !== '' && attr.indexOf('://') === -1) {
+ if (attr && attr !== "" && baseUrl !== "" && attr.indexOf("://") === -1) {
// attr = urlParser.resolve(baseUrl, attr);
attr = modules.url.resolve(attr, baseUrl);
modules.domUtils.setAttribute(nodes[i], attrName, attr);
}
} catch (err) {
// do nothing - convert only the urls we can, leave the rest as they are
}
}
@@ -1417,20 +1417,20 @@ var Microformats; // jshint ignore:line
* removes all rootid attributes
*
* @param {DOM Node} rootNode
*/
removeRootIds(rootNode) {
var arr,
i;
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'rootids');
+ arr = modules.domUtils.getNodesByAttribute(rootNode, "rootids");
i = arr.length;
while (i--) {
- modules.domUtils.removeAttribute(arr[i], 'rootids');
+ modules.domUtils.removeAttribute(arr[i], "rootids");
}
},
/**
* removes all changes made to the DOM
*
* @param {DOM Node} rootNode
@@ -1457,26 +1457,26 @@ var Microformats; // jshint ignore:line
*
* @param {DOM Node} node
* @param {Object} uf (microformat output structure)
* @param {Object} parentClasses (classes structure)
* @param {Boolean} impliedPropertiesByVersion
* @return {Object}
*/
modules.Parser.prototype.impliedRules = function(node, uf, parentClasses) {
- var typeVersion = (uf.typeVersion) ? uf.typeVersion : 'v2';
+ var typeVersion = (uf.typeVersion) ? uf.typeVersion : "v2";
// TEMP: override to allow v1 implied properties while spec changes
if (this.options.impliedPropertiesByVersion === false) {
- typeVersion = 'v2';
+ typeVersion = "v2";
}
if (node && uf && uf.properties) {
uf = this.impliedBackwardComp( node, uf, parentClasses );
- if (typeVersion === 'v2') {
+ if (typeVersion === "v2") {
uf = this.impliedhFeedTitle( uf );
uf = this.impliedName( node, uf );
uf = this.impliedPhoto( node, uf );
uf = this.impliedUrl( node, uf );
}
uf = this.impliedValue( node, uf, parentClasses );
uf = this.impliedDate( uf );
@@ -1511,25 +1511,25 @@ var Microformats; // jshint ignore:line
.h-x>:only-child>img:only-child[alt]:not[.h-*] <div class="h-card"><span><img src="jane.html" alt="Jane Doe"/></span></div>
.h-x>:only-child>area:only-child[alt]:not[.h-*] <div class="h-card"><span><area href="jane.html" alt="Jane Doe"></area></span></div>
.h-x>:only-child>abbr:only-child[title] <div class="h-card"><span><abbr title="Jane Doe">JD</abbr></span></div>
*/
var name,
value;
if (!uf.properties.name) {
- value = this.getImpliedProperty(node, ['img', 'area', 'abbr'], this.getNameAttr);
+ value = this.getImpliedProperty(node, ["img", "area", "abbr"], this.getNameAttr);
var textFormat = this.options.textFormat;
// if no value for tags/properties use text
if (!value) {
name = [modules.text.parse(this.document, node, textFormat)];
} else {
name = [modules.text.parseText(this.document, value, textFormat)];
}
- if (name && name[0] !== '') {
+ if (name && name[0] !== "") {
uf.properties.name = name;
}
}
return uf;
};
@@ -1547,20 +1547,20 @@ var Microformats; // jshint ignore:line
object.h-x[data] <object class="h-card" data="jane.jpeg"/>Jane Doe</object>
.h-x>img[src]:only-of-type:not[.h-*] <div class="h-card"><img alt="Jane Doe" src="jane.jpeg"/></div>
.h-x>object[data]:only-of-type:not[.h-*] <div class="h-card"><object data="jane.jpeg"/>Jane Doe</object></div>
.h-x>:only-child>img[src]:only-of-type:not[.h-*] <div class="h-card"><span><img alt="Jane Doe" src="jane.jpeg"/></span></div>
.h-x>:only-child>object[data]:only-of-type:not[.h-*] <div class="h-card"><span><object data="jane.jpeg"/>Jane Doe</object></span></div>
*/
var value;
if (!uf.properties.photo) {
- value = this.getImpliedProperty(node, ['img', 'object'], this.getPhotoAttr);
+ value = this.getImpliedProperty(node, ["img", "object"], this.getPhotoAttr);
if (value) {
// relative to absolute URL
- if (value && value !== '' && this.options.baseUrl !== '' && value.indexOf('://') === -1) {
+ if (value && value !== "" && this.options.baseUrl !== "" && value.indexOf("://") === -1) {
value = modules.url.resolve(value, this.options.baseUrl);
}
uf.properties.photo = [modules.utils.trim(value)];
}
}
return uf;
};
@@ -1577,20 +1577,20 @@ var Microformats; // jshint ignore:line
/*
a.h-x[href] <a class="h-card" href="glenn.html">Glenn</a>
area.h-x[href] <area class="h-card" href="glenn.html">Glenn</area>
.h-x>a[href]:only-of-type:not[.h-*] <div class="h-card" ><a href="glenn.html">Glenn</a><p>...</p></div>
.h-x>area[href]:only-of-type:not[.h-*] <div class="h-card" ><area href="glenn.html">Glenn</area><p>...</p></div>
*/
var value;
if (!uf.properties.url) {
- value = this.getImpliedProperty(node, ['a', 'area'], this.getURLAttr);
+ value = this.getImpliedProperty(node, ["a", "area"], this.getURLAttr);
if (value) {
// relative to absolute URL
- if (value && value !== '' && this.options.baseUrl !== '' && value.indexOf('://') === -1) {
+ if (value && value !== "" && this.options.baseUrl !== "" && value.indexOf("://") === -1) {
value = modules.url.resolve(value, this.options.baseUrl);
}
uf.properties.url = [modules.utils.trim(value)];
}
}
return uf;
};
@@ -1656,52 +1656,52 @@ var Microformats; // jshint ignore:line
/**
* get an implied name value from a node
*
* @param {DOM Node} node
* @return {String || null}
*/
modules.Parser.prototype.getNameAttr = function(node) {
- var value = modules.domUtils.getAttrValFromTagList(node, ['img', 'area'], 'alt');
+ var value = modules.domUtils.getAttrValFromTagList(node, ["img", "area"], "alt");
if (!value) {
- value = modules.domUtils.getAttrValFromTagList(node, ['abbr'], 'title');
+ value = modules.domUtils.getAttrValFromTagList(node, ["abbr"], "title");
}
return value;
};
/**
* get an implied photo value from a node
*
* @param {DOM Node} node
* @return {String || null}
*/
modules.Parser.prototype.getPhotoAttr = function(node) {
- var value = modules.domUtils.getAttrValFromTagList(node, ['img'], 'src');
- if (!value && modules.domUtils.hasAttributeValue(node, 'class', 'include') === false) {
- value = modules.domUtils.getAttrValFromTagList(node, ['object'], 'data');
+ var value = modules.domUtils.getAttrValFromTagList(node, ["img"], "src");
+ if (!value && modules.domUtils.hasAttributeValue(node, "class", "include") === false) {
+ value = modules.domUtils.getAttrValFromTagList(node, ["object"], "data");
}
return value;
};
/**
* get an implied photo value from a node
*
* @param {DOM Node} node
* @return {String || null}
*/
modules.Parser.prototype.getURLAttr = function(node) {
var value = null;
- if (modules.domUtils.hasAttributeValue(node, 'class', 'include') === false) {
-
- value = modules.domUtils.getAttrValFromTagList(node, ['a'], 'href');
+ if (modules.domUtils.hasAttributeValue(node, "class", "include") === false) {
+
+ value = modules.domUtils.getAttrValFromTagList(node, ["a"], "href");
if (!value) {
- value = modules.domUtils.getAttrValFromTagList(node, ['area'], 'href');
+ value = modules.domUtils.getAttrValFromTagList(node, ["area"], "href");
}
}
return value;
};
/**
@@ -1711,24 +1711,24 @@ var Microformats; // jshint ignore:line
* @param {Object} uf
* @return {Object}
*/
modules.Parser.prototype.impliedValue = function(node, uf, parentClasses) {
// intersection of implied name and implied value rules
if (uf.properties.name) {
if (uf.value && parentClasses.root.length > 0 && parentClasses.properties.length === 1) {
- uf = this.getAltValue(uf, parentClasses.properties[0][0], 'p-name', uf.properties.name[0]);
+ uf = this.getAltValue(uf, parentClasses.properties[0][0], "p-name", uf.properties.name[0]);
}
}
// intersection of implied URL and implied value rules
if (uf.properties.url) {
if (parentClasses && parentClasses.root.length === 1 && parentClasses.properties.length === 1) {
- uf = this.getAltValue(uf, parentClasses.properties[0][0], 'u-url', uf.properties.url[0]);
+ uf = this.getAltValue(uf, parentClasses.properties[0][0], "u-url", uf.properties.url[0]);
}
}
// apply alt value
if (uf.altValue !== null) {
uf.value = uf.altValue.value;
}
delete uf.altValue;
@@ -1745,44 +1745,44 @@ var Microformats; // jshint ignore:line
* @param {String} parentPropertyName
* @param {String} propertyName
* @param {String} value
* @return {Object}
*/
modules.Parser.prototype.getAltValue = function(uf, parentPropertyName, propertyName, value) {
if (uf.value && !uf.altValue) {
// first p-name of the h-* child
- if (modules.utils.startWith(parentPropertyName, 'p-') && propertyName === 'p-name') {
+ if (modules.utils.startWith(parentPropertyName, "p-") && propertyName === "p-name") {
uf.altValue = {name: propertyName, value};
}
// if it's an e-* property element
- if (modules.utils.startWith(parentPropertyName, 'e-') && modules.utils.startWith(propertyName, 'e-')) {
+ if (modules.utils.startWith(parentPropertyName, "e-") && modules.utils.startWith(propertyName, "e-")) {
uf.altValue = {name: propertyName, value};
}
// if it's an u-* property element
- if (modules.utils.startWith(parentPropertyName, 'u-') && propertyName === 'u-url') {
+ if (modules.utils.startWith(parentPropertyName, "u-") && propertyName === "u-url") {
uf.altValue = {name: propertyName, value};
}
}
return uf;
};
/**
* if a h-feed does not have a title use the title tag of a page
*
* @param {Object} uf
* @return {Object}
*/
modules.Parser.prototype.impliedhFeedTitle = function( uf ) {
- if (uf.type && uf.type.indexOf('h-feed') > -1) {
+ if (uf.type && uf.type.indexOf("h-feed") > -1) {
// has no name property
- if (uf.properties.name === undefined || uf.properties.name[0] === '' ) {
+ if (uf.properties.name === undefined || uf.properties.name[0] === "" ) {
// use the text from the title tag
- var title = modules.domUtils.querySelector(this.document, 'title');
+ var title = modules.domUtils.querySelector(this.document, "title");
if (title) {
uf.properties.name = [modules.domUtils.textContent(title)];
}
}
}
return uf;
};
@@ -1796,31 +1796,31 @@ var Microformats; // jshint ignore:line
*/
modules.Parser.prototype.impliedGeo = function( uf ) {
var geoPair,
parts,
longitude,
latitude,
valid = true;
- if (uf.type && uf.type.indexOf('h-geo') > -1) {
+ if (uf.type && uf.type.indexOf("h-geo") > -1) {
// has no latitude or longitude property
if (uf.properties.latitude === undefined || uf.properties.longitude === undefined ) {
geoPair = (uf.properties.name) ? uf.properties.name[0] : null;
geoPair = (!geoPair && uf.properties.value) ? uf.properties.value : geoPair;
if (geoPair) {
// allow for the use of a ';' as in microformats and also ',' as in Geo URL
- geoPair = geoPair.replace(';', ',');
+ geoPair = geoPair.replace(";", ",");
// has sep char
- if (geoPair.indexOf(',') > -1 ) {
- parts = geoPair.split(',');
+ if (geoPair.indexOf(",") > -1 ) {
+ parts = geoPair.split(",");
// only correct if we have two or more parts
if (parts.length > 1) {
// latitude no value outside the range -90 or 90
latitude = parseFloat( parts[0] );
if (modules.utils.isNumber(latitude) && latitude > 90 || latitude < -90) {
valid = false;
@@ -1852,17 +1852,17 @@ var Microformats; // jshint ignore:line
* @param {Object} uf
* @return {Object}
*/
modules.Parser.prototype.impliedBackwardComp = function(node, uf, parentClasses) {
// look for pattern in parent classes like "p-geo h-geo"
// these are structures built from backwards compat parsing of geo
if (parentClasses.root.length === 1 && parentClasses.properties.length === 1) {
- if (parentClasses.root[0].replace('h-', '') === this.removePropPrefix(parentClasses.properties[0][0])) {
+ if (parentClasses.root[0].replace("h-", "") === this.removePropPrefix(parentClasses.properties[0][0])) {
// if microformat has no properties apply the impliedName rule to get value from containing node
// this will get value from html such as <abbr class="geo" title="30.267991;-97.739568">Brighton</abbr>
if ( modules.utils.hasProperties(uf.properties) === false ) {
uf = this.impliedName( node, uf );
}
}
}
@@ -1880,18 +1880,18 @@ var Microformats; // jshint ignore:line
/**
* appends clones of include Nodes into the DOM structure
*
* @param {DOM node} rootNode
*/
modules.Parser.prototype.addIncludes = function(rootNode) {
- this.addAttributeIncludes(rootNode, 'itemref');
- this.addAttributeIncludes(rootNode, 'headers');
+ this.addAttributeIncludes(rootNode, "itemref");
+ this.addAttributeIncludes(rootNode, "headers");
this.addClassIncludes(rootNode);
};
/**
* appends clones of include Nodes into the DOM structure for attribute based includes
*
* @param {DOM node} rootNode
@@ -1929,22 +1929,22 @@ var Microformats; // jshint ignore:line
* @param {DOM node} rootNode
*/
modules.Parser.prototype.addClassIncludes = function(rootNode) {
var id,
arr,
x = 0,
i;
- arr = modules.domUtils.getNodesByAttributeValue(rootNode, 'class', 'include');
+ arr = modules.domUtils.getNodesByAttributeValue(rootNode, "class", "include");
i = arr.length;
while (x < i) {
- id = modules.domUtils.getAttrValFromTagList(arr[x], ['a'], 'href');
+ id = modules.domUtils.getAttrValFromTagList(arr[x], ["a"], "href");
if (!id) {
- id = modules.domUtils.getAttrValFromTagList(arr[x], ['object'], 'data');
+ id = modules.domUtils.getAttrValFromTagList(arr[x], ["object"], "data");
}
this.apppendInclude(arr[x], id);
x++;
}
};
/**
@@ -1952,17 +1952,17 @@ var Microformats; // jshint ignore:line
*
* @param {DOM node} rootNode
* @param {Stringe} id
*/
modules.Parser.prototype.apppendInclude = function(node, id) {
var include,
clone;
- id = modules.utils.trim(id.replace('#', ''));
+ id = modules.utils.trim(id.replace("#", ""));
include = modules.domUtils.getElementById(this.document, id);
if (include) {
clone = modules.domUtils.clone(include);
this.markIncludeChildren(clone);
modules.domUtils.appendChild(node, clone);
}
};
@@ -1976,36 +1976,36 @@ var Microformats; // jshint ignore:line
var arr,
x,
i;
// loop the array and add the attribute
arr = this.findRootNodes(rootNode);
x = 0;
i = arr.length;
- modules.domUtils.setAttribute(rootNode, 'data-include', 'true');
- modules.domUtils.setAttribute(rootNode, 'style', 'display:none');
+ modules.domUtils.setAttribute(rootNode, "data-include", "true");
+ modules.domUtils.setAttribute(rootNode, "style", "display:none");
while (x < i) {
- modules.domUtils.setAttribute(arr[x], 'data-include', 'true');
+ modules.domUtils.setAttribute(arr[x], "data-include", "true");
x++;
}
};
/**
* removes all appended include clones from DOM
*
* @param {DOM node} rootNode
*/
modules.Parser.prototype.removeIncludes = function(rootNode) {
var arr,
i;
// remove all the items that were added as includes
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'data-include');
+ arr = modules.domUtils.getNodesByAttribute(rootNode, "data-include");
i = arr.length;
while (i--) {
modules.domUtils.removeChild(rootNode, arr[i]);
}
};
}
@@ -2017,84 +2017,84 @@ var Microformats; // jshint ignore:line
/**
* finds rel=* structures
*
* @param {DOM node} rootNode
* @return {Object}
*/
modules.Parser.prototype.findRels = function(rootNode) {
var out = {
- 'items': [],
- 'rels': {},
- 'rel-urls': {}
+ "items": [],
+ "rels": {},
+ "rel-urls": {}
},
x,
i,
y,
z,
relList,
items,
item,
value,
arr;
- arr = modules.domUtils.getNodesByAttribute(rootNode, 'rel');
+ arr = modules.domUtils.getNodesByAttribute(rootNode, "rel");
x = 0;
i = arr.length;
while (x < i) {
- relList = modules.domUtils.getAttribute(arr[x], 'rel');
+ relList = modules.domUtils.getAttribute(arr[x], "rel");
if (relList) {
- items = relList.split(' ');
+ items = relList.split(" ");
// add rels
z = 0;
y = items.length;
while (z < y) {
item = modules.utils.trim(items[z]);
// get rel value
- value = modules.domUtils.getAttrValFromTagList(arr[x], ['a', 'area'], 'href');
+ value = modules.domUtils.getAttrValFromTagList(arr[x], ["a", "area"], "href");
if (!value) {
- value = modules.domUtils.getAttrValFromTagList(arr[x], ['link'], 'href');
+ value = modules.domUtils.getAttrValFromTagList(arr[x], ["link"], "href");
}
// create the key
if (!out.rels[item]) {
out.rels[item] = [];
}
- if (typeof this.options.baseUrl === 'string' && typeof value === 'string') {
+ if (typeof this.options.baseUrl === "string" && typeof value === "string") {
var resolved = modules.url.resolve(value, this.options.baseUrl);
// do not add duplicate rels - based on resolved URLs
if (out.rels[item].indexOf(resolved) === -1) {
out.rels[item].push( resolved );
}
}
z++;
}
var url = null;
- if (modules.domUtils.hasAttribute(arr[x], 'href')) {
- url = modules.domUtils.getAttribute(arr[x], 'href');
+ if (modules.domUtils.hasAttribute(arr[x], "href")) {
+ url = modules.domUtils.getAttribute(arr[x], "href");
if (url) {
url = modules.url.resolve(url, this.options.baseUrl );
}
}
// add to rel-urls
var relUrl = this.getRelProperties(arr[x]);
relUrl.rels = items;
// do not add duplicate rel-urls - based on resolved URLs
- if (url && out['rel-urls'][url] === undefined) {
- out['rel-urls'][url] = relUrl;
+ if (url && out["rel-urls"][url] === undefined) {
+ out["rel-urls"][url] = relUrl;
}
}
x++;
}
return out;
};
@@ -2104,29 +2104,29 @@ var Microformats; // jshint ignore:line
* gets the properties of a rel=*
*
* @param {DOM node} node
* @return {Object}
*/
modules.Parser.prototype.getRelProperties = function(node) {
var obj = {};
- if (modules.domUtils.hasAttribute(node, 'media')) {
- obj.media = modules.domUtils.getAttribute(node, 'media');
+ if (modules.domUtils.hasAttribute(node, "media")) {
+ obj.media = modules.domUtils.getAttribute(node, "media");
}
- if (modules.domUtils.hasAttribute(node, 'type')) {
- obj.type = modules.domUtils.getAttribute(node, 'type');
+ if (modules.domUtils.hasAttribute(node, "type")) {
+ obj.type = modules.domUtils.getAttribute(node, "type");
}
- if (modules.domUtils.hasAttribute(node, 'hreflang')) {
- obj.hreflang = modules.domUtils.getAttribute(node, 'hreflang');
+ if (modules.domUtils.hasAttribute(node, "hreflang")) {
+ obj.hreflang = modules.domUtils.getAttribute(node, "hreflang");
}
- if (modules.domUtils.hasAttribute(node, 'title')) {
- obj.title = modules.domUtils.getAttribute(node, 'title');
+ if (modules.domUtils.hasAttribute(node, "title")) {
+ obj.title = modules.domUtils.getAttribute(node, "title");
}
- if (modules.utils.trim(this.getPValue(node, false)) !== '') {
+ if (modules.utils.trim(this.getPValue(node, false)) !== "") {
obj.text = this.getPValue(node, false);
}
return obj;
};
/**
@@ -2141,24 +2141,24 @@ var Microformats; // jshint ignore:line
map,
i;
map = this.getMapping(ufName);
if (map) {
for (var key in map.properties) {
if (map.properties.hasOwnProperty(key)) {
var prop = map.properties[key],
- propName = (prop.map) ? prop.map : 'p-' + key,
+ propName = (prop.map) ? prop.map : "p-" + key,
relCount = 0;
// is property an alt rel=* mapping
- if (prop.relAlt && modules.domUtils.hasAttribute(node, 'rel')) {
+ if (prop.relAlt && modules.domUtils.hasAttribute(node, "rel")) {
i = prop.relAlt.length;
while (i--) {
- if (modules.domUtils.hasAttributeValue(node, 'rel', prop.relAlt[i])) {
+ if (modules.domUtils.hasAttributeValue(node, "rel", prop.relAlt[i])) {
relCount++;
}
}
if (relCount === prop.relAlt.length) {
out = propName;
}
}
}
@@ -2182,17 +2182,17 @@ var Microformats; // jshint ignore:line
/**
* returns the number of rel=* microformats
*
* @param {DOM node} node
* @return {Int}
*/
modules.Parser.prototype.countRels = function(node) {
if (node) {
- return modules.domUtils.getNodesByAttribute(node, 'rel').length;
+ return modules.domUtils.getNodesByAttribute(node, "rel").length;
}
return 0;
};
}
@@ -2201,17 +2201,17 @@ var Microformats; // jshint ignore:line
/**
* is the object a string
*
* @param {Object} obj
* @return {Boolean}
*/
isString( obj ) {
- return typeof( obj ) === 'string';
+ return typeof( obj ) === "string";
},
/**
* is the object a number
*
* @param {Object} obj
* @return {Boolean}
*/
@@ -2222,17 +2222,17 @@ var Microformats; // jshint ignore:line
/**
* is the object an array
*
* @param {Object} obj
* @return {Boolean}
*/
isArray( obj ) {
- return obj && !( obj.propertyIsEnumerable( 'length' ) ) && typeof obj === 'object' && typeof obj.length === 'number';
+ return obj && !( obj.propertyIsEnumerable( "length" ) ) && typeof obj === "object" && typeof obj.length === "number";
},
/**
* is the object a function
*
* @param {Object} obj
* @return {Boolean}
@@ -2257,19 +2257,19 @@ var Microformats; // jshint ignore:line
/**
* removes spaces at front and back of text
*
* @param {String} text
* @return {String}
*/
trim( text ) {
if (text && this.isString(text)) {
- return (text.trim()) ? text.trim() : text.replace(/^\s+|\s+$/g, '');
+ return (text.trim()) ? text.trim() : text.replace(/^\s+|\s+$/g, "");
}
- return '';
+ return "";
},
/**
* replaces a character in text
*
* @param {String} text
* @param {Int} index
@@ -2293,27 +2293,27 @@ var Microformats; // jshint ignore:line
trimWhitespace( text ) {
if (text && text.length) {
var i = text.length,
x = 0;
// turn all whitespace chars at end into spaces
while (i--) {
if (this.isOnlyWhiteSpace(text[i])) {
- text = this.replaceCharAt( text, i, ' ' );
+ text = this.replaceCharAt( text, i, " " );
} else {
break;
}
}
// turn all whitespace chars at start into spaces
i = text.length;
while (x < i) {
if (this.isOnlyWhiteSpace(text[x])) {
- text = this.replaceCharAt( text, i, ' ' );
+ text = this.replaceCharAt( text, i, " " );
} else {
break;
}
x++;
}
}
return this.trim(text);
},
@@ -2332,17 +2332,17 @@ var Microformats; // jshint ignore:line
/**
* removes whitespace from text (leaves a single space)
*
* @param {String} text
* @return {Sring}
*/
collapseWhiteSpace( text ) {
- return text.replace(/[\t\n\r ]+/g, ' ');
+ return text.replace(/[\t\n\r ]+/g, " ");
},
/**
* does an object have any of its own properties
*
* @param {Object} obj
* @return {Boolean}
@@ -2422,35 +2422,35 @@ var Microformats; // jshint ignore:line
this.rootNode = options.node;
}
// if a html string is passed
if (options.html) {
// var domParser = new DOMParser();
var domParser = this.getDOMParser();
- this.rootNode = domParser.parseFromString( options.html, 'text/html' );
+ this.rootNode = domParser.parseFromString( options.html, "text/html" );
}
// find top level document from rootnode
if (this.rootNode !== null) {
if (this.rootNode.nodeType === 9) {
this.document = this.rootNode;
- this.rootNode = modules.domUtils.querySelector(this.rootNode, 'html');
+ this.rootNode = modules.domUtils.querySelector(this.rootNode, "html");
} else {
// if it's DOM node get parent DOM Document
this.document = modules.domUtils.ownerDocument(this.rootNode);
}
}
// use global document object
if (!this.rootNode && document) {
- this.rootNode = modules.domUtils.querySelector(document, 'html');
+ this.rootNode = modules.domUtils.querySelector(document, "html");
this.document = document;
}
if (this.rootNode && this.document) {
return {document: this.document, rootNode: this.rootNode};
}
@@ -2493,17 +2493,17 @@ var Microformats; // jshint ignore:line
* @return {String}
*/
textContent(node) {
if (node.textContent) {
return node.textContent;
} else if (node.innerText) {
return node.innerText;
}
- return '';
+ return "";
},
/**
* abstracts DOM innerHTML
*
* @param {DOM Node} node
* @return {String}
@@ -2576,17 +2576,17 @@ var Microformats; // jshint ignore:line
/**
* abstracts DOM getElementById
*
* @param {DOM Node || DOM Document} node
* @param {String} id
* @return {DOM Node}
*/
getElementById(docNode, id) {
- return docNode.querySelector( '#' + id );
+ return docNode.querySelector( "#" + id );
},
/**
* abstracts DOM querySelector
*
* @param {DOM Node || DOM Document} node
* @param {String} selector
@@ -2604,36 +2604,36 @@ var Microformats; // jshint ignore:line
* @param {String} attributeName
* @return {Array}
*/
getAttributeList(node, attributeName) {
var out = [],
attList;
attList = node.getAttribute(attributeName);
- if (attList && attList !== '') {
- if (attList.indexOf(' ') > -1) {
- out = attList.split(' ');
+ if (attList && attList !== "") {
+ if (attList.indexOf(" ") > -1) {
+ out = attList.split(" ");
} else {
out.push(attList);
}
}
return out;
},
/**
* gets all child nodes with a given attribute
*
* @param {DOM Node} node
* @param {String} attributeName
* @return {NodeList}
*/
getNodesByAttribute(node, attributeName) {
- var selector = '[' + attributeName + ']';
+ var selector = "[" + attributeName + "]";
return node.querySelectorAll(selector);
},
/**
* gets all child nodes with a given attribute containing a given value
*
* @param {DOM Node} node
@@ -2668,17 +2668,17 @@ var Microformats; // jshint ignore:line
* @return {String || null}
*/
getAttrValFromTagList(node, tagNames, attributeName) {
var i = tagNames.length;
while (i--) {
if (node.tagName.toLowerCase() === tagNames[i]) {
var attrValue = this.getAttribute(node, attributeName);
- if (attrValue && attrValue !== '') {
+ if (attrValue && attrValue !== "") {
return attrValue;
}
}
}
return null;
},
@@ -2790,32 +2790,32 @@ var Microformats; // jshint ignore:line
/**
* abstracts DOM cloneNode
*
* @param {DOM Node} node
* @return {DOM Node}
*/
clone(node) {
var newNode = node.cloneNode(true);
- newNode.removeAttribute('id');
+ newNode.removeAttribute("id");
return newNode;
},
/**
* gets the text of a node
*
* @param {DOM Node} node
* @return {String}
*/
getElementText( node ) {
if (node && node.data) {
return node.data;
}
- return '';
+ return "";
},
/**
* gets the attributes of a node - ordered by sequence in html
*
* @param {DOM Node} node
* @return {Array}
@@ -2825,17 +2825,17 @@ var Microformats; // jshint ignore:line
attrs = [];
for (var i = 0; i < node.attributes.length; i++) {
var attr = node.attributes[i];
attr.indexNum = nodeStr.indexOf(attr.name);
attrs.push( attr );
}
- return attrs.sort( modules.utils.sortObjects( 'indexNum' ) );
+ return attrs.sort( modules.utils.sortObjects( "indexNum" ) );
},
/**
* decodes html entities in given text
*
* @param {DOM Document} doc
* @param String} text
@@ -2853,19 +2853,19 @@ var Microformats; // jshint ignore:line
* @param {DOM Document} document
* @return {DOM Document}
*/
cloneDocument( document ) {
var newNode,
newDocument = null;
if ( this.canCloneDocument( document )) {
- newDocument = document.implementation.createHTMLDocument('');
+ newDocument = document.implementation.createHTMLDocument("");
newNode = newDocument.importNode( document.documentElement, true );
- newDocument.replaceChild(newNode, newDocument.querySelector('html'));
+ newDocument.replaceChild(newNode, newDocument.querySelector("html"));
}
return (newNode && newNode.nodeType && newNode.nodeType === 1) ? newDocument : document;
},
/**
* can environment clone a DOM document
*
@@ -2980,38 +2980,38 @@ var Microformats; // jshint ignore:line
/**
* creates DOM objects needed to resolve URLs
*/
init() {
// this._domParser = new DOMParser();
this._domParser = modules.domUtils.getDOMParser();
// do not use a head tag it does not work with IE9
this._html = '<base id="base" href=""></base><a id="link" href=""></a>';
- this._nodes = this._domParser.parseFromString( this._html, 'text/html' );
- this._baseNode = modules.domUtils.getElementById(this._nodes, 'base');
- this._linkNode = modules.domUtils.getElementById(this._nodes, 'link');
+ this._nodes = this._domParser.parseFromString( this._html, "text/html" );
+ this._baseNode = modules.domUtils.getElementById(this._nodes, "base");
+ this._linkNode = modules.domUtils.getElementById(this._nodes, "link");
},
/**
* resolves url to absolute version using baseUrl
*
* @param {String} url
* @param {String} baseUrl
* @return {String}
*/
resolve(url, baseUrl) {
// use modern URL web API where we can
- if (modules.utils.isString(url) && modules.utils.isString(baseUrl) && url.indexOf('://') === -1) {
+ if (modules.utils.isString(url) && modules.utils.isString(baseUrl) && url.indexOf("://") === -1) {
// this try catch is required as IE has an URL object but no constuctor support
// http://glennjones.net/articles/the-problem-with-window-url
try {
var resolved = new URL(url, baseUrl).toString();
// deal with early Webkit not throwing an error - for Safari
- if (resolved === '[object URL]') {
+ if (resolved === "[object URL]") {
resolved = URI.resolve(baseUrl, url);
}
return resolved;
} catch (e) {
// otherwise fallback to DOM
if (this._domParser === undefined) {
this.init();
}
@@ -3022,17 +3022,17 @@ var Microformats; // jshint ignore:line
// dont use getAttribute as it returns orginal value not resolved
return this._linkNode.href;
}
} else {
if (modules.utils.isString(url)) {
return url;
}
- return '';
+ return "";
}
},
};
/**
* constructor
@@ -3040,17 +3040,17 @@ var Microformats; // jshint ignore:line
*
* @param {String} dateString
* @param {String} format
* @return {String}
*/
modules.ISODate = function( dateString, format ) {
this.clear();
- this.format = (format) ? format : 'auto'; // auto or W3C or RFC3339 or HTML5
+ this.format = (format) ? format : "auto"; // auto or W3C or RFC3339 or HTML5
this.setFormatSep();
// optional should be full iso date/time string
if (arguments[0]) {
this.parse(dateString, format);
}
};
@@ -3096,32 +3096,32 @@ var Microformats; // jshint ignore:line
/**
* clear timezone states
*
*/
clearTimeZone() {
this.tzH = -1;
this.tzM = -1;
- this.tzPN = '+';
+ this.tzPN = "+";
this.z = false;
},
/**
* resets the auto profile state
*
*/
setAutoProfileState() {
this.autoProfile = {
- sep: 'T',
- dsep: '-',
- tsep: ':',
- tzsep: ':',
- tzZulu: 'Z'
+ sep: "T",
+ dsep: "-",
+ tsep: ":",
+ tzsep: ":",
+ tzZulu: "Z"
};
},
/**
* parses text to find ISO date/time string i.e. 2008-05-01T15:45:19Z
*
* @param {String} dateString
@@ -3129,85 +3129,85 @@ var Microformats; // jshint ignore:line
* @return {String}
*/
parse( dateString, format ) {
this.clear();
var parts = [],
tzArray = [],
position = 0,
- datePart = '',
- timePart = '',
- timeZonePart = '';
+ datePart = "",
+ timePart = "",
+ timeZonePart = "";
if (format) {
this.format = format;
}
// discover date time separtor for auto profile
// Set to 'T' by default
- if (dateString.indexOf('t') > -1) {
- this.autoProfile.sep = 't';
+ if (dateString.indexOf("t") > -1) {
+ this.autoProfile.sep = "t";
}
- if (dateString.indexOf('z') > -1) {
- this.autoProfile.tzZulu = 'z';
+ if (dateString.indexOf("z") > -1) {
+ this.autoProfile.tzZulu = "z";
}
- if (dateString.indexOf('Z') > -1) {
- this.autoProfile.tzZulu = 'Z';
+ if (dateString.indexOf("Z") > -1) {
+ this.autoProfile.tzZulu = "Z";
}
- if (dateString.toUpperCase().indexOf('T') === -1) {
- this.autoProfile.sep = ' ';
+ if (dateString.toUpperCase().indexOf("T") === -1) {
+ this.autoProfile.sep = " ";
}
- dateString = dateString.toUpperCase().replace(' ', 'T');
+ dateString = dateString.toUpperCase().replace(" ", "T");
// break on 'T' divider or space
- if (dateString.indexOf('T') > -1) {
- parts = dateString.split('T');
+ if (dateString.indexOf("T") > -1) {
+ parts = dateString.split("T");
datePart = parts[0];
timePart = parts[1];
// zulu UTC
- if (timePart.indexOf( 'Z' ) > -1) {
+ if (timePart.indexOf( "Z" ) > -1) {
this.z = true;
}
// timezone
- if (timePart.indexOf( '+' ) > -1 || timePart.indexOf( '-' ) > -1) {
- tzArray = timePart.split( 'Z' ); // incase of incorrect use of Z
+ if (timePart.indexOf( "+" ) > -1 || timePart.indexOf( "-" ) > -1) {
+ tzArray = timePart.split( "Z" ); // incase of incorrect use of Z
timePart = tzArray[0];
timeZonePart = tzArray[1];
// timezone
- if (timePart.indexOf( '+' ) > -1 || timePart.indexOf( '-' ) > -1) {
+ if (timePart.indexOf( "+" ) > -1 || timePart.indexOf( "-" ) > -1) {
position = 0;
- if (timePart.indexOf( '+' ) > -1) {
- position = timePart.indexOf( '+' );
+ if (timePart.indexOf( "+" ) > -1) {
+ position = timePart.indexOf( "+" );
} else {
- position = timePart.indexOf( '-' );
+ position = timePart.indexOf( "-" );
}
timeZonePart = timePart.substring( position, timePart.length );
timePart = timePart.substring( 0, position );
}
}
} else {
datePart = dateString;
}
- if (datePart !== '') {
+ if (datePart !== "") {
this.parseDate( datePart );
- if (timePart !== '') {
+ if (timePart !== "") {
this.parseTime( timePart );
- if (timeZonePart !== '') {
+ if (timeZonePart !== "") {
this.parseTimeZone( timeZonePart );
}
}
}
return this.toString( format );
},
@@ -3219,18 +3219,18 @@ var Microformats; // jshint ignore:line
* @return {String}
*/
parseDate( dateString, format ) {
this.clearDate();
var parts = [];
// discover timezone separtor for auto profile // default is ':'
- if (dateString.indexOf('-') === -1) {
- this.autoProfile.tsep = '';
+ if (dateString.indexOf("-") === -1) {
+ this.autoProfile.tsep = "";
}
// YYYY-DDD
parts = dateString.match( /(\d\d\d\d)-(\d\d\d)/ );
if (parts) {
if (parts[1]) {
this.dY = parts[1];
}
@@ -3263,18 +3263,18 @@ var Microformats; // jshint ignore:line
* @param {String} format
* @return {String}
*/
parseTime( timeString, format ) {
this.clearTime();
var parts = [];
// discover date separtor for auto profile // default is ':'
- if (timeString.indexOf(':') === -1) {
- this.autoProfile.tsep = '';
+ if (timeString.indexOf(":") === -1) {
+ this.autoProfile.tsep = "";
}
// finds timezone HH:MM:SS and HHMMSS ie 13:30:45, 133045 and 13:30:45.0135
parts = timeString.match( /(\d\d)?:?(\d\d)?:?(\d\d)?.?([0-9]+)?/ );
if (parts[1]) {
this.tH = parts[1];
}
if (parts[2]) {
@@ -3296,54 +3296,54 @@ var Microformats; // jshint ignore:line
* @param {String} timeString
* @param {String} format
* @return {String}
*/
parseTimeZone( timeString, format ) {
this.clearTimeZone();
var parts = [];
- if (timeString.toLowerCase() === 'z') {
+ if (timeString.toLowerCase() === "z") {
this.z = true;
// set case for z
- this.autoProfile.tzZulu = (timeString === 'z') ? 'z' : 'Z';
+ this.autoProfile.tzZulu = (timeString === "z") ? "z" : "Z";
} else {
// discover timezone separtor for auto profile // default is ':'
- if (timeString.indexOf(':') === -1) {
- this.autoProfile.tzsep = '';
+ if (timeString.indexOf(":") === -1) {
+ this.autoProfile.tzsep = "";
}
// finds timezone +HH:MM and +HHMM ie +13:30 and +1330
parts = timeString.match( /([\-\+]{1})?(\d\d)?:?(\d\d)?/ );
if (parts[1]) {
this.tzPN = parts[1];
}
if (parts[2]) {
this.tzH = parts[2];
}
if (parts[3]) {
this.tzM = parts[3];
}
}
- this.tzZulu = 'z';
+ this.tzZulu = "z";
return this.toTimeString( format );
},
/**
* returns ISO date/time string in W3C Note, RFC 3339, HTML5, or auto profile
*
* @param {String} format
* @return {String}
*/
toString( format ) {
- var output = '';
+ var output = "";
if (format) {
this.format = format;
}
this.setFormatSep();
if (this.dY > -1) {
output = this.dY;
@@ -3370,33 +3370,33 @@ var Microformats; // jshint ignore:line
/**
* returns just the time string element of an ISO date/time
* in W3C Note, RFC 3339, HTML5, or auto profile
*
* @param {String} format
* @return {String}
*/
toTimeString( format ) {
- var out = '';
+ var out = "";
if (format) {
this.format = format;
}
this.setFormatSep();
// time can only be created with a full date
if (this.tH) {
if (this.tH > -1 && this.tH < 25) {
out += this.tH;
if (this.tM > -1 && this.tM < 61) {
out += this.tsep + this.tM;
if (this.tS > -1 && this.tS < 61) {
out += this.tsep + this.tS;
if (this.tD > -1) {
- out += '.' + this.tD;
+ out += "." + this.tD;
}
}
}
// time zone offset
if (this.z) {
@@ -3414,36 +3414,36 @@ var Microformats; // jshint ignore:line
/**
* set the current profile to W3C Note, RFC 3339, HTML5, or auto profile
*
*/
setFormatSep() {
switch ( this.format.toLowerCase() ) {
- case 'rfc3339':
- this.sep = 'T';
- this.dsep = '';
- this.tsep = '';
- this.tzsep = '';
- this.tzZulu = 'Z';
+ case "rfc3339":
+ this.sep = "T";
+ this.dsep = "";
+ this.tsep = "";
+ this.tzsep = "";
+ this.tzZulu = "Z";
break;
- case 'w3c':
- this.sep = 'T';
- this.dsep = '-';
- this.tsep = ':';
- this.tzsep = ':';
- this.tzZulu = 'Z';
+ case "w3c":
+ this.sep = "T";
+ this.dsep = "-";
+ this.tsep = ":";
+ this.tzsep = ":";
+ this.tzZulu = "Z";
break;
- case 'html5':
- this.sep = ' ';
- this.dsep = '-';
- this.tsep = ':';
- this.tzsep = ':';
- this.tzZulu = 'Z';
+ case "html5":
+ this.sep = " ";
+ this.dsep = "-";
+ this.tsep = ":";
+ this.tzsep = ":";
+ this.tzZulu = "Z";
break;
default:
// auto - defined by format of input string
this.sep = this.autoProfile.sep;
this.dsep = this.autoProfile.dsep;
this.tsep = this.autoProfile.tsep;
this.tzsep = this.autoProfile.tzsep;
this.tzZulu = this.autoProfile.tzZulu;
@@ -3500,53 +3500,53 @@ var Microformats; // jshint ignore:line
/**
* does text contain am
*
* @param {String} text
* @return {Boolean}
*/
hasAM( text ) {
text = text.toLowerCase();
- return (text.indexOf('am') > -1 || text.indexOf('a.m.') > -1);
+ return (text.indexOf("am") > -1 || text.indexOf("a.m.") > -1);
},
/**
* does text contain pm
*
* @param {String} text
* @return {Boolean}
*/
hasPM( text ) {
text = text.toLowerCase();
- return (text.indexOf('pm') > -1 || text.indexOf('p.m.') > -1);
+ return (text.indexOf("pm") > -1 || text.indexOf("p.m.") > -1);
},
/**
* remove am and pm from text and return it
*
* @param {String} text
* @return {String}
*/
removeAMPM( text ) {
- return text.replace('pm', '').replace('p.m.', '').replace('am', '').replace('a.m.', '');
+ return text.replace("pm", "").replace("p.m.", "").replace("am", "").replace("a.m.", "");
},
/**
* simple test of whether ISO date string is a duration i.e. PY17M or PW12
*
* @param {String} text
* @return {Boolean}
*/
isDuration( text ) {
if (modules.utils.isString( text )) {
text = text.toLowerCase();
- if (modules.utils.startWith(text, 'p') ) {
+ if (modules.utils.startWith(text, "p") ) {
return true;
}
}
return false;
},
/**
@@ -3556,26 +3556,26 @@ var Microformats; // jshint ignore:line
* @param {String} text
* @return {Boolean}
*/
isTime( text ) {
if (modules.utils.isString(text)) {
text = text.toLowerCase();
text = modules.utils.trim( text );
// start with timezone char
- if ( text.match(':') && ( modules.utils.startWith(text, 'z') || modules.utils.startWith(text, '-') || modules.utils.startWith(text, '+') )) {
+ if ( text.match(":") && ( modules.utils.startWith(text, "z") || modules.utils.startWith(text, "-") || modules.utils.startWith(text, "+") )) {
return true;
}
// has ante meridiem or post meridiem
if ( text.match(/^[0-9]/) &&
( this.hasAM(text) || this.hasPM(text) )) {
return true;
}
// contains time delimiter but not datetime delimiter
- if ( text.match(':') && !text.match(/t|\s/) ) {
+ if ( text.match(":") && !text.match(/t|\s/) ) {
return true;
}
// if it's a number of 2, 4 or 6 chars
if (modules.utils.isNumber(text)) {
if (text.length === 2 || text.length === 4 || text.length === 6) {
return true;
}
@@ -3594,43 +3594,43 @@ var Microformats; // jshint ignore:line
*/
parseAmPmTime( text ) {
var out = text,
times = [];
// if the string has a text : or am or pm
if (modules.utils.isString(out)) {
// text = text.toLowerCase();
- text = text.replace(/[ ]+/g, '');
-
- if (text.match(':') || this.hasAM(text) || this.hasPM(text)) {
-
- if (text.match(':')) {
- times = text.split(':');
+ text = text.replace(/[ ]+/g, "");
+
+ if (text.match(":") || this.hasAM(text) || this.hasPM(text)) {
+
+ if (text.match(":")) {
+ times = text.split(":");
} else {
// single number text i.e. 5pm
times[0] = text;
times[0] = this.removeAMPM(times[0]);
}
// change pm hours to 24hr number
if (this.hasPM(text)) {
if (times[0] < 12) {
times[0] = parseInt(times[0], 10) + 12;
}
}
// add leading zero's where needed
if (times[0] && times[0].length === 1) {
- times[0] = '0' + times[0];
+ times[0] = "0" + times[0];
}
// rejoin text elements together
if (times[0]) {
- text = times.join(':');
+ text = times.join(":");
}
}
}
// remove am/pm strings
return this.removeAMPM(text);
},
@@ -3668,48 +3668,48 @@ var Microformats; // jshint ignore:line
*
* @param {Array} arr ( Array of Strings )
* @param {String} format ( Modules.ISODate profile format )
* @return {Object} Modules.ISODate
*/
concatFragments(arr, format) {
var out = new modules.ISODate(),
i = 0,
- value = '';
+ value = "";
// if the fragment already contains a full date just return it once
- if (arr[0].toUpperCase().match('T')) {
+ if (arr[0].toUpperCase().match("T")) {
return new modules.ISODate(arr[0], format);
}
for (i = 0; i < arr.length; i++) {
value = arr[i];
// date pattern
- if ( value.charAt(4) === '-' && out.hasFullDate() === false ) {
+ if ( value.charAt(4) === "-" && out.hasFullDate() === false ) {
out.parseDate(value);
}
// time pattern
- if ( (value.indexOf(':') > -1 || modules.utils.isNumber( this.parseAmPmTime(value) )) && out.hasTime() === false ) {
+ if ( (value.indexOf(":") > -1 || modules.utils.isNumber( this.parseAmPmTime(value) )) && out.hasTime() === false ) {
// split time and timezone
var items = this.splitTimeAndZone(value);
value = items[0];
// parse any use of am/pm
value = this.parseAmPmTime(value);
out.parseTime(value);
// parse any timezone
if (items.length > 1) {
out.parseTimeZone(items[1], format);
}
}
// timezone pattern
- if (value.charAt(0) === '-' || value.charAt(0) === '+' || value.toUpperCase() === 'Z') {
+ if (value.charAt(0) === "-" || value.charAt(0) === "+" || value.toUpperCase() === "Z") {
if ( out.hasTimeZone() === false ) {
out.parseTimeZone(value);
}
}
}
return out;
},
@@ -3718,17 +3718,17 @@ var Microformats; // jshint ignore:line
/**
* parses text by splitting it into an array of time and timezone strings
*
* @param {String} text
* @return {Array} Modules.ISODate
*/
splitTimeAndZone( text ) {
var out = [text],
- chars = ['-', '+', 'z', 'Z'],
+ chars = ["-", "+", "z", "Z"],
i = chars.length;
while (i--) {
if (text.indexOf(chars[i]) > -1) {
out[0] = text.slice( 0, text.indexOf(chars[i]) );
out.push( text.slice( text.indexOf(chars[i]) ) );
break;
}
@@ -3737,112 +3737,112 @@ var Microformats; // jshint ignore:line
}
};
modules.text = {
// normalised or whitespace or whitespacetrimmed
- textFormat: 'whitespacetrimmed',
+ textFormat: "whitespacetrimmed",
// block level tags, used to add line returns
- blockLevelTags: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'hr', 'pre', 'table',
- 'address', 'article', 'aside', 'blockquote', 'caption', 'col', 'colgroup', 'dd', 'div',
- 'dt', 'dir', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'header', 'hgroup', 'hr',
- 'li', 'map', 'menu', 'nav', 'optgroup', 'option', 'section', 'tbody', 'testarea',
- 'tfoot', 'th', 'thead', 'tr', 'td', 'ul', 'ol', 'dl', 'details'],
+ blockLevelTags: ["h1", "h2", "h3", "h4", "h5", "h6", "p", "hr", "pre", "table",
+ "address", "article", "aside", "blockquote", "caption", "col", "colgroup", "dd", "div",
+ "dt", "dir", "fieldset", "figcaption", "figure", "footer", "form", "header", "hgroup", "hr",
+ "li", "map", "menu", "nav", "optgroup", "option", "section", "tbody", "testarea",
+ "tfoot", "th", "thead", "tr", "td", "ul", "ol", "dl", "details"],
// tags to exclude
- excludeTags: ['noframe', 'noscript', 'template', 'script', 'style', 'frames', 'frameset'],
+ excludeTags: ["noframe", "noscript", "template", "script", "style", "frames", "frameset"],
/**
* parses the text from the DOM Node
*
* @param {DOM Node} node
* @param {String} textFormat
* @return {String}
*/
parse(doc, node, textFormat) {
var out;
this.textFormat = (textFormat) ? textFormat : this.textFormat;
- if (this.textFormat === 'normalised') {
+ if (this.textFormat === "normalised") {
out = this.walkTreeForText( node );
if (out !== undefined) {
return this.normalise( doc, out );
}
- return '';
+ return "";
}
return this.formatText( doc, modules.domUtils.textContent(node), this.textFormat );
},
/**
* parses the text from a html string
*
* @param {DOM Document} doc
* @param {String} text
* @param {String} textFormat
* @return {String}
*/
parseText( doc, text, textFormat ) {
- var node = modules.domUtils.createNodeWithText( 'div', text );
+ var node = modules.domUtils.createNodeWithText( "div", text );
return this.parse( doc, node, textFormat );
},
/**
* parses the text from a html string - only for whitespace or whitespacetrimmed formats
*
* @param {String} text
* @param {String} textFormat
* @return {String}
*/
formatText( doc, text, textFormat ) {
this.textFormat = (textFormat) ? textFormat : this.textFormat;
if (text) {
- var out = '',
+ var out = "",
regex = /(<([^>]+)>)/ig;
- out = text.replace(regex, '');
- if (this.textFormat === 'whitespacetrimmed') {
+ out = text.replace(regex, "");
+ if (this.textFormat === "whitespacetrimmed") {
out = modules.utils.trimWhitespace( out );
}
// return entities.decode( out, 2 );
return modules.domUtils.decodeEntities( doc, out );
}
- return '';
+ return "";
},
/**
* normalises whitespace in given text
*
* @param {String} text
* @return {String}
*/
normalise( doc, text ) {
- text = text.replace( / /g, ' ') ; // exchanges html entity for space into space char
+ text = text.replace( / /g, " ") ; // exchanges html entity for space into space char
text = modules.utils.collapseWhiteSpace( text ); // removes linefeeds, tabs and addtional spaces
text = modules.domUtils.decodeEntities( doc, text ); // decode HTML entities
- text = text.replace( '–', '-' ); // correct dash decoding
+ text = text.replace( "–", "-" ); // correct dash decoding
return modules.utils.trim( text );
},
/**
* walks DOM tree parsing the text from DOM Nodes
*
* @param {DOM Node} node
* @return {String}
*/
walkTreeForText( node ) {
- var out = '',
+ var out = "",
j = 0;
if (node.tagName && this.excludeTags.indexOf( node.tagName.toLowerCase() ) > -1) {
return out;
}
// if node is a text node get its text
if (node.nodeType && node.nodeType === 3) {
@@ -3856,39 +3856,39 @@ var Microformats; // jshint ignore:line
if (text !== undefined) {
out += text;
}
}
}
// if it's a block level tag add an additional space at the end
if (node.tagName && this.blockLevelTags.indexOf( node.tagName.toLowerCase() ) !== -1) {
- out += ' ';
+ out += " ";
}
- return (out === '') ? undefined : out ;
+ return (out === "") ? undefined : out ;
}
};
modules.html = {
// elements which are self-closing
- selfClosingElt: ['area', 'base', 'br', 'col', 'hr', 'img', 'input', 'link', 'meta', 'param', 'command', 'keygen', 'source'],
+ selfClosingElt: ["area", "base", "br", "col", "hr", "img", "input", "link", "meta", "param", "command", "keygen", "source"],
/**
* parse the html string from DOM Node
*
* @param {DOM Node} node
* @return {String}
*/
parse( node ) {
- var out = '',
+ var out = "",
j = 0;
// we do not want the outer container
if (node.childNodes && node.childNodes.length > 0) {
for (j = 0; j < node.childNodes.length; j++) {
var text = this.walkTreeForHtml( node.childNodes[j] );
if (text !== undefined) {
out += text;
@@ -3903,563 +3903,563 @@ var Microformats; // jshint ignore:line
/**
* walks the DOM tree parsing the html string from the nodes
*
* @param {DOM Document} doc
* @param {DOM Node} node
* @return {String}
*/
walkTreeForHtml( node ) {
- var out = '',
+ var out = "",
j = 0;
// if node is a text node get its text
if (node.nodeType && node.nodeType === 3) {
out += modules.domUtils.getElementText( node );
}
// exclude text which has been added with include pattern -
- if (node.nodeType && node.nodeType === 1 && modules.domUtils.hasAttribute(node, 'data-include') === false) {
+ if (node.nodeType && node.nodeType === 1 && modules.domUtils.hasAttribute(node, "data-include") === false) {
// begin tag
- out += '<' + node.tagName.toLowerCase();
+ out += "<" + node.tagName.toLowerCase();
// add attributes
var attrs = modules.domUtils.getOrderedAttributes(node);
for (j = 0; j < attrs.length; j++) {
- out += ' ' + attrs[j].name + '=' + '"' + attrs[j].value + '"';
+ out += " " + attrs[j].name + "=" + '"' + attrs[j].value + '"';
}
if (this.selfClosingElt.indexOf(node.tagName.toLowerCase()) === -1) {
- out += '>';
+ out += ">";
}
// get the text of the child nodes
if (node.childNodes && node.childNodes.length > 0) {
for (j = 0; j < node.childNodes.length; j++) {
var text = this.walkTreeForHtml( node.childNodes[j] );
if (text !== undefined) {
out += text;
}
}
}
// end tag
if (this.selfClosingElt.indexOf(node.tagName.toLowerCase()) > -1) {
- out += ' />';
+ out += " />";
} else {
- out += '</' + node.tagName.toLowerCase() + '>';
+ out += "</" + node.tagName.toLowerCase() + ">";
}
}
- return (out === '') ? undefined : out;
+ return (out === "") ? undefined : out;
}
};
- modules.maps['h-adr'] = {
- root: 'adr',
- name: 'h-adr',
+ modules.maps["h-adr"] = {
+ root: "adr",
+ name: "h-adr",
properties: {
- 'post-office-box': {},
- 'street-address': {},
- 'extended-address': {},
- 'locality': {},
- 'region': {},
- 'postal-code': {},
- 'country-name': {}
+ "post-office-box": {},
+ "street-address": {},
+ "extended-address": {},
+ "locality": {},
+ "region": {},
+ "postal-code": {},
+ "country-name": {}
}
};
- modules.maps['h-card'] = {
- root: 'vcard',
- name: 'h-card',
+ modules.maps["h-card"] = {
+ root: "vcard",
+ name: "h-card",
properties: {
- 'fn': {
- 'map': 'p-name'
+ "fn": {
+ "map": "p-name"
},
- 'adr': {
- 'map': 'p-adr',
- 'uf': ['h-adr']
+ "adr": {
+ "map": "p-adr",
+ "uf": ["h-adr"]
},
- 'agent': {
- 'uf': ['h-card']
+ "agent": {
+ "uf": ["h-card"]
},
- 'bday': {
- 'map': 'dt-bday'
+ "bday": {
+ "map": "dt-bday"
},
- 'class': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "class": {},
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'email': {
- 'map': 'u-email'
+ "email": {
+ "map": "u-email"
},
- 'geo': {
- 'map': 'p-geo',
- 'uf': ['h-geo']
+ "geo": {
+ "map": "p-geo",
+ "uf": ["h-geo"]
},
- 'key': {
- 'map': 'u-key'
+ "key": {
+ "map": "u-key"
},
- 'label': {},
- 'logo': {
- 'map': 'u-logo'
+ "label": {},
+ "logo": {
+ "map": "u-logo"
},
- 'mailer': {},
- 'honorific-prefix': {},
- 'given-name': {},
- 'additional-name': {},
- 'family-name': {},
- 'honorific-suffix': {},
- 'nickname': {},
- 'note': {}, // could be html i.e. e-note
- 'org': {},
- 'p-organization-name': {},
- 'p-organization-unit': {},
- 'photo': {
- 'map': 'u-photo'
+ "mailer": {},
+ "honorific-prefix": {},
+ "given-name": {},
+ "additional-name": {},
+ "family-name": {},
+ "honorific-suffix": {},
+ "nickname": {},
+ "note": {}, // could be html i.e. e-note
+ "org": {},
+ "p-organization-name": {},
+ "p-organization-unit": {},
+ "photo": {
+ "map": "u-photo"
},
- 'rev': {
- 'map': 'dt-rev'
+ "rev": {
+ "map": "dt-rev"
},
- 'role': {},
- 'sequence': {},
- 'sort-string': {},
- 'sound': {
- 'map': 'u-sound'
+ "role": {},
+ "sequence": {},
+ "sort-string": {},
+ "sound": {
+ "map": "u-sound"
},
- 'title': {
- 'map': 'p-job-title'
+ "title": {
+ "map": "p-job-title"
},
- 'tel': {},
- 'tz': {},
- 'uid': {
- 'map': 'u-uid'
+ "tel": {},
+ "tz": {},
+ "uid": {
+ "map": "u-uid"
},
- 'url': {
- 'map': 'u-url'
+ "url": {
+ "map": "u-url"
}
}
};
- modules.maps['h-entry'] = {
- root: 'hentry',
- name: 'h-entry',
+ modules.maps["h-entry"] = {
+ root: "hentry",
+ name: "h-entry",
properties: {
- 'entry-title': {
- 'map': 'p-name'
+ "entry-title": {
+ "map": "p-name"
},
- 'entry-summary': {
- 'map': 'p-summary'
+ "entry-summary": {
+ "map": "p-summary"
},
- 'entry-content': {
- 'map': 'e-content'
+ "entry-content": {
+ "map": "e-content"
},
- 'published': {
- 'map': 'dt-published'
+ "published": {
+ "map": "dt-published"
},
- 'updated': {
- 'map': 'dt-updated'
+ "updated": {
+ "map": "dt-updated"
},
- 'author': {
- 'uf': ['h-card']
+ "author": {
+ "uf": ["h-card"]
},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'geo': {
- 'map': 'p-geo',
- 'uf': ['h-geo']
+ "geo": {
+ "map": "p-geo",
+ "uf": ["h-geo"]
},
- 'latitude': {},
- 'longitude': {},
- 'url': {
- 'map': 'u-url',
- 'relAlt': ['bookmark']
+ "latitude": {},
+ "longitude": {},
+ "url": {
+ "map": "u-url",
+ "relAlt": ["bookmark"]
}
}
};
- modules.maps['h-event'] = {
- root: 'vevent',
- name: 'h-event',
+ modules.maps["h-event"] = {
+ root: "vevent",
+ name: "h-event",
properties: {
- 'summary': {
- 'map': 'p-name'
+ "summary": {
+ "map": "p-name"
},
- 'dtstart': {
- 'map': 'dt-start'
+ "dtstart": {
+ "map": "dt-start"
},
- 'dtend': {
- 'map': 'dt-end'
+ "dtend": {
+ "map": "dt-end"
},
- 'description': {},
- 'url': {
- 'map': 'u-url'
+ "description": {},
+ "url": {
+ "map": "u-url"
},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'location': {
- 'uf': ['h-card']
+ "location": {
+ "uf": ["h-card"]
},
- 'geo': {
- 'uf': ['h-geo']
+ "geo": {
+ "uf": ["h-geo"]
},
- 'latitude': {},
- 'longitude': {},
- 'duration': {
- 'map': 'dt-duration'
+ "latitude": {},
+ "longitude": {},
+ "duration": {
+ "map": "dt-duration"
},
- 'contact': {
- 'uf': ['h-card']
+ "contact": {
+ "uf": ["h-card"]
},
- 'organizer': {
- 'uf': ['h-card']},
- 'attendee': {
- 'uf': ['h-card']},
- 'uid': {
- 'map': 'u-uid'
+ "organizer": {
+ "uf": ["h-card"]},
+ "attendee": {
+ "uf": ["h-card"]},
+ "uid": {
+ "map": "u-uid"
},
- 'attach': {
- 'map': 'u-attach'
+ "attach": {
+ "map": "u-attach"
},
- 'status': {},
- 'rdate': {},
- 'rrule': {}
+ "status": {},
+ "rdate": {},
+ "rrule": {}
}
};
- modules.maps['h-feed'] = {
- root: 'hfeed',
- name: 'h-feed',
+ modules.maps["h-feed"] = {
+ root: "hfeed",
+ name: "h-feed",
properties: {
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'summary': {
- 'map': 'p-summary'
+ "summary": {
+ "map": "p-summary"
},
- 'author': {
- 'uf': ['h-card']
+ "author": {
+ "uf": ["h-card"]
},
- 'url': {
- 'map': 'u-url'
+ "url": {
+ "map": "u-url"
},
- 'photo': {
- 'map': 'u-photo'
+ "photo": {
+ "map": "u-photo"
},
}
};
- modules.maps['h-geo'] = {
- root: 'geo',
- name: 'h-geo',
+ modules.maps["h-geo"] = {
+ root: "geo",
+ name: "h-geo",
properties: {
- 'latitude': {},
- 'longitude': {}
+ "latitude": {},
+ "longitude": {}
}
};
- modules.maps['h-item'] = {
- root: 'item',
- name: 'h-item',
+ modules.maps["h-item"] = {
+ root: "item",
+ name: "h-item",
subTree: false,
properties: {
- 'fn': {
- 'map': 'p-name'
+ "fn": {
+ "map": "p-name"
},
- 'url': {
- 'map': 'u-url'
+ "url": {
+ "map": "u-url"
},
- 'photo': {
- 'map': 'u-photo'
+ "photo": {
+ "map": "u-photo"
}
}
};
- modules.maps['h-listing'] = {
- root: 'hlisting',
- name: 'h-listing',
+ modules.maps["h-listing"] = {
+ root: "hlisting",
+ name: "h-listing",
properties: {
- 'version': {},
- 'lister': {
- 'uf': ['h-card']
+ "version": {},
+ "lister": {
+ "uf": ["h-card"]
},
- 'dtlisted': {
- 'map': 'dt-listed'
+ "dtlisted": {
+ "map": "dt-listed"
},
- 'dtexpired': {
- 'map': 'dt-expired'
+ "dtexpired": {
+ "map": "dt-expired"
},
- 'location': {},
- 'price': {},
- 'item': {
- 'uf': ['h-card', 'a-adr', 'h-geo']
+ "location": {},
+ "price": {},
+ "item": {
+ "uf": ["h-card", "a-adr", "h-geo"]
},
- 'summary': {
- 'map': 'p-name'
+ "summary": {
+ "map": "p-name"
},
- 'description': {
- 'map': 'e-description'
+ "description": {
+ "map": "e-description"
},
- 'listing': {}
+ "listing": {}
}
};
- modules.maps['h-news'] = {
- root: 'hnews',
- name: 'h-news',
+ modules.maps["h-news"] = {
+ root: "hnews",
+ name: "h-news",
properties: {
- 'entry': {
- 'uf': ['h-entry']
+ "entry": {
+ "uf": ["h-entry"]
},
- 'geo': {
- 'uf': ['h-geo']
+ "geo": {
+ "uf": ["h-geo"]
},
- 'latitude': {},
- 'longitude': {},
- 'source-org': {
- 'uf': ['h-card']
+ "latitude": {},
+ "longitude": {},
+ "source-org": {
+ "uf": ["h-card"]
},
- 'dateline': {
- 'uf': ['h-card']
+ "dateline": {
+ "uf": ["h-card"]
},
- 'item-license': {
- 'map': 'u-item-license'
+ "item-license": {
+ "map": "u-item-license"
},
- 'principles': {
- 'map': 'u-principles',
- 'relAlt': ['principles']
+ "principles": {
+ "map": "u-principles",
+ "relAlt": ["principles"]
}
}
};
- modules.maps['h-org'] = {
- root: 'h-x-org', // drop this from v1 as it causes issue with fn org hcard pattern
- name: 'h-org',
+ modules.maps["h-org"] = {
+ root: "h-x-org", // drop this from v1 as it causes issue with fn org hcard pattern
+ name: "h-org",
childStructure: true,
properties: {
- 'organization-name': {},
- 'organization-unit': {}
+ "organization-name": {},
+ "organization-unit": {}
}
};
- modules.maps['h-product'] = {
- root: 'hproduct',
- name: 'h-product',
+ modules.maps["h-product"] = {
+ root: "hproduct",
+ name: "h-product",
properties: {
- 'brand': {
- 'uf': ['h-card']
+ "brand": {
+ "uf": ["h-card"]
},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'price': {},
- 'description': {
- 'map': 'e-description'
+ "price": {},
+ "description": {
+ "map": "e-description"
},
- 'fn': {
- 'map': 'p-name'
+ "fn": {
+ "map": "p-name"
},
- 'photo': {
- 'map': 'u-photo'
+ "photo": {
+ "map": "u-photo"
},
- 'url': {
- 'map': 'u-url'
+ "url": {
+ "map": "u-url"
},
- 'review': {
- 'uf': ['h-review', 'h-review-aggregate']
+ "review": {
+ "uf": ["h-review", "h-review-aggregate"]
},
- 'listing': {
- 'uf': ['h-listing']
+ "listing": {
+ "uf": ["h-listing"]
},
- 'identifier': {
- 'map': 'u-identifier'
+ "identifier": {
+ "map": "u-identifier"
}
}
};
- modules.maps['h-recipe'] = {
- root: 'hrecipe',
- name: 'h-recipe',
+ modules.maps["h-recipe"] = {
+ root: "hrecipe",
+ name: "h-recipe",
properties: {
- 'fn': {
- 'map': 'p-name'
+ "fn": {
+ "map": "p-name"
},
- 'ingredient': {
- 'map': 'e-ingredient'
+ "ingredient": {
+ "map": "e-ingredient"
},
- 'yield': {},
- 'instructions': {
- 'map': 'e-instructions'
+ "yield": {},
+ "instructions": {
+ "map": "e-instructions"
},
- 'duration': {
- 'map': 'dt-duration'
+ "duration": {
+ "map": "dt-duration"
},
- 'photo': {
- 'map': 'u-photo'
+ "photo": {
+ "map": "u-photo"
},
- 'summary': {},
- 'author': {
- 'uf': ['h-card']
+ "summary": {},
+ "author": {
+ "uf": ["h-card"]
},
- 'published': {
- 'map': 'dt-published'
+ "published": {
+ "map": "dt-published"
},
- 'nutrition': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "nutrition": {},
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
}
};
- modules.maps['h-resume'] = {
- root: 'hresume',
- name: 'h-resume',
+ modules.maps["h-resume"] = {
+ root: "hresume",
+ name: "h-resume",
properties: {
- 'summary': {},
- 'contact': {
- 'uf': ['h-card']
+ "summary": {},
+ "contact": {
+ "uf": ["h-card"]
},
- 'education': {
- 'uf': ['h-card', 'h-event']
+ "education": {
+ "uf": ["h-card", "h-event"]
},
- 'experience': {
- 'uf': ['h-card', 'h-event']
+ "experience": {
+ "uf": ["h-card", "h-event"]
},
- 'skill': {},
- 'affiliation': {
- 'uf': ['h-card']
+ "skill": {},
+ "affiliation": {
+ "uf": ["h-card"]
}
}
};
- modules.maps['h-review-aggregate'] = {
- root: 'hreview-aggregate',
- name: 'h-review-aggregate',
+ modules.maps["h-review-aggregate"] = {
+ root: "hreview-aggregate",
+ name: "h-review-aggregate",
properties: {
- 'summary': {
- 'map': 'p-name'
+ "summary": {
+ "map": "p-name"
},
- 'item': {
- 'map': 'p-item',
- 'uf': ['h-item', 'h-geo', 'h-adr', 'h-card', 'h-event', 'h-product']
+ "item": {
+ "map": "p-item",
+ "uf": ["h-item", "h-geo", "h-adr", "h-card", "h-event", "h-product"]
},
- 'rating': {},
- 'average': {},
- 'best': {},
- 'worst': {},
- 'count': {},
- 'votes': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "rating": {},
+ "average": {},
+ "best": {},
+ "worst": {},
+ "count": {},
+ "votes": {},
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'url': {
- 'map': 'u-url',
- 'relAlt': ['self', 'bookmark']
+ "url": {
+ "map": "u-url",
+ "relAlt": ["self", "bookmark"]
}
}
};
- modules.maps['h-review'] = {
- root: 'hreview',
- name: 'h-review',
+ modules.maps["h-review"] = {
+ root: "hreview",
+ name: "h-review",
properties: {
- 'summary': {
- 'map': 'p-name'
+ "summary": {
+ "map": "p-name"
},
- 'description': {
- 'map': 'e-description'
+ "description": {
+ "map": "e-description"
},
- 'item': {
- 'map': 'p-item',
- 'uf': ['h-item', 'h-geo', 'h-adr', 'h-card', 'h-event', 'h-product']
+ "item": {
+ "map": "p-item",
+ "uf": ["h-item", "h-geo", "h-adr", "h-card", "h-event", "h-product"]
},
- 'reviewer': {
- 'uf': ['h-card']
+ "reviewer": {
+ "uf": ["h-card"]
},
- 'dtreviewer': {
- 'map': 'dt-reviewer'
+ "dtreviewer": {
+ "map": "dt-reviewer"
},
- 'rating': {},
- 'best': {},
- 'worst': {},
- 'category': {
- 'map': 'p-category',
- 'relAlt': ['tag']
+ "rating": {},
+ "best": {},
+ "worst": {},
+ "category": {
+ "map": "p-category",
+ "relAlt": ["tag"]
},
- 'url': {
- 'map': 'u-url',
- 'relAlt': ['self', 'bookmark']
+ "url": {
+ "map": "u-url",
+ "relAlt": ["self", "bookmark"]
}
}
};
modules.rels = {
// xfn
- 'friend': [ 'yes', 'external'],
- 'acquaintance': [ 'yes', 'external'],
- 'contact': [ 'yes', 'external'],
- 'met': [ 'yes', 'external'],
- 'co-worker': [ 'yes', 'external'],
- 'colleague': [ 'yes', 'external'],
- 'co-resident': [ 'yes', 'external'],
- 'neighbor': [ 'yes', 'external'],
- 'child': [ 'yes', 'external'],
- 'parent': [ 'yes', 'external'],
- 'sibling': [ 'yes', 'external'],
- 'spouse': [ 'yes', 'external'],
- 'kin': [ 'yes', 'external'],
- 'muse': [ 'yes', 'external'],
- 'crush': [ 'yes', 'external'],
- 'date': [ 'yes', 'external'],
- 'sweetheart': [ 'yes', 'external'],
- 'me': [ 'yes', 'external'],
+ "friend": [ "yes", "external"],
+ "acquaintance": [ "yes", "external"],
+ "contact": [ "yes", "external"],
+ "met": [ "yes", "external"],
+ "co-worker": [ "yes", "external"],
+ "colleague": [ "yes", "external"],
+ "co-resident": [ "yes", "external"],
+ "neighbor": [ "yes", "external"],
+ "child": [ "yes", "external"],
+ "parent": [ "yes", "external"],
+ "sibling": [ "yes", "external"],
+ "spouse": [ "yes", "external"],
+ "kin": [ "yes", "external"],
+ "muse": [ "yes", "external"],
+ "crush": [ "yes", "external"],
+ "date": [ "yes", "external"],
+ "sweetheart": [ "yes", "external"],
+ "me": [ "yes", "external"],
// other rel=*
- 'license': [ 'yes', 'yes'],
- 'nofollow': [ 'no', 'external'],
- 'tag': [ 'no', 'yes'],
- 'self': [ 'no', 'external'],
- 'bookmark': [ 'no', 'external'],
- 'author': [ 'no', 'external'],
- 'home': [ 'no', 'external'],
- 'directory': [ 'no', 'external'],
- 'enclosure': [ 'no', 'external'],
- 'pronunciation': [ 'no', 'external'],
- 'payment': [ 'no', 'external'],
- 'principles': [ 'no', 'external']
+ "license": [ "yes", "yes"],
+ "nofollow": [ "no", "external"],
+ "tag": [ "no", "yes"],
+ "self": [ "no", "external"],
+ "bookmark": [ "no", "external"],
+ "author": [ "no", "external"],
+ "home": [ "no", "external"],
+ "directory": [ "no", "external"],
+ "enclosure": [ "no", "external"],
+ "pronunciation": [ "no", "external"],
+ "payment": [ "no", "external"],
+ "principles": [ "no", "external"]
};
var External = {
version: modules.version,
livingStandard: modules.livingStandard
@@ -4515,9 +4515,9 @@ var Microformats; // jshint ignore:line
return External;
}));
try {
// mozilla jsm support
Components.utils.importGlobalProperties(["URL"]);
} catch (e) {}
-this.EXPORTED_SYMBOLS = ['Microformats'];
+this.EXPORTED_SYMBOLS = ["Microformats"];
--- a/toolkit/components/microformats/update/update.js
+++ b/toolkit/components/microformats/update/update.js
@@ -13,61 +13,61 @@
* test/standards-tests
* test/static
Copyright (C) 2015 Glenn Jones. All Rights Reserved.
MIT License: https://raw.github.com/glennjones/microformat-shiv/master/license.txt
*/
// configuration
-var deployDir = '../'
+var deployDir = "../"
exportedSymbol = 'try {\n // mozilla jsm support\n Components.utils.importGlobalProperties(["URL"]);\n} catch(e) {}\nthis.EXPORTED_SYMBOLS = [\'Microformats\'];';
-var path = require('path'),
- request = require('request'),
- fs = require('fs-extra'),
- download = require('download-github-repo');
+var path = require("path"),
+ request = require("request"),
+ fs = require("fs-extra"),
+ download = require("download-github-repo");
-var repo = 'glennjones/microformat-shiv',
- tempDir = path.resolve(__dirname, 'temp-repo'),
+var repo = "glennjones/microformat-shiv",
+ tempDir = path.resolve(__dirname, "temp-repo"),
deployDirResolved = path.resolve(__dirname, deployDir),
pathList = [
- ['/modern/microformat-shiv-modern.js', '/microformat-shiv.js'],
- ['/lib', '/test/lib'],
- ['/test/interface-tests', '/test/interface-tests'],
- ['/test/module-tests', '/test/module-tests'],
- ['/test/standards-tests', '/test/standards-tests'],
- ['/test/static', '/test/static']
+ ["/modern/microformat-shiv-modern.js", "/microformat-shiv.js"],
+ ["/lib", "/test/lib"],
+ ["/test/interface-tests", "/test/interface-tests"],
+ ["/test/module-tests", "/test/module-tests"],
+ ["/test/standards-tests", "/test/standards-tests"],
+ ["/test/static", "/test/static"]
];
getLastBuildState( repo, function( err, buildState) {
if (buildState) {
- console.log('last build state:', buildState);
+ console.log("last build state:", buildState);
- if (buildState === 'passed') {
+ if (buildState === "passed") {
- console.log('downloading git repo', repo);
+ console.log("downloading git repo", repo);
getLastCommitDate( repo, function( err, date) {
if (date) {
- console.log( 'last commit:', new Date(date).toString() );
+ console.log( "last commit:", new Date(date).toString() );
}
});
updateFromRepo();
} else {
- console.log('not updating because of build state is failing please contact Glenn Jones glennjones@gmail.com');
+ console.log("not updating because of build state is failing please contact Glenn Jones glennjones@gmail.com");
}
} else {
- console.log('could not get build state from travis-ci:', err);
+ console.log("could not get build state from travis-ci:", err);
}
});
/**
* updates from directories and files from repo
*
*/
@@ -78,189 +78,189 @@ function updateFromRepo() {
if ( fs.existsSync( tempDir ) ) {
var version = getRepoVersion();
removeCurrentFiles( pathList, deployDirResolved );
addNewFiles( pathList, deployDirResolved );
fs.removeSync(tempDir);
// changes files for firefox
- replaceInFile('/test/module-tests/index.html', /..\/..\/lib\//g, '../lib/' );
- addExportedSymbol( '/microformat-shiv.js' );
+ replaceInFile("/test/module-tests/index.html", /..\/..\/lib\//g, "../lib/" );
+ addExportedSymbol( "/microformat-shiv.js" );
- console.log('microformat-shiv is now uptodate to v' + version);
+ console.log("microformat-shiv is now uptodate to v" + version);
} else {
- console.log('error getting repo', err);
+ console.log("error getting repo", err);
}
});
}
/**
* removes old version of delpoyed directories and files
*
* @param {Array} pathList
* @param {String} deployDirResolved
*/
function removeCurrentFiles( pathList, deployDirResolved ) {
pathList.forEach( function( path ) {
- console.log('removed:', deployDirResolved + path[1]);
+ console.log("removed:", deployDirResolved + path[1]);
fs.removeSync(deployDirResolved + path[1]);
});
}
/**
* copies over required directories and files into deployed path
*
* @param {Array} pathList
* @param {String} deployDirResolved
*/
function addNewFiles( pathList, deployDirResolved ) {
pathList.forEach( function( path ) {
- console.log('added:', deployDirResolved + path[1]);
+ console.log("added:", deployDirResolved + path[1]);
fs.copySync(tempDir + path[0], deployDirResolved + path[1]);
});
}
/**
* gets the repo version number
*
* @return {String}
*/
function getRepoVersion() {
- var pack = fs.readFileSync(path.resolve(tempDir, 'package.json'), {encoding: 'utf8'});
+ var pack = fs.readFileSync(path.resolve(tempDir, "package.json"), {encoding: "utf8"});
if (pack) {
pack = JSON.parse(pack)
if (pack && pack.version) {
return pack.version;
}
}
- return '';
+ return "";
}
/**
* get the last commit date from github repo
*
* @param {String} repo
* @param {Function} callback
*/
function getLastCommitDate( repo, callback ) {
var options = {
- url: 'https://api.github.com/repos/' + repo + '/commits?per_page=1',
+ url: "https://api.github.com/repos/" + repo + "/commits?per_page=1",
headers: {
- 'User-Agent': 'request'
+ "User-Agent": "request"
}
};
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
var date = null,
json = JSON.parse(body);
if (json && json.length && json[0].commit && json[0].commit.author ) {
date = json[0].commit.author.date;
}
callback(null, date);
} else {
console.log(error, response, body);
- callback('fail to get last commit date', null);
+ callback("fail to get last commit date", null);
}
});
}
/**
* get the last build state from travis-ci
*
* @param {String} repo
* @param {Function} callback
*/
function getLastBuildState( repo, callback ) {
var options = {
- url: 'https://api.travis-ci.org/repos/' + repo,
+ url: "https://api.travis-ci.org/repos/" + repo,
headers: {
- 'User-Agent': 'request',
- 'Accept': 'application/vnd.travis-ci.2+json'
+ "User-Agent": "request",
+ "Accept": "application/vnd.travis-ci.2+json"
}
};
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
var buildState = null,
json = JSON.parse(body);
if (json && json.repo && json.repo.last_build_state ) {
buildState = json.repo.last_build_state;
}
callback(null, buildState);
} else {
console.log(error, response, body);
- callback('fail to get last build state', null);
+ callback("fail to get last build state", null);
}
});
}
/**
* adds exported symbol to microformat-shiv.js file
*
* @param {String} path
* @param {String} content
*/
function addExportedSymbol( path ) {
- if (path === '/microformat-shiv.js') {
- fs.appendFileSync(deployDirResolved + '/microformat-shiv.js', '\r\n' + exportedSymbol + '\r\n');
- console.log('appended exported symbol to microformat-shiv.js');
+ if (path === "/microformat-shiv.js") {
+ fs.appendFileSync(deployDirResolved + "/microformat-shiv.js", "\r\n" + exportedSymbol + "\r\n");
+ console.log("appended exported symbol to microformat-shiv.js");
}
}
/**
* adds exported symbol to microformat-shiv.js file
*
* @param {String} path
* @param {String} content
*/
function replaceInFile( path, findStr, replaceStr ) {
readFile(deployDirResolved + path, function(err, fileStr) {
if (fileStr) {
fileStr = fileStr.replace(findStr, replaceStr)
writeFile(deployDirResolved + path, fileStr);
- console.log('replaced ' + findStr + ' with ' + replaceStr + ' in ' + path);
+ console.log("replaced " + findStr + " with " + replaceStr + " in " + path);
} else {
- console.log('error replaced strings in ' + path);
+ console.log("error replaced strings in " + path);
}
})
}
/**
* write a file
*
* @param {String} path
* @param {String} content
*/
function writeFile(path, content) {
- fs.writeFile(path, content, 'utf8', function(err) {
+ fs.writeFile(path, content, "utf8", function(err) {
if (err) {
console.log(err);
} else {
- console.log('The file: ' + path + ' was saved');
+ console.log("The file: " + path + " was saved");
}
});
}
/**
* read a file
*
* @param {String} path
* @param {Function} callback
*/
function readFile(path, callback) {
- fs.readFile(path, 'utf8', callback);
+ fs.readFile(path, "utf8", callback);
}
--- a/toolkit/components/passwordmgr/LoginHelper.jsm
+++ b/toolkit/components/passwordmgr/LoginHelper.jsm
@@ -618,17 +618,17 @@ this.LoginHelper = {
},
/**
* Same as above, but for a single login.
*/
loginToVanillaObject(login) {
let obj = {};
for (let i in login.QueryInterface(Ci.nsILoginMetaInfo)) {
- if (typeof login[i] !== 'function') {
+ if (typeof login[i] !== "function") {
obj[i] = login[i];
}
}
return obj;
},
/**
--- a/toolkit/components/passwordmgr/nsLoginManagerPrompter.js
+++ b/toolkit/components/passwordmgr/nsLoginManagerPrompter.js
@@ -964,17 +964,17 @@ LoginManagerPrompter.prototype = {
// The main action is the "Save" or "Update" button.
let mainAction = {
label: this._getLocalizedString(initialMsgNames.buttonLabel),
accessKey: this._getLocalizedString(initialMsgNames.buttonAccessKey),
callback: () => {
histogram.add(PROMPT_ADD_OR_UPDATE);
if (histogramName == "PWMGR_PROMPT_REMEMBER_ACTION") {
- Services.obs.notifyObservers(null, 'LoginStats:NewSavedPassword', null);
+ Services.obs.notifyObservers(null, "LoginStats:NewSavedPassword", null);
}
readDataFromUI();
persistData();
browser.focus();
}
};
let secondaryActions = [{
--- a/toolkit/components/passwordmgr/storage-json.js
+++ b/toolkit/components/passwordmgr/storage-json.js
@@ -378,17 +378,17 @@ this.LoginManagerStorage_json.prototype
findLogins(count, hostname, formSubmitURL, httpRealm) {
let loginData = {
hostname,
formSubmitURL,
httpRealm
};
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
- if (loginData[field] != '')
+ if (loginData[field] != "")
matchData[field] = loginData[field];
let [logins, ids] = this._searchLogins(matchData);
// Decrypt entries found for the caller.
logins = this._decryptLogins(logins);
this.log("_findLogins: returning", logins.length, "logins");
count.value = logins.length; // needed for XPCOM
@@ -398,17 +398,17 @@ this.LoginManagerStorage_json.prototype
countLogins(hostname, formSubmitURL, httpRealm) {
let loginData = {
hostname,
formSubmitURL,
httpRealm
};
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
- if (loginData[field] != '')
+ if (loginData[field] != "")
matchData[field] = loginData[field];
let [logins, ids] = this._searchLogins(matchData);
this.log("_countLogins: counted logins:", logins.length);
return logins.length;
},
get uiBusy() {
@@ -422,17 +422,17 @@ this.LoginManagerStorage_json.prototype
/**
* Returns an array with two items: [id, login]. If the login was not
* found, both items will be null. The returned login contains the actual
* stored login (useful for looking at the actual nsILoginMetaInfo values).
*/
_getIdForLogin(login) {
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
- if (login[field] != '')
+ if (login[field] != "")
matchData[field] = login[field];
let [logins, ids] = this._searchLogins(matchData);
let id = null;
let foundLogin = null;
// The specified login isn't encrypted, so we need to ensure
// the logins we're comparing with are decrypted. We decrypt one entry
--- a/toolkit/components/passwordmgr/storage-mozStorage.js
+++ b/toolkit/components/passwordmgr/storage-mozStorage.js
@@ -603,17 +603,17 @@ LoginManagerStorage_mozStorage.prototype
findLogins(count, hostname, formSubmitURL, httpRealm) {
let loginData = {
hostname,
formSubmitURL,
httpRealm
};
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
- if (loginData[field] != '')
+ if (loginData[field] != "")
matchData[field] = loginData[field];
let [logins, ids] = this._searchLogins(matchData);
// Decrypt entries found for the caller.
logins = this._decryptLogins(logins);
this.log("_findLogins: returning " + logins.length + " logins");
count.value = logins.length; // needed for XPCOM
@@ -668,17 +668,17 @@ LoginManagerStorage_mozStorage.prototype
/**
* Returns an array with two items: [id, login]. If the login was not
* found, both items will be null. The returned login contains the actual
* stored login (useful for looking at the actual nsILoginMetaInfo values).
*/
_getIdForLogin(login) {
let matchData = { };
for (let field of ["hostname", "formSubmitURL", "httpRealm"])
- if (login[field] != '')
+ if (login[field] != "")
matchData[field] = login[field];
let [logins, ids] = this._searchLogins(matchData);
let id = null;
let foundLogin = null;
// The specified login isn't encrypted, so we need to ensure
// the logins we're comparing with are decrypted. We decrypt one entry
@@ -705,31 +705,31 @@ LoginManagerStorage_mozStorage.prototype
* statement being created. This fixes the cases where nulls are involved
* and the empty string is supposed to be a wildcard match
*/
_buildConditionsAndParams(hostname, formSubmitURL, httpRealm) {
let conditions = [], params = {};
if (hostname == null) {
conditions.push("hostname isnull");
- } else if (hostname != '') {
+ } else if (hostname != "") {
conditions.push("hostname = :hostname");
params["hostname"] = hostname;
}
if (formSubmitURL == null) {
conditions.push("formSubmitURL isnull");
- } else if (formSubmitURL != '') {
+ } else if (formSubmitURL != "") {
conditions.push("formSubmitURL = :formSubmitURL OR formSubmitURL = ''");
params["formSubmitURL"] = formSubmitURL;
}
if (httpRealm == null) {
conditions.push("httpRealm isnull");
- } else if (httpRealm != '') {
+ } else if (httpRealm != "") {
conditions.push("httpRealm = :httpRealm");
params["httpRealm"] = httpRealm;
}
return [conditions, params];
},
@@ -1014,18 +1014,18 @@ LoginManagerStorage_mozStorage.prototype
let stmt;
query = "SELECT id, encryptedUsername, encryptedPassword " +
"FROM moz_logins WHERE encType isnull";
try {
stmt = this._dbCreateStatement(query);
while (stmt.executeStep()) {
let params = { id: stmt.row.id };
// We will tag base64 logins correctly, but no longer support their use.
- if (stmt.row.encryptedUsername.charAt(0) == '~' ||
- stmt.row.encryptedPassword.charAt(0) == '~')
+ if (stmt.row.encryptedUsername.charAt(0) == "~" ||
+ stmt.row.encryptedPassword.charAt(0) == "~")
params.encType = Ci.nsILoginManagerCrypto.ENCTYPE_BASE64;
else
params.encType = Ci.nsILoginManagerCrypto.ENCTYPE_SDR;
logins.push(params);
}
} catch (e) {
this.log("Failed getting logins: " + e);
throw e;
--- a/toolkit/components/passwordmgr/test/browser/browser_context_menu.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_context_menu.js
@@ -154,17 +154,17 @@ add_task(function* test_context_menu_pas
});
if (contextMenu.state != "open") {
continue;
}
// The only field affected by the password fill
// should be the target password field itself.
- let unchangedFields = form.querySelectorAll('input:not(#' + passwordField.id + ')');
+ let unchangedFields = form.querySelectorAll("input:not(#" + passwordField.id + ")");
yield assertContextMenuFill(form, null, passwordField, unchangedFields, 1);
Assert.equal(passwordField.value, "password1", "Check upgraded login was actually used");
contextMenu.hidePopup();
}
}
});
});
@@ -213,17 +213,17 @@ add_task(function* test_context_menu_use
}
return true;
});
if (contextMenu.state != "open") {
continue;
}
// We shouldn't change any field that's not the target username field or the first password field
- let unchangedFields = form.querySelectorAll('input:not(#' + usernameField.id + '):not(#' + passwordField.id + ')');
+ let unchangedFields = form.querySelectorAll("input:not(#" + usernameField.id + "):not(#" + passwordField.id + ")");
yield assertContextMenuFill(form, usernameField, passwordField, unchangedFields, 1);
if (!passwordField.hasAttribute("expectedFail")) {
Assert.equal(passwordField.value, "password1", "Check upgraded login was actually used");
}
contextMenu.hidePopup();
}
}
});
--- a/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_passwordmgr_observers.js
@@ -74,17 +74,17 @@ add_task(function* test() {
function getLoginOrder() {
let doc = pmDialog.document;
let signonsTree = doc.getElementById("signonsTree");
let column = signonsTree.columns[0]; // host column
let order = [];
for (let i = 0; i < signonsTree.view.rowCount; i++) {
order.push(signonsTree.view.getCellText(i, column));
}
- return order.join(',');
+ return order.join(",");
}
function getLoginPassword() {
let doc = pmDialog.document;
let loginsTree = doc.getElementById("signonsTree");
let column = loginsTree.columns[2]; // password column
return loginsTree.view.getCellText(0, column);
}
--- a/toolkit/components/passwordmgr/test/browser/browser_username_select_dialog.js
+++ b/toolkit/components/passwordmgr/test/browser/browser_username_select_dialog.js
@@ -58,17 +58,17 @@ add_task(function* test_changeUPLoginOnP
}, "Wait for selection dialog to be accessible.");
let doc = getSelectDialogDoc();
let dialog = doc.getElementsByTagName("dialog")[0];
let listbox = doc.getElementById("list");
is(listbox.selectedIndex, 0, "Checking selected index");
is(listbox.itemCount, 2, "Checking selected length");
- ['notifyu1', 'notifyu1B'].forEach((username, i) => {
+ ["notifyu1", "notifyu1B"].forEach((username, i) => {
is(listbox.getItemAtIndex(i).label, username, "Check username selection on dialog");
});
dialog.acceptDialog();
yield ContentTaskUtils.waitForCondition(() => {
return !getSelectDialogDoc();
}, "Wait for selection dialog to disappear.");
@@ -109,17 +109,17 @@ add_task(function* test_changeUPLoginOnP
}, "Wait for selection dialog to be accessible.");
let doc = getSelectDialogDoc();
let dialog = doc.getElementsByTagName("dialog")[0];
let listbox = doc.getElementById("list");
is(listbox.selectedIndex, 0, "Checking selected index");
is(listbox.itemCount, 2, "Checking selected length");
- ['notifyu1', 'notifyu1B'].forEach((username, i) => {
+ ["notifyu1", "notifyu1B"].forEach((username, i) => {
is(listbox.getItemAtIndex(i).label, username, "Check username selection on dialog");
});
dialog.cancelDialog();
yield ContentTaskUtils.waitForCondition(() => {
return !getSelectDialogDoc();
}, "Wait for selection dialog to disappear.");
--- a/toolkit/components/passwordmgr/test/chrome_timeout.js
+++ b/toolkit/components/passwordmgr/test/chrome_timeout.js
@@ -1,11 +1,11 @@
const Cc = Components.classes;
const Ci = Components.interfaces;
-addMessageListener('setTimeout', msg => {
- let timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
+addMessageListener("setTimeout", msg => {
+ let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.init(_ => {
- sendAsyncMessage('timeout');
+ sendAsyncMessage("timeout");
}, msg.delay, Ci.nsITimer.TYPE_ONE_SHOT);
});
-sendAsyncMessage('ready');
+sendAsyncMessage("ready");
--- a/toolkit/components/passwordmgr/test/pwmgr_common.js
+++ b/toolkit/components/passwordmgr/test/pwmgr_common.js
@@ -166,29 +166,29 @@ function commonInit(selfFilling) {
}
function registerRunTests() {
// We provide a general mechanism for our tests to know when they can
// safely run: we add a final form that we know will be filled in, wait
// for the login manager to tell us that it's filled in and then continue
// with the rest of the tests.
window.addEventListener("DOMContentLoaded", (event) => {
- var form = document.createElement('form');
- form.id = 'observerforcer';
- var username = document.createElement('input');
- username.name = 'testuser';
+ var form = document.createElement("form");
+ form.id = "observerforcer";
+ var username = document.createElement("input");
+ username.name = "testuser";
form.appendChild(username);
- var password = document.createElement('input');
- password.name = 'testpass';
- password.type = 'password';
+ var password = document.createElement("input");
+ password.name = "testpass";
+ password.type = "password";
form.appendChild(password);
var observer = SpecialPowers.wrapCallback(function(subject, topic, data) {
var formLikeRoot = subject.QueryInterface(SpecialPowers.Ci.nsIDOMNode);
- if (formLikeRoot.id !== 'observerforcer')
+ if (formLikeRoot.id !== "observerforcer")
return;
SpecialPowers.removeObserver(observer, "passwordmgr-processed-form");
formLikeRoot.remove();
SimpleTest.executeSoon(() => {
var runTestEvent = new Event("runTests");
window.dispatchEvent(runTestEvent);
});
});
--- a/toolkit/components/places/BookmarkHTMLUtils.jsm
+++ b/toolkit/components/places/BookmarkHTMLUtils.jsm
@@ -1037,17 +1037,17 @@ BookmarkExporter.prototype = {
_converterOut: null,
_write(aText) {
this._converterOut.writeString(aText || "");
},
_writeAttribute(aName, aValue) {
- this._write(' ' + aName + '="' + aValue + '"');
+ this._write(" " + aName + '="' + aValue + '"');
},
_writeLine(aText) {
this._write(aText + "\n");
},
_writeHeader() {
this._writeLine("<!DOCTYPE NETSCAPE-Bookmark-file-1>");
--- a/toolkit/components/places/Bookmarks.jsm
+++ b/toolkit/components/places/Bookmarks.jsm
@@ -507,17 +507,17 @@ var Bookmarks = Object.freeze({
* @return {Promise} resolved when the listing is complete.
* @resolves to an array of recent bookmark-items.
* @rejects if an error happens while querying.
*/
getRecent(numberOfItems) {
if (numberOfItems === undefined) {
throw new Error("numberOfItems argument is required");
}
- if (!typeof numberOfItems === 'number' || (numberOfItems % 1) !== 0) {
+ if (!typeof numberOfItems === "number" || (numberOfItems % 1) !== 0) {
throw new Error("numberOfItems argument must be an integer");
}
if (numberOfItems <= 0) {
throw new Error("numberOfItems argument must be greater than zero");
}
return Task.spawn(function* () {
return yield fetchRecentBookmarks(numberOfItems);
--- a/toolkit/components/places/PageIconProtocolHandler.js
+++ b/toolkit/components/places/PageIconProtocolHandler.js
@@ -1,18 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-Cu.import('resource://gre/modules/Services.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
function makeDefaultFaviconChannel(uri, loadInfo) {
let channel = Services.io.newChannelFromURIWithLoadInfo(
PlacesUtils.favicons.defaultFavicon, loadInfo);
@@ -70,17 +70,17 @@ PageIconProtocolHandler.prototype = {
try {
// Create a pipe that will give us an output stream that we can use once
// we got all the favicon data.
let pipe = Cc["@mozilla.org/pipe;1"]
.createInstance(Ci.nsIPipe);
pipe.init(true, true, 0, Ci.nsIFaviconService.MAX_FAVICON_BUFFER_SIZE);
// Create our channel.
- let channel = Cc['@mozilla.org/network/input-stream-channel;1']
+ let channel = Cc["@mozilla.org/network/input-stream-channel;1"]
.createInstance(Ci.nsIInputStreamChannel);
channel.QueryInterface(Ci.nsIChannel);
channel.setURI(uri);
channel.contentStream = pipe.inputStream;
channel.loadInfo = loadInfo;
let pageURI = NetUtil.newURI(uri.path);
PlacesUtils.favicons.getFaviconDataForPage(pageURI, (iconuri, len, data, mime) => {
--- a/toolkit/components/places/PlacesUtils.jsm
+++ b/toolkit/components/places/PlacesUtils.jsm
@@ -947,17 +947,17 @@ this.PlacesUtils = {
break;
}
case this.TYPE_UNICODE: {
let parts = blob.split("\n");
for (let i = 0; i < parts.length; i++) {
let uriString = parts[i];
// text/uri-list is converted to TYPE_UNICODE but it could contain
// comments line prepended by #, we should skip them
- if (uriString.substr(0, 1) == '\x23')
+ if (uriString.substr(0, 1) == "\x23")
continue;
// note: this._uri() will throw if uriString is not a valid URI
if (uriString != "" && this._uri(uriString))
nodes.push({ uri: uriString,
title: uriString,
type: this.TYPE_X_MOZ_URL });
}
break;
--- a/toolkit/components/places/nsTaggingService.js
+++ b/toolkit/components/places/nsTaggingService.js
@@ -606,17 +606,17 @@ TagAutoCompleteSearch.prototype = {
var searchResults = this.tagging.allTags;
var results = [];
var comments = [];
this._stopped = false;
// only search on characters for the last tag
var index = Math.max(searchString.lastIndexOf(","),
searchString.lastIndexOf(";"));
- var before = '';
+ var before = "";
if (index != -1) {
before = searchString.slice(0, index + 1);
searchString = searchString.slice(index + 1);
// skip past whitespace
var m = searchString.match(/\s+/);
if (m) {
before += m[0];
searchString = searchString.slice(m[0].length);
--- a/toolkit/components/places/tests/browser/browser_bug646422.js
+++ b/toolkit/components/places/tests/browser/browser_bug646422.js
@@ -3,17 +3,17 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Test for Bug 646224. Make sure that after changing the URI via
* history.pushState, the history service has a title stored for the new URI.
**/
add_task(function* () {
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, 'http://example.com');
+ let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://example.com");
let newTitlePromise = new Promise(resolve => {
let observer = {
onTitleChanged(uri, title) {
// If the uri of the page whose title is changing ends with 'new_page',
// then it's the result of our pushState.
if (/new_page$/.test(uri.spec)) {
resolve(title);
@@ -31,17 +31,17 @@ add_task(function* () {
QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver])
};
PlacesUtils.history.addObserver(observer, false);
});
yield ContentTask.spawn(tab.linkedBrowser, null, function* () {
let title = content.document.title;
- content.history.pushState('', '', 'new_page');
+ content.history.pushState("", "", "new_page");
Assert.ok(title, "Content window should initially have a title.");
});
let newtitle = yield newTitlePromise;
yield ContentTask.spawn(tab.linkedBrowser, { newtitle }, function* (args) {
Assert.equal(args.newtitle, content.document.title, "Title after pushstate.");
});
--- a/toolkit/components/places/tests/browser/head.js
+++ b/toolkit/components/places/tests/browser/head.js
@@ -250,17 +250,17 @@ function DBConn(aForceNewConnection) {
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.DBConnection;
if (db.connectionReady)
return db;
}
// If the Places database connection has been closed, create a new connection.
if (!gDBConn || aForceNewConnection) {
- let file = Services.dirsvc.get('ProfD', Ci.nsIFile);
+ let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append("places.sqlite");
let dbConn = gDBConn = Services.storage.openDatabase(file);
// Be sure to cleanly close this connection.
Services.obs.addObserver(function DBCloseCallback(aSubject, aTopic, aData) {
Services.obs.removeObserver(DBCloseCallback, aTopic);
dbConn.asyncClose();
}, "profile-before-change", false);
--- a/toolkit/components/places/tests/favicons/test_replaceFaviconDataFromDataURL.js
+++ b/toolkit/components/places/tests/favicons/test_replaceFaviconDataFromDataURL.js
@@ -314,21 +314,21 @@ add_task(function* test_replaceFaviconDa
yield deferSetAndFetchFavicon.promise;
yield PlacesTestUtils.clearHistory();
});
/* toBase64 copied from image/test/unit/test_encoder_png.js */
/* Convert data (an array of integers) to a Base64 string. */
-const toBase64Table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' +
- '0123456789+/';
-const base64Pad = '=';
+const toBase64Table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
+ "0123456789+/";
+const base64Pad = "=";
function toBase64(data) {
- let result = '';
+ let result = "";
let length = data.length;
let i;
// Convert every three bytes to 4 ascii characters.
for (i = 0; i < (length - 2); i += 3) {
result += toBase64Table[data[i] >> 2];
result += toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)];
result += toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)];
result += toBase64Table[data[i + 2] & 0x3f];
--- a/toolkit/components/places/tests/head_common.js
+++ b/toolkit/components/places/tests/head_common.js
@@ -108,17 +108,17 @@ function DBConn(aForceNewConnection) {
let db = PlacesUtils.history.QueryInterface(Ci.nsPIPlacesDatabase)
.DBConnection;
if (db.connectionReady)
return db;
}
// If the Places database connection has been closed, create a new connection.
if (!gDBConn || aForceNewConnection) {
- let file = Services.dirsvc.get('ProfD', Ci.nsIFile);
+ let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append("places.sqlite");
let dbConn = gDBConn = Services.storage.openDatabase(file);
// Be sure to cleanly close this connection.
promiseTopicObserved("profile-before-change").then(() => dbConn.asyncClose());
}
return gDBConn.connectionReady ? gDBConn : null;
@@ -230,17 +230,17 @@ function compareArrays(aArray1, aArray2)
}
/**
* Deletes a previously created sqlite file from the profile folder.
*/
function clearDB() {
try {
- let file = Services.dirsvc.get('ProfD', Ci.nsIFile);
+ let file = Services.dirsvc.get("ProfD", Ci.nsIFile);
file.append("places.sqlite");
if (file.exists())
file.remove(false);
} catch (ex) { dump("Exception: " + ex); }
}
/**
--- a/toolkit/components/places/tests/queries/test_queryMultipleFolder.js
+++ b/toolkit/components/places/tests/queries/test_queryMultipleFolder.js
@@ -30,17 +30,17 @@ add_task(function* test_queryMultipleFol
}
// using queryStringToQueries
let query = {};
let options = {};
let maxResults = 20;
let queryString = "place:" + folderIds.map((id) => {
return "folder=" + id;
- }).join('&') + "&sort=5&maxResults=" + maxResults;
+ }).join("&") + "&sort=5&maxResults=" + maxResults;
PlacesUtils.history.queryStringToQueries(queryString, query, {}, options);
let rootNode = PlacesUtils.history.executeQuery(query.value[0], options.value).root;
rootNode.containerOpen = true;
let resultLength = rootNode.childCount;
Assert.equal(resultLength, maxResults);
for (let i = 0; i < resultLength; ++i) {
let node = rootNode.getChild(i);
Assert.equal(bookmarkIds[i], node.itemId, node.uri);
--- a/toolkit/components/places/tests/unit/test_async_history_api.js
+++ b/toolkit/components/places/tests/unit/test_async_history_api.js
@@ -643,17 +643,17 @@ add_task(function* test_add_visit() {
do_check_eq(visit.visitDate, VISIT_TIME);
do_check_true(Object.values(PlacesUtils.history.TRANSITIONS).includes(visit.transitionType));
do_check_true(visit.referrerURI === null);
// For TRANSITION_EMBED visits, many properties will always be zero or
// undefined.
if (visit.transitionType == TRANSITION_EMBED) {
// Check mozIPlaceInfo properties.
- do_check_eq(placeInfo.placeId, 0, '//');
+ do_check_eq(placeInfo.placeId, 0, "//");
do_check_eq(placeInfo.guid, null);
// Check mozIVisitInfo properties.
do_check_eq(visit.visitId, 0);
} else {
// But they should be valid for non-embed visits.
// Check mozIPlaceInfo properties.
do_check_true(placeInfo.placeId > 0);
--- a/toolkit/components/places/tests/unit/test_history_notifications.js
+++ b/toolkit/components/places/tests/unit/test_history_notifications.js
@@ -1,14 +1,14 @@
const NS_PLACES_INIT_COMPLETE_TOPIC = "places-init-complete";
const NS_PLACES_DATABASE_LOCKED_TOPIC = "places-database-locked";
add_task(function* () {
// Create a dummy places.sqlite and open an unshared connection on it
- let db = Services.dirsvc.get('ProfD', Ci.nsIFile);
+ let db = Services.dirsvc.get("ProfD", Ci.nsIFile);
db.append("places.sqlite");
let dbConn = Services.storage.openUnsharedDatabase(db);
Assert.ok(db.exists(), "The database should have been created");
// We need an exclusive lock on the db
dbConn.executeSimpleSQL("PRAGMA locking_mode = EXCLUSIVE");
// Exclusive locking is lazy applied, we need to make a write to activate it
dbConn.executeSimpleSQL("PRAGMA USER_VERSION = 1");
--- a/toolkit/components/places/tests/unit/test_preventive_maintenance.js
+++ b/toolkit/components/places/tests/unit/test_preventive_maintenance.js
@@ -83,37 +83,37 @@ tests.push({
setup() {
// Add a place to ensure place_id = 1 is valid.
this._placeId = addPlace();
// Add an obsolete attribute.
let stmt = mDBConn.createStatement(
"INSERT INTO moz_anno_attributes (name) VALUES (:anno)"
);
- stmt.params['anno'] = this._obsoleteWeaveAttribute;
+ stmt.params["anno"] = this._obsoleteWeaveAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement(
`INSERT INTO moz_annos (place_id, anno_attribute_id)
VALUES (:place_id,
(SELECT id FROM moz_anno_attributes WHERE name = :anno)
)`
);
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._obsoleteWeaveAttribute;
+ stmt.params["place_id"] = this._placeId;
+ stmt.params["anno"] = this._obsoleteWeaveAttribute;
stmt.execute();
stmt.finalize();
},
check() {
// Check that the obsolete annotation has been removed.
let stmt = mDBConn.createStatement(
"SELECT id FROM moz_anno_attributes WHERE name = :anno"
);
- stmt.params['anno'] = this._obsoleteWeaveAttribute;
+ stmt.params["anno"] = this._obsoleteWeaveAttribute;
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
tests.push({
name: "A.2",
desc: "Remove obsolete annotations from moz_items_annos",
@@ -129,44 +129,44 @@ tests.push({
this._placeId = addPlace();
// Add a bookmark.
this._bookmarkId = addBookmark(this._placeId);
// Add an obsolete attribute.
let stmt = mDBConn.createStatement(
`INSERT INTO moz_anno_attributes (name)
VALUES (:anno1), (:anno2), (:anno3)`
);
- stmt.params['anno1'] = this._obsoleteSyncAttribute;
- stmt.params['anno2'] = this._obsoleteGuidAttribute;
- stmt.params['anno3'] = this._obsoleteWeaveAttribute;
+ stmt.params["anno1"] = this._obsoleteSyncAttribute;
+ stmt.params["anno2"] = this._obsoleteGuidAttribute;
+ stmt.params["anno3"] = this._obsoleteWeaveAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement(
`INSERT INTO moz_items_annos (item_id, anno_attribute_id)
SELECT :item_id, id
FROM moz_anno_attributes
WHERE name IN (:anno1, :anno2, :anno3)`
);
- stmt.params['item_id'] = this._bookmarkId;
- stmt.params['anno1'] = this._obsoleteSyncAttribute;
- stmt.params['anno2'] = this._obsoleteGuidAttribute;
- stmt.params['anno3'] = this._obsoleteWeaveAttribute;
+ stmt.params["item_id"] = this._bookmarkId;
+ stmt.params["anno1"] = this._obsoleteSyncAttribute;
+ stmt.params["anno2"] = this._obsoleteGuidAttribute;
+ stmt.params["anno3"] = this._obsoleteWeaveAttribute;
stmt.execute();
stmt.finalize();
},
check() {
// Check that the obsolete annotations have been removed.
let stmt = mDBConn.createStatement(
`SELECT id FROM moz_anno_attributes
WHERE name IN (:anno1, :anno2, :anno3)`
);
- stmt.params['anno1'] = this._obsoleteSyncAttribute;
- stmt.params['anno2'] = this._obsoleteGuidAttribute;
- stmt.params['anno3'] = this._obsoleteWeaveAttribute;
+ stmt.params["anno1"] = this._obsoleteSyncAttribute;
+ stmt.params["anno2"] = this._obsoleteGuidAttribute;
+ stmt.params["anno3"] = this._obsoleteWeaveAttribute;
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
tests.push({
name: "A.3",
desc: "Remove unused attributes",
@@ -179,49 +179,49 @@ tests.push({
setup() {
// Add a place to ensure place_id = 1 is valid
this._placeId = addPlace();
// add a bookmark
this._bookmarkId = addBookmark(this._placeId);
// Add a used attribute and an unused one.
let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.reset();
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.reset();
- stmt.params['anno'] = this._unusedAttribute;
+ stmt.params["anno"] = this._unusedAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["place_id"] = this._placeId;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES(:item_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['item_id'] = this._bookmarkId;
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["item_id"] = this._bookmarkId;
+ stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.finalize();
},
check() {
// Check that used attributes are still there
let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
do_check_true(stmt.executeStep());
stmt.reset();
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
do_check_true(stmt.executeStep());
stmt.reset();
// Check that unused attribute has been removed
- stmt.params['anno'] = this._unusedAttribute;
+ stmt.params["anno"] = this._unusedAttribute;
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
// ------------------------------------------------------------------------------
tests.push({
@@ -231,40 +231,40 @@ tests.push({
_usedPageAttribute: "usedPage",
_placeId: null,
setup() {
// Add a place to ensure place_id = 1 is valid
this._placeId = addPlace();
// Add a used attribute.
let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["place_id"] = this._placeId;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.finalize();
// Add an annotation with a nonexistent attribute
stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, 1337)");
- stmt.params['place_id'] = this._placeId;
+ stmt.params["place_id"] = this._placeId;
stmt.execute();
stmt.finalize();
},
check() {
// Check that used attribute is still there
let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// check that annotation with valid attribute is still there
stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// Check that annotation with bogus attribute has been removed
stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE anno_attribute_id = 1337");
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
@@ -278,40 +278,40 @@ tests.push({
_usedPageAttribute: "usedPage",
_placeId: null,
setup() {
// Add a place to ensure place_id = 1 is valid
this._placeId = addPlace();
// Add a used attribute.
let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement("INSERT INTO moz_annos (place_id, anno_attribute_id) VALUES(:place_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['place_id'] = this._placeId;
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["place_id"] = this._placeId;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.reset();
// Add an annotation to a nonexistent page
- stmt.params['place_id'] = 1337;
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["place_id"] = 1337;
+ stmt.params["anno"] = this._usedPageAttribute;
stmt.execute();
stmt.finalize();
},
check() {
// Check that used attribute is still there
let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// check that annotation with valid attribute is still there
stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedPageAttribute;
+ stmt.params["anno"] = this._usedPageAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// Check that an annotation to a nonexistent page has been removed
stmt = mDBConn.createStatement("SELECT id FROM moz_annos WHERE place_id = 1337");
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
@@ -905,40 +905,40 @@ tests.push({
setup() {
// Add a place to ensure place_id = 1 is valid
this._placeId = addPlace();
// Insert a bookmark
this._bookmarkId = addBookmark(this._placeId);
// Add a used attribute.
let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES(:item_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
- stmt.params['item_id'] = this._bookmarkId;
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["item_id"] = this._bookmarkId;
+ stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.finalize();
// Add an annotation with a nonexistent attribute
stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES(:item_id, 1337)");
- stmt.params['item_id'] = this._bookmarkId;
+ stmt.params["item_id"] = this._bookmarkId;
stmt.execute();
stmt.finalize();
},
check() {
// Check that used attribute is still there
let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// check that annotation with valid attribute is still there
stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// Check that annotation with bogus attribute has been removed
stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE anno_attribute_id = 1337");
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
@@ -956,17 +956,17 @@ tests.push({
setup() {
// Add a place to ensure place_id = 1 is valid
this._placeId = addPlace();
// Insert a bookmark
this._bookmarkId = addBookmark(this._placeId);
// Add a used attribute.
let stmt = mDBConn.createStatement("INSERT INTO moz_anno_attributes (name) VALUES (:anno)");
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.finalize();
stmt = mDBConn.createStatement("INSERT INTO moz_items_annos (item_id, anno_attribute_id) VALUES (:item_id, (SELECT id FROM moz_anno_attributes WHERE name = :anno))");
stmt.params["item_id"] = this._bookmarkId;
stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.reset();
// Add an annotation to a nonexistent item
@@ -974,22 +974,22 @@ tests.push({
stmt.params["anno"] = this._usedItemAttribute;
stmt.execute();
stmt.finalize();
},
check() {
// Check that used attribute is still there
let stmt = mDBConn.createStatement("SELECT id FROM moz_anno_attributes WHERE name = :anno");
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// check that annotation with valid attribute is still there
stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE anno_attribute_id = (SELECT id FROM moz_anno_attributes WHERE name = :anno)");
- stmt.params['anno'] = this._usedItemAttribute;
+ stmt.params["anno"] = this._usedItemAttribute;
do_check_true(stmt.executeStep());
stmt.finalize();
// Check that an annotation to a nonexistent page has been removed
stmt = mDBConn.createStatement("SELECT id FROM moz_items_annos WHERE item_id = 8888");
do_check_false(stmt.executeStep());
stmt.finalize();
}
});
--- a/toolkit/components/places/tests/unit/test_tagging.js
+++ b/toolkit/components/places/tests/unit/test_tagging.js
@@ -157,17 +157,17 @@ function run_test() {
do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
}
// Tag name length should be limited to nsITaggingService.MAX_TAG_LENGTH (bug407821)
try {
// generate a long tag name. i.e. looooo...oong_tag
var n = Ci.nsITaggingService.MAX_TAG_LENGTH;
- var someOos = new Array(n).join('o');
+ var someOos = new Array(n).join("o");
var longTagName = "l" + someOos + "ng_tag";
tagssvc.tagURI(uri1, ["short_tag", longTagName]);
do_throw("Passing a bad tags array should throw");
} catch (ex) {
do_check_eq(ex.name, "NS_ERROR_ILLEGAL_VALUE");
}
--- a/toolkit/components/prompts/src/CommonDialog.jsm
+++ b/toolkit/components/prompts/src/CommonDialog.jsm
@@ -154,17 +154,17 @@ CommonDialog.prototype = {
this.args.buttonNumClicked = 1;
// Set the default button
let b = (this.args.defaultButtonNum || 0);
let button = this.ui["button" + b];
if (xulDialog)
- xulDialog.defaultButton = ['accept', 'cancel', 'extra1', 'extra2'][b];
+ xulDialog.defaultButton = ["accept", "cancel", "extra1", "extra2"][b];
else
button.setAttribute("default", "true");
// Set default focus / selection.
this.setDefaultFocus(true);
if (this.args.enableDelay) {
this.delayHelper = new EnableDelayHelper({
--- a/toolkit/components/reader/AboutReader.jsm
+++ b/toolkit/components/reader/AboutReader.jsm
@@ -236,33 +236,33 @@ AboutReader.prototype = {
handleEvent(aEvent) {
if (!aEvent.isTrusted)
return;
switch (aEvent.type) {
case "click":
let target = aEvent.target;
- if (target.classList.contains('dropdown-toggle')) {
+ if (target.classList.contains("dropdown-toggle")) {
this._toggleDropdownClicked(aEvent);
- } else if (!target.closest('.dropdown-popup')) {
+ } else if (!target.closest(".dropdown-popup")) {
this._closeDropdowns();
}
break;
case "scroll":
this._closeDropdowns(true);
let isScrollingUp = this._scrollOffset > aEvent.pageY;
this._setSystemUIVisibility(isScrollingUp);
this._scrollOffset = aEvent.pageY;
break;
case "resize":
this._updateImageMargins();
if (this._isToolbarVertical) {
this._win.setTimeout(() => {
- for (let dropdown of this._doc.querySelectorAll('.dropdown.open')) {
+ for (let dropdown of this._doc.querySelectorAll(".dropdown.open")) {
this._updatePopupPosition(dropdown);
}
}, 0);
}
break;
case "devicelight":
this._handleDeviceLight(aEvent.value);
@@ -680,21 +680,21 @@ AboutReader.prototype = {
},
_loadFavicon(url, faviconUrl) {
if (this._article.url !== url)
return;
let doc = this._doc;
- let link = doc.createElement('link');
- link.rel = 'shortcut icon';
+ let link = doc.createElement("link");
+ link.rel = "shortcut icon";
link.href = faviconUrl;
- doc.getElementsByTagName('head')[0].appendChild(link);
+ doc.getElementsByTagName("head")[0].appendChild(link);
},
_updateImageMargins() {
let windowWidth = this._win.innerWidth;
let bodyWidth = this._doc.body.clientWidth;
let setImageMargins = function(img) {
// If the image is at least as wide as the window, make it fill edge-to-edge on mobile.
@@ -960,17 +960,17 @@ AboutReader.prototype = {
let toggleHeight = dropdownToggle.offsetHeight;
let toggleTop = dropdownToggle.offsetTop;
let popupTop = toggleTop - toggleHeight / 2;
dropdownPopup.style.top = popupTop + "px";
},
_toggleDropdownClicked(event) {
- let dropdown = event.target.closest('.dropdown');
+ let dropdown = event.target.closest(".dropdown");
if (!dropdown)
return;
event.stopPropagation();
if (dropdown.classList.contains("open")) {
this._closeDropdowns();
--- a/toolkit/components/reader/ReaderMode.jsm
+++ b/toolkit/components/reader/ReaderMode.jsm
@@ -154,17 +154,17 @@ this.ReaderMode = {
let searchParams = new URLSearchParams(url.substring("about:reader?".length));
if (!searchParams.has("url")) {
return null;
}
let originalUrl = searchParams.get("url");
if (outerHash) {
try {
let uriObj = Services.io.newURI(originalUrl);
- uriObj = Services.io.newURI('#' + outerHash, null, uriObj);
+ uriObj = Services.io.newURI("#" + outerHash, null, uriObj);
originalUrl = uriObj.spec;
} catch (ex) {}
}
return originalUrl;
},
/**
* Decides whether or not a document is reader-able without parsing the whole thing.
--- a/toolkit/components/reader/test/head.js
+++ b/toolkit/components/reader/test/head.js
@@ -47,17 +47,17 @@ function promiseTabLoadEvent(tab, url) {
// Promise.all rejects if either promise rejects (i.e. if we time out) and
// if our loaded promise resolves before the timeout, then we resolve the
// timeout promise as well, causing the all promise to resolve.
return Promise.all([deferred.promise, loaded]);
}
function waitForCondition(condition, nextTest, errorMsg, retryTimes) {
- retryTimes = typeof retryTimes !== 'undefined' ? retryTimes : 30;
+ retryTimes = typeof retryTimes !== "undefined" ? retryTimes : 30;
var tries = 0;
var interval = setInterval(function() {
if (tries >= retryTimes) {
ok(false, errorMsg);
moveOn();
}
var conditionPassed;
try {
--- a/toolkit/components/satchel/FormHistory.jsm
+++ b/toolkit/components/satchel/FormHistory.jsm
@@ -227,17 +227,17 @@ function validateSearchData(aData, aData
if (field != "op" && validFields.indexOf(field) == -1 && searchFilters.indexOf(field) == -1) {
throw Components.Exception(
aDataType + " query contains an unrecognized field: " + field,
Cr.NS_ERROR_ILLEGAL_VALUE);
}
}
}
-function makeQueryPredicates(aQueryData, delimiter = ' AND ') {
+function makeQueryPredicates(aQueryData, delimiter = " AND ") {
return Object.keys(aQueryData).map(function(field) {
if (field == "firstUsedStart") {
return "firstUsed >= :" + field;
} else if (field == "firstUsedEnd") {
return "firstUsed <= :" + field;
} else if (field == "lastUsedStart") {
return "lastUsed >= :" + field;
} else if (field == "lastUsedEnd") {
@@ -303,17 +303,17 @@ function makeRemoveStatement(aSearchData
// won't need to modify the query in this case.
}
return dbCreateAsyncStatement(query, aSearchData, aBindingArrays);
}
function makeUpdateStatement(aGuid, aNewData, aBindingArrays) {
let query = "UPDATE moz_formhistory SET ";
- let queryTerms = makeQueryPredicates(aNewData, ', ');
+ let queryTerms = makeQueryPredicates(aNewData, ", ");
if (!queryTerms) {
throw Components.Exception("Update query must define fields to modify.",
Cr.NS_ERROR_ILLEGAL_VALUE);
}
query += queryTerms + " WHERE guid = :existing_guid";
aNewData["existing_guid"] = aGuid;
--- a/toolkit/components/satchel/formSubmitListener.js
+++ b/toolkit/components/satchel/formSubmitListener.js
@@ -33,17 +33,17 @@ var satchelFormListener = {
this.enabled = Services.prefs.getBoolPref("browser.formfill.enable");
this.saveHttpsForms = Services.prefs.getBoolPref("browser.formfill.saveHttpsForms");
},
// Implements the Luhn checksum algorithm as described at
// http://wikipedia.org/wiki/Luhn_algorithm
isValidCCNumber(ccNumber) {
// Remove dashes and whitespace
- ccNumber = ccNumber.replace(/[\-\s]/g, '');
+ ccNumber = ccNumber.replace(/[\-\s]/g, "");
let len = ccNumber.length;
if (len != 9 && len != 15 && len != 16)
return false;
if (!/^\d+$/.test(ccNumber))
return false;
@@ -149,17 +149,17 @@ var satchelFormListener = {
this.log("skipping saving a credit card number");
continue;
}
let name = input.name || input.id;
if (!name)
continue;
- if (name == 'searchbar-history') {
+ if (name == "searchbar-history") {
this.log('addEntry for input name "' + name + '" is denied')
continue;
}
// Limit stored data to 200 characters.
if (name.length > 200 || value.length > 200) {
this.log("skipping input that has a name/value too large");
continue;
--- a/toolkit/components/satchel/nsFormAutoComplete.js
+++ b/toolkit/components/satchel/nsFormAutoComplete.js
@@ -307,26 +307,26 @@ FormAutoComplete.prototype = {
if (!this._enabled) {
if (aListener) {
aListener.onSearchCompletion(emptyResult);
}
return;
}
// don't allow form inputs (aField != null) to get results from search bar history
- if (aInputName == 'searchbar-history' && aField) {
+ if (aInputName == "searchbar-history" && aField) {
this.log('autoCompleteSearch for input name "' + aInputName + '" is denied');
if (aListener) {
aListener.onSearchCompletion(emptyResult);
}
return;
}
if (aField && isAutocompleteDisabled(aField)) {
- this.log('autoCompleteSearch not allowed due to autcomplete=off');
+ this.log("autoCompleteSearch not allowed due to autcomplete=off");
if (aListener) {
aListener.onSearchCompletion(emptyResult);
}
return;
}
this.log("AutoCompleteSearch invoked. Search is: " + aUntrimmedSearchString);
let searchString = aUntrimmedSearchString.trim().toLowerCase();
--- a/toolkit/components/satchel/test/unit/test_autocomplete.js
+++ b/toolkit/components/satchel/test/unit/test_autocomplete.js
@@ -8,19 +8,19 @@ var testnum = 0;
var fac;
var prefs;
var numRecords, timeGroupingSize, now;
const DEFAULT_EXPIRE_DAYS = 180;
function padLeft(number, length) {
- var str = number + '';
+ var str = number + "";
while (str.length < length)
- str = '0' + str;
+ str = "0" + str;
return str;
}
function getFormExpiryDays() {
if (prefs.prefHasUserValue("browser.formfill.expire_days")) {
return prefs.getIntPref("browser.formfill.expire_days");
}
return DEFAULT_EXPIRE_DAYS;
--- a/toolkit/components/satchel/test/unit/test_previous_result.js
+++ b/toolkit/components/satchel/test/unit/test_previous_result.js
@@ -13,12 +13,12 @@ var aaListener = {
onSearchResult(search, result) {
do_check_eq(result.searchString, "aa");
search.startSearch("aaa", "", result, aaaListener);
}
};
function run_test() {
do_test_pending();
- let search = Cc['@mozilla.org/autocomplete/search;1?name=form-history'].
+ let search = Cc["@mozilla.org/autocomplete/search;1?name=form-history"].
getService(Components.interfaces.nsIAutoCompleteSearch);
search.startSearch("aa", "", null, aaListener);
}
--- a/toolkit/components/search/nsSearchService.js
+++ b/toolkit/components/search/nsSearchService.js
@@ -930,17 +930,17 @@ function sanitizeName(aName) {
const maxLength = 60;
const minLength = 1;
var name = aName.toLowerCase();
name = name.replace(/\s+/g, "-");
name = name.replace(/[^-a-z0-9]/g, "");
// Use a random name if our input had no valid characters.
if (name.length < minLength)
- name = Math.random().toString(36).replace(/^.*\./, '');
+ name = Math.random().toString(36).replace(/^.*\./, "");
// Force max length.
return name.substring(0, maxLength);
}
/**
* Retrieve a pref from the search param branch.
*
--- a/toolkit/components/search/tests/xpcshell/test_location_funnelcake.js
+++ b/toolkit/components/search/tests/xpcshell/test_location_funnelcake.js
@@ -1,15 +1,15 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
// funnelcake builds start with "mozilla"
- Services.prefs.setCharPref("distribution.id", 'mozilla38');
+ Services.prefs.setCharPref("distribution.id", "mozilla38");
setUpGeoDefaults();
Services.search.init(() => {
equal(Services.search.defaultEngine.name, "A second test engine");
do_test_finished();
run_next_test();
});
--- a/toolkit/components/search/tests/xpcshell/test_location_partner.js
+++ b/toolkit/components/search/tests/xpcshell/test_location_partner.js
@@ -1,14 +1,14 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() {
Services.prefs.setCharPref("browser.search.geoip.url", 'data:application/json,{"country_code": "US"}');
- Services.prefs.setCharPref("distribution.id", 'partner-1');
+ Services.prefs.setCharPref("distribution.id", "partner-1");
setUpGeoDefaults();
Services.search.init(() => {
equal(Services.search.defaultEngine.name, "Test search engine");
do_test_finished();
run_next_test();
});
--- a/toolkit/components/search/tests/xpcshell/test_svg_icon.js
+++ b/toolkit/components/search/tests/xpcshell/test_svg_icon.js
@@ -6,17 +6,17 @@
var url;
var requestHandled;
const icon =
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>' +
'<svg xmlns="http://www.w3.org/2000/svg" ' +
'width="16" height="16" viewBox="0 0 16 16">' +
'<rect x="4" y="4" width="8px" height="8px" style="fill: blue"/>' +
- '</svg>';
+ "</svg>";
function run_test() {
useHttpServer(); // Unused, but required to call addTestEngines.
requestHandled = new Promise(resolve => {
let srv = new HttpServer();
srv.registerPathHandler("/icon.svg", (metadata, response) => {
response.setStatusLine("1.0", 200, "OK");
--- a/toolkit/components/securityreporter/SecurityReporter.js
+++ b/toolkit/components/securityreporter/SecurityReporter.js
@@ -1,16 +1,16 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const { classes: Cc, interfaces: Ci, utils: Cu} = Components;
-Cu.importGlobalProperties(['fetch']);
+Cu.importGlobalProperties(["fetch"]);
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {});
const protocolHandler = Cc["@mozilla.org/network/protocol;1?name=http"]
.getService(Ci.nsIHttpProtocolHandler);
const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const TLS_ERROR_REPORT_TELEMETRY_SUCCESS = 6;
const TLS_ERROR_REPORT_TELEMETRY_FAILURE = 7;
@@ -18,17 +18,17 @@ const HISTOGRAM_ID = "TLS_ERROR_REPORT_U
XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
"resource://gre/modules/UpdateUtils.jsm");
function getDERString(cert) {
var length = {};
var derArray = cert.getRawDER(length);
- var derString = '';
+ var derString = "";
for (var i = 0; i < derArray.length; i++) {
derString += String.fromCharCode(derArray[i]);
}
return derString;
}
function SecurityReporter() { }
@@ -84,17 +84,17 @@ SecurityReporter.prototype = {
product: Services.appinfo.name,
channel: UpdateUtils.UpdateChannel
}
fetch(endpoint, {
method: "POST",
body: JSON.stringify(report),
headers: {
- 'Content-Type': 'application/json'
+ "Content-Type": "application/json"
}
}).then(function(aResponse) {
if (!aResponse.ok) {
// request returned non-success status
Services.telemetry.getHistogramById(HISTOGRAM_ID)
.add(TLS_ERROR_REPORT_TELEMETRY_FAILURE);
} else {
Services.telemetry.getHistogramById(HISTOGRAM_ID)
--- a/toolkit/components/startup/tests/browser/browser_bug511456.js
+++ b/toolkit/components/startup/tests/browser/browser_bug511456.js
@@ -25,17 +25,17 @@ function test() {
// Cancel the prompt the first time.
waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
seenDialog = Services.focus.activeWindow == window &&
gBrowser.selectedBrowser == browser;
btnStay.click();
});
- let appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].
+ let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].
getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eAttemptQuit);
ok(seenDialog, "Should have seen a prompt dialog");
ok(!win2.closed, "Shouldn't have closed the additional window");
win2.close();
// Leave the page the second time.
waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
--- a/toolkit/components/startup/tests/browser/browser_bug537449.js
+++ b/toolkit/components/startup/tests/browser/browser_bug537449.js
@@ -24,17 +24,17 @@ function test() {
let seenDialog = false;
// Cancel the prompt the first time.
waitForOnBeforeUnloadDialog(browser, (btnLeave, btnStay) => {
seenDialog = true;
btnStay.click();
});
- let appStartup = Cc['@mozilla.org/toolkit/app-startup;1'].
+ let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"].
getService(Ci.nsIAppStartup);
appStartup.quit(Ci.nsIAppStartup.eAttemptQuit);
ok(seenDialog, "Should have seen a prompt dialog");
ok(!window.closed, "Shouldn't have closed the window");
let win2 = window.openDialog(location, "", "chrome,all,dialog=no", "about:blank");
ok(win2 != null, "Should have been able to open a new window");
win2.addEventListener("load", function onLoad() {
--- a/toolkit/components/telemetry/TelemetryController.jsm
+++ b/toolkit/components/telemetry/TelemetryController.jsm
@@ -505,17 +505,17 @@ var Impl = {
const typeUuid = /^[a-z0-9][a-z0-9-]+[a-z0-9]$/i;
if (!typeUuid.test(aType)) {
this._log.error("submitExternalPing - invalid ping type: " + aType);
let histogram = Telemetry.getKeyedHistogramById("TELEMETRY_INVALID_PING_TYPE_SUBMITTED");
histogram.add(aType, 1);
return Promise.reject(new Error("Invalid type string submitted."));
}
// Enforce that the payload is an object.
- if (aPayload === null || typeof aPayload !== 'object' || Array.isArray(aPayload)) {
+ if (aPayload === null || typeof aPayload !== "object" || Array.isArray(aPayload)) {
this._log.error("submitExternalPing - invalid payload type: " + typeof aPayload);
let histogram = Telemetry.getHistogramById("TELEMETRY_INVALID_PAYLOAD_SUBMITTED");
histogram.add(1);
return Promise.reject(new Error("Invalid payload type submitted."));
}
let promise = this._submitPingLogic(aType, aPayload, aOptions);
this._trackPendingPingTask(promise);
--- a/toolkit/components/telemetry/TelemetryEnvironment.jsm
+++ b/toolkit/components/telemetry/TelemetryEnvironment.jsm
@@ -228,17 +228,17 @@ function enforceBoolean(aValue) {
/**
* Get the current browser.
* @return a string with the locale or null on failure.
*/
function getBrowserLocale() {
try {
return Cc["@mozilla.org/chrome/chrome-registry;1"].
getService(Ci.nsIXULChromeRegistry).
- getSelectedLocale('global');
+ getSelectedLocale("global");
} catch (e) {
return null;
}
}
/**
* Get the current OS locale.
* @return a string with the OS locale or null on failure.
@@ -361,17 +361,17 @@ function getWindowsVersionInfo() {
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
const WCHAR = ctypes.char16_t;
const BOOL = ctypes.int;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724833%28v=vs.85%29.aspx
const SZCSDVERSIONLENGTH = 128;
- const OSVERSIONINFOEXW = new ctypes.StructType('OSVERSIONINFOEXW',
+ const OSVERSIONINFOEXW = new ctypes.StructType("OSVERSIONINFOEXW",
[
{dwOSVersionInfoSize: DWORD},
{dwMajorVersion: DWORD},
{dwMinorVersion: DWORD},
{dwBuildNumber: DWORD},
{dwPlatformId: DWORD},
{szCSDVersion: ctypes.ArrayType(WCHAR, SZCSDVERSIONLENGTH)},
{wServicePackMajor: WORD},
@@ -1310,17 +1310,17 @@ EnvironmentCache.prototype = {
} else if (AppConstants.platform === "win") {
// The path to the "UBR" key, queried to get additional version details on Windows.
const WINDOWS_UBR_KEY_PATH = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
let versionInfo = getWindowsVersionInfo();
data.servicePackMajor = versionInfo.servicePackMajor;
data.servicePackMinor = versionInfo.servicePackMinor;
// We only need the build number and UBR if we're at or above Windows 10.
- if (typeof(data.version) === 'string' &&
+ if (typeof(data.version) === "string" &&
Services.vc.compare(data.version, "10") >= 0) {
data.windowsBuildNumber = versionInfo.buildNumber;
// Query the UBR key and only add it to the environment if it's available.
// |readRegKey| doesn't throw, but rather returns 'undefined' on error.
let ubr = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE,
WINDOWS_UBR_KEY_PATH, "UBR",
Ci.nsIWindowsRegKey.WOW64_64);
data.windowsUBR = (ubr !== undefined) ? ubr : null;
--- a/toolkit/components/telemetry/TelemetrySession.jsm
+++ b/toolkit/components/telemetry/TelemetrySession.jsm
@@ -229,22 +229,22 @@ var processInfo = {
if (isWindows)
return this.getCounters_Windows();
return null;
},
getCounters_Windows() {
if (!this._initialized) {
Cu.import("resource://gre/modules/ctypes.jsm");
this._IO_COUNTERS = new ctypes.StructType("IO_COUNTERS", [
- {'readOps': ctypes.unsigned_long_long},
- {'writeOps': ctypes.unsigned_long_long},
- {'otherOps': ctypes.unsigned_long_long},
- {'readBytes': ctypes.unsigned_long_long},
- {'writeBytes': ctypes.unsigned_long_long},
- {'otherBytes': ctypes.unsigned_long_long} ]);
+ {"readOps": ctypes.unsigned_long_long},
+ {"writeOps": ctypes.unsigned_long_long},
+ {"otherOps": ctypes.unsigned_long_long},
+ {"readBytes": ctypes.unsigned_long_long},
+ {"writeBytes": ctypes.unsigned_long_long},
+ {"otherBytes": ctypes.unsigned_long_long} ]);
try {
this._kernel32 = ctypes.open("Kernel32.dll");
this._GetProcessIoCounters = this._kernel32.declare("GetProcessIoCounters",
ctypes.winapi_abi,
ctypes.bool, // return
ctypes.voidptr_t, // hProcess
this._IO_COUNTERS.ptr); // lpIoCounters
this._GetCurrentProcess = this._kernel32.declare("GetCurrentProcess",
@@ -1001,17 +1001,17 @@ var Impl = {
let scalarsSnapshot = keyed ?
Telemetry.snapshotKeyedScalars(this.getDatasetType(), clearSubsession) :
Telemetry.snapshotScalars(this.getDatasetType(), clearSubsession);
// Don't return the test scalars.
let ret = {};
for (let processName in scalarsSnapshot) {
for (let name in scalarsSnapshot[processName]) {
- if (name.startsWith('telemetry.test') && this._testing == false) {
+ if (name.startsWith("telemetry.test") && this._testing == false) {
this._log.trace("getScalars - Skipping test scalar: " + name);
continue;
}
// Finally arrange the data in the returned object.
if (!(processName in ret)) {
ret[processName] = {};
}
ret[processName][name] = scalarsSnapshot[processName][name];
--- a/toolkit/components/telemetry/TelemetryStorage.jsm
+++ b/toolkit/components/telemetry/TelemetryStorage.jsm
@@ -1811,17 +1811,17 @@ function getPingDirectory() {
* @return {String} The full path to the archived ping.
*/
function getArchivedPingPath(aPingId, aDate, aType) {
// Helper to pad the month to 2 digits, if needed (e.g. "1" -> "01").
let addLeftPadding = value => (value < 10) ? ("0" + value) : value;
// Get the ping creation date and generate the archive directory to hold it. Note
// that getMonth returns a 0-based month, so we need to add an offset.
let archivedPingDir = OS.Path.join(gPingsArchivePath,
- aDate.getFullYear() + '-' + addLeftPadding(aDate.getMonth() + 1));
+ aDate.getFullYear() + "-" + addLeftPadding(aDate.getMonth() + 1));
// Generate the archived ping file path as YYYY-MM/<TIMESTAMP>.UUID.type.json
let fileName = [aDate.getTime(), aPingId, aType, "json"].join(".");
return OS.Path.join(archivedPingDir, fileName);
}
/**
* Get the size of the ping file on the disk.
* @return {Integer} The file size, in bytes, of the ping file or 0 on errors.
--- a/toolkit/components/telemetry/UITelemetry.jsm
+++ b/toolkit/components/telemetry/UITelemetry.jsm
@@ -199,17 +199,17 @@ this.UITelemetry = {
if (!this.enabled) {
return;
}
if (aName in this._simpleMeasureFunctions) {
throw new Error("A simple measurement function is already registered for " + aName);
}
- if (!aFunction || typeof aFunction !== 'function') {
+ if (!aFunction || typeof aFunction !== "function") {
throw new Error("addSimpleMeasureFunction called with non-function argument.");
}
this._simpleMeasureFunctions[aName] = aFunction;
},
removeSimpleMeasureFunction(aName) {
delete this._simpleMeasureFunctions[aName];
--- a/toolkit/components/telemetry/tests/unit/head.js
+++ b/toolkit/components/telemetry/tests/unit/head.js
@@ -153,17 +153,17 @@ function decodeRequestPayload(request) {
return payload;
}
function wrapWithExceptionHandler(f) {
function wrapper(...args) {
try {
f(...args);
} catch (ex) {
- if (typeof(ex) != 'object') {
+ if (typeof(ex) != "object") {
throw ex;
}
dump("Caught exception: " + ex.message + "\n");
dump(ex.stack);
do_test_finished();
}
}
return wrapper;
--- a/toolkit/components/telemetry/tests/unit/test_ChildScalars.js
+++ b/toolkit/components/telemetry/tests/unit/test_ChildScalars.js
@@ -67,21 +67,21 @@ function checkParentScalars(processData)
Assert.ok(ALL_PROCESSES_UINT_SCALAR in scalars,
`${ALL_PROCESSES_UINT_SCALAR} must be recorded in the parent process.`);
Assert.equal(scalars[ALL_PROCESSES_UINT_SCALAR], 37,
`${ALL_PROCESSES_UINT_SCALAR} must have the correct value (parent process).`);
// Now check the keyed scalars.
Assert.ok(KEYED_BOOL_SCALAR in keyedScalars,
`${KEYED_BOOL_SCALAR} must be recorded in the parent process.`);
- Assert.ok('parent-key' in keyedScalars[KEYED_BOOL_SCALAR],
+ Assert.ok("parent-key" in keyedScalars[KEYED_BOOL_SCALAR],
`${KEYED_BOOL_SCALAR} must be recorded in the parent process.`);
Assert.equal(Object.keys(keyedScalars[KEYED_BOOL_SCALAR]).length, 1,
`${KEYED_BOOL_SCALAR} must only contain the expected key in parent process.`);
- Assert.equal(keyedScalars[KEYED_BOOL_SCALAR]['parent-key'], false,
+ Assert.equal(keyedScalars[KEYED_BOOL_SCALAR]["parent-key"], false,
`${KEYED_BOOL_SCALAR} must have the correct value (parent process).`);
}
function checkContentScalars(processData) {
const scalars = processData.scalars;
const keyedScalars = processData.keyedScalars;
// Check the plain scalars for the content process.
@@ -100,23 +100,23 @@ function checkContentScalars(processData
Assert.ok(ALL_PROCESSES_UINT_SCALAR in scalars,
`${ALL_PROCESSES_UINT_SCALAR} must be recorded in the content process.`);
Assert.equal(scalars[ALL_PROCESSES_UINT_SCALAR], 37,
`${ALL_PROCESSES_UINT_SCALAR} must have the correct value (content process).`);
// Check the keyed scalars.
Assert.ok(KEYED_BOOL_SCALAR in keyedScalars,
`${KEYED_BOOL_SCALAR} must be recorded in the content process.`);
- Assert.ok('content-key' in keyedScalars[KEYED_BOOL_SCALAR],
+ Assert.ok("content-key" in keyedScalars[KEYED_BOOL_SCALAR],
`${KEYED_BOOL_SCALAR} must be recorded in the content process.`);
- Assert.ok('content-key2' in keyedScalars[KEYED_BOOL_SCALAR],
+ Assert.ok("content-key2" in keyedScalars[KEYED_BOOL_SCALAR],
`${KEYED_BOOL_SCALAR} must be recorded in the content process.`);
- Assert.equal(keyedScalars[KEYED_BOOL_SCALAR]['content-key'], true,
+ Assert.equal(keyedScalars[KEYED_BOOL_SCALAR]["content-key"], true,
`${KEYED_BOOL_SCALAR} must have the correct value (content process).`);
- Assert.equal(keyedScalars[KEYED_BOOL_SCALAR]['content-key2'], false,
+ Assert.equal(keyedScalars[KEYED_BOOL_SCALAR]["content-key2"], false,
`${KEYED_BOOL_SCALAR} must have the correct value (content process).`);
Assert.equal(Object.keys(keyedScalars[KEYED_BOOL_SCALAR]).length, 2,
`${KEYED_BOOL_SCALAR} must contain the expected keys in content process.`);
}
/**
* This function waits until content scalars are reported into the
* scalar snapshot.
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetryLateWrites.js
@@ -13,19 +13,19 @@ const RW_OWNER = parseInt("0600", 8);
const STACK_SUFFIX1 = "stack1.txt";
const STACK_SUFFIX2 = "stack2.txt";
const STACK_BOGUS_SUFFIX = "bogus.txt";
const LATE_WRITE_PREFIX = "Telemetry.LateWriteFinal-";
// The names and IDs don't matter, but the format of the IDs does.
const LOADED_MODULES = {
- '4759A7E6993548C89CAF716A67EC242D00': 'libtest.so',
- 'F77AF15BB8D6419FA875954B4A3506CA00': 'libxul.so',
- '1E2F7FB590424E8F93D60BB88D66B8C500': 'libc.so'
+ "4759A7E6993548C89CAF716A67EC242D00": "libtest.so",
+ "F77AF15BB8D6419FA875954B4A3506CA00": "libxul.so",
+ "1E2F7FB590424E8F93D60BB88D66B8C500": "libc.so"
};
const N_MODULES = Object.keys(LOADED_MODULES).length;
// Format of individual items is [index, offset-in-library].
const STACK1 = [
[ 0, 0 ],
[ 1, 1 ],
[ 2, 2 ]
--- a/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetrySession.js
@@ -422,18 +422,18 @@ function checkPayload(payload, reason, s
// memory reporters. But we can at least check that the data is there.
//
// It's important to check for the presence of reporters with a mix of units,
// because TelemetryController has separate logic for each one. But we can't
// currently check UNITS_COUNT_CUMULATIVE or UNITS_PERCENTAGE because
// Telemetry doesn't touch a memory reporter with these units that's
// available on all platforms.
- Assert.ok('MEMORY_JS_GC_HEAP' in payload.histograms); // UNITS_BYTES
- Assert.ok('MEMORY_JS_COMPARTMENTS_SYSTEM' in payload.histograms); // UNITS_COUNT
+ Assert.ok("MEMORY_JS_GC_HEAP" in payload.histograms); // UNITS_BYTES
+ Assert.ok("MEMORY_JS_COMPARTMENTS_SYSTEM" in payload.histograms); // UNITS_COUNT
// We should have included addon histograms.
Assert.ok("addonHistograms" in payload);
Assert.ok(ADDON_NAME in payload.addonHistograms);
Assert.ok(ADDON_HISTOGRAM in payload.addonHistograms[ADDON_NAME]);
Assert.ok(("mainThread" in payload.slowSQL) &&
("otherThreads" in payload.slowSQL));
--- a/toolkit/components/telemetry/tests/unit/test_TelemetryTimestamps.js
+++ b/toolkit/components/telemetry/tests/unit/test_TelemetryTimestamps.js
@@ -2,17 +2,17 @@
* http://creativecommons.org/publicdomain/zero/1.0/ */
var Cu = Components.utils;
var Cc = Components.classes;
var Ci = Components.interfaces;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/TelemetryController.jsm", this);
Cu.import("resource://gre/modules/TelemetrySession.jsm", this);
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
// The @mozilla/xre/app-info;1 XPCOM object provided by the xpcshell test harness doesn't
// implement the nsIXULAppInfo interface, which is needed by Services.jsm and
// TelemetrySession.jsm. updateAppInfo() creates and registers a minimal mock app-info.
Cu.import("resource://testing-common/AppInfo.jsm");
updateAppInfo();
var gGlobalScope = this;
--- a/toolkit/components/telemetry/tests/unit/test_ThreadHangStats.js
+++ b/toolkit/components/telemetry/tests/unit/test_ThreadHangStats.js
@@ -14,23 +14,23 @@ function run_test() {
// We disable hang reporting in several situations (e.g. debug builds,
// official releases). In those cases, we don't have hang stats available
// and should exit the test early.
if (!startHangs) {
ok("Hang reporting not enabled.");
return;
}
- if (Services.appinfo.OS === 'Linux' || Services.appinfo.OS === 'Android') {
+ if (Services.appinfo.OS === "Linux" || Services.appinfo.OS === "Android") {
// We use the rt_tgsigqueueinfo syscall on Linux which requires a
// certain kernel version. It's not an error if the system running
// the test is older than that.
- let kernel = Services.sysinfo.get('kernel_version') ||
- Services.sysinfo.get('version');
- if (Services.vc.compare(kernel, '2.6.31') < 0) {
+ let kernel = Services.sysinfo.get("kernel_version") ||
+ Services.sysinfo.get("version");
+ if (Services.vc.compare(kernel, "2.6.31") < 0) {
ok("Hang reporting not supported for old kernel.");
return;
}
}
// Run three events in the event loop:
// the first event causes a transient hang;
// the second event causes a permanent hang;
--- a/toolkit/components/thumbnails/PageThumbUtils.jsm
+++ b/toolkit/components/thumbnails/PageThumbUtils.jsm
@@ -145,17 +145,17 @@ this.PageThumbUtils = {
* @params aDestCanvas destination canvas to draw the final
* snapshot to. Can be null.
* @param aArgs (optional) Additional named parameters:
* fullScale - request that a non-downscaled image be returned.
* @return Canvas with a scaled thumbnail of the window.
*/
createSnapshotThumbnail(aWindow, aDestCanvas, aArgs) {
if (Cu.isCrossProcessWrapper(aWindow)) {
- throw new Error('Do not pass cpows here.');
+ throw new Error("Do not pass cpows here.");
}
let fullScale = aArgs ? aArgs.fullScale : false;
let [contentWidth, contentHeight] = this.getContentSize(aWindow);
let [thumbnailWidth, thumbnailHeight] = aDestCanvas ?
[aDestCanvas.width, aDestCanvas.height] :
this.getThumbnailSize(aWindow);
// If the caller wants a fullscale image, set the desired thumbnail dims
@@ -226,17 +226,17 @@ this.PageThumbUtils = {
* window.
*
* @param aWindow The content window.
* @param aCanvas The target canvas.
* @return An array containing width, height and scale.
*/
determineCropSize(aWindow, aCanvas) {
if (Cu.isCrossProcessWrapper(aWindow)) {
- throw new Error('Do not pass cpows here.');
+ throw new Error("Do not pass cpows here.");
}
let utils = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
// aWindow may be a cpow, add exposed props security values.
let sbWidth = {}, sbHeight = {};
try {
utils.getScrollbarSize(false, sbWidth, sbHeight);
--- a/toolkit/components/thumbnails/PageThumbs.jsm
+++ b/toolkit/components/thumbnails/PageThumbs.jsm
@@ -28,17 +28,17 @@ const MAX_THUMBNAIL_AGE_SECS = 172800; /
*/
const THUMBNAIL_DIRECTORY = "thumbnails";
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
Cu.import("resource://gre/modules/PromiseWorker.jsm", this);
Cu.import("resource://gre/modules/Promise.jsm", this);
Cu.import("resource://gre/modules/osfile.jsm", this);
-Cu.importGlobalProperties(['FileReader']);
+Cu.importGlobalProperties(["FileReader"]);
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
"resource://gre/modules/NetUtil.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Services",
"resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "FileUtils",
@@ -52,17 +52,17 @@ XPCOMUtils.defineLazyServiceGetter(this,
XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
});
XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = 'utf8';
+ converter.charset = "utf8";
return converter;
});
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
"resource://gre/modules/Deprecated.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown",
--- a/toolkit/components/thumbnails/content/backgroundPageThumbsContent.js
+++ b/toolkit/components/thumbnails/content/backgroundPageThumbsContent.js
@@ -1,15 +1,15 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-Cu.importGlobalProperties(['Blob', 'FileReader']);
+Cu.importGlobalProperties(["Blob", "FileReader"]);
Cu.import("resource://gre/modules/PageThumbUtils.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
const STATE_LOADING = 1;
const STATE_CAPTURING = 2;
const STATE_CANCELED = 3;
--- a/toolkit/components/thumbnails/test/head.js
+++ b/toolkit/components/thumbnails/test/head.js
@@ -301,57 +301,57 @@ function bgAddPageThumbObserver(url) {
Services.obs.addObserver(observe, "page-thumbnail:create", false);
Services.obs.addObserver(observe, "page-thumbnail:error", false);
});
}
function bgAddCrashObserver() {
let crashed = false;
Services.obs.addObserver(function crashObserver(subject, topic, data) {
- is(topic, 'ipc:content-shutdown', 'Received correct observer topic.');
+ is(topic, "ipc:content-shutdown", "Received correct observer topic.");
ok(subject instanceof Components.interfaces.nsIPropertyBag2,
- 'Subject implements nsIPropertyBag2.');
+ "Subject implements nsIPropertyBag2.");
// we might see this called as the process terminates due to previous tests.
// We are only looking for "abnormal" exits...
if (!subject.hasKey("abnormal")) {
info("This is a normal termination and isn't the one we are looking for...");
return;
}
- Services.obs.removeObserver(crashObserver, 'ipc:content-shutdown');
+ Services.obs.removeObserver(crashObserver, "ipc:content-shutdown");
crashed = true;
var dumpID;
- if ('nsICrashReporter' in Components.interfaces) {
- dumpID = subject.getPropertyAsAString('dumpID');
+ if ("nsICrashReporter" in Components.interfaces) {
+ dumpID = subject.getPropertyAsAString("dumpID");
ok(dumpID, "dumpID is present and not an empty string");
}
if (dumpID) {
var minidumpDirectory = getMinidumpDirectory();
- removeFile(minidumpDirectory, dumpID + '.dmp');
- removeFile(minidumpDirectory, dumpID + '.extra');
+ removeFile(minidumpDirectory, dumpID + ".dmp");
+ removeFile(minidumpDirectory, dumpID + ".extra");
}
- }, 'ipc:content-shutdown', false);
+ }, "ipc:content-shutdown", false);
return {
get crashed() {
return crashed;
}
};
}
function bgInjectCrashContentScript() {
const TEST_CONTENT_HELPER = "chrome://mochitests/content/browser/toolkit/components/thumbnails/test/thumbnails_crash_content_helper.js";
let thumbnailBrowser = BackgroundPageThumbs._thumbBrowser;
let mm = thumbnailBrowser.messageManager;
mm.loadFrameScript(TEST_CONTENT_HELPER, false);
return mm;
}
function getMinidumpDirectory() {
- var dir = Services.dirsvc.get('ProfD', Components.interfaces.nsIFile);
+ var dir = Services.dirsvc.get("ProfD", Components.interfaces.nsIFile);
dir.append("minidumps");
return dir;
}
function removeFile(directory, filename) {
var file = directory.clone();
file.append(filename);
if (file.exists()) {
--- a/toolkit/components/timermanager/tests/unit/consumerNotifications.js
+++ b/toolkit/components/timermanager/tests/unit/consumerNotifications.js
@@ -1,16 +1,16 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* General Update Timer Manager Tests */
-'use strict';
+"use strict";
const { classes: Cc, interfaces: Ci, manager: Cm, results: Cr,
utils: Cu } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const CATEGORY_UPDATE_TIMER = "update-timer";
--- a/toolkit/components/tooltiptext/TooltipTextProvider.js
+++ b/toolkit/components/tooltiptext/TooltipTextProvider.js
@@ -36,29 +36,29 @@ TooltipTextProvider.prototype = {
var direction = tipElement.ownerDocument.dir;
// If the element is invalid per HTML5 Forms specifications and has no title,
// show the constraint validation error message.
if ((tipElement instanceof defView.HTMLInputElement ||
tipElement instanceof defView.HTMLTextAreaElement ||
tipElement instanceof defView.HTMLSelectElement ||
tipElement instanceof defView.HTMLButtonElement) &&
- !tipElement.hasAttribute('title') &&
+ !tipElement.hasAttribute("title") &&
(!tipElement.form || !tipElement.form.noValidate)) {
// If the element is barred from constraint validation or valid,
// the validation message will be the empty string.
titleText = tipElement.validationMessage || null;
}
// If the element is an <input type='file'> without a title, we should show
// the current file selection.
if (!titleText &&
tipElement instanceof defView.HTMLInputElement &&
- tipElement.type == 'file' &&
- !tipElement.hasAttribute('title')) {
+ tipElement.type == "file" &&
+ !tipElement.hasAttribute("title")) {
let files = tipElement.files;
try {
var bundle =
Services.strings.createBundle("chrome://global/locale/layout/HtmlForm.properties");
if (files.length == 0) {
if (tipElement.multiple) {
titleText = bundle.GetStringFromName("NoFilesSelected");
@@ -126,17 +126,17 @@ TooltipTextProvider.prototype = {
}
tipElement = tipElement.parentNode;
}
return [titleText, XLinkTitleText, SVGTitleText, XULtooltiptextText].some(function(t) {
if (t && /\S/.test(t)) {
// Make CRLF and CR render one line break each.
- textOut.value = t.replace(/\r\n?/g, '\n');
+ textOut.value = t.replace(/\r\n?/g, "\n");
directionOut.value = direction;
return true;
}
return false;
});
},
--- a/toolkit/components/tooltiptext/tests/browser_bug581947.js
+++ b/toolkit/components/tooltiptext/tests/browser_bug581947.js
@@ -1,55 +1,55 @@
function check(aBrowser, aElementName, aBarred, aType) {
return ContentTask.spawn(aBrowser, [aElementName, aBarred, aType], function*([aElementName, aBarred, aType]) {
let e = content.document.createElement(aElementName);
- let contentElement = content.document.getElementById('content');
+ let contentElement = content.document.getElementById("content");
contentElement.appendChild(e);
if (aType) {
e.type = aType;
}
let tttp = Cc["@mozilla.org/embedcomp/default-tooltiptextprovider;1"]
.getService(Ci.nsITooltipTextProvider);
ok(!tttp.getNodeText(e, {}, {}),
"No tooltip should be shown when the element is valid");
- e.setCustomValidity('foo');
+ e.setCustomValidity("foo");
if (aBarred) {
ok(!tttp.getNodeText(e, {}, {}),
"No tooltip should be shown when the element is barred from constraint validation");
} else {
ok(tttp.getNodeText(e, {}, {}),
e.tagName + " " + "A tooltip should be shown when the element isn't valid");
}
- e.setAttribute('title', '');
+ e.setAttribute("title", "");
ok(!tttp.getNodeText(e, {}, {}),
"No tooltip should be shown if the title attribute is set");
- e.removeAttribute('title');
- contentElement.setAttribute('novalidate', '');
+ e.removeAttribute("title");
+ contentElement.setAttribute("novalidate", "");
ok(!tttp.getNodeText(e, {}, {}),
"No tooltip should be shown if the novalidate attribute is set on the form owner");
- contentElement.removeAttribute('novalidate');
+ contentElement.removeAttribute("novalidate");
e.remove();
});
}
function todo_check(aBrowser, aElementName, aBarred) {
return ContentTask.spawn(aBrowser, [aElementName, aBarred], function*([aElementName, aBarred]) {
let e = content.document.createElement(aElementName);
- let contentElement = content.document.getElementById('content');
+ let contentElement = content.document.getElementById("content");
contentElement.appendChild(e);
let caught = false;
try {
- e.setCustomValidity('foo');
+ e.setCustomValidity("foo");
} catch (e) {
caught = true;
}
todo(!caught, "setCustomValidity should exist for " + aElementName);
e.remove();
});
@@ -57,31 +57,31 @@ function todo_check(aBrowser, aElementNa
add_task(function*() {
yield BrowserTestUtils.withNewTab({
gBrowser,
url: "data:text/html,<!DOCTYPE html><html><body><form id='content'></form></body></html>",
}, function*(browser) {
let testData = [
/* element name, barred */
- [ 'input', false, null],
- [ 'textarea', false, null],
- [ 'button', true, 'button'],
- [ 'button', false, 'submit'],
- [ 'select', false, null],
- [ 'output', true, null],
- [ 'fieldset', true, null],
- [ 'object', true, null],
+ [ "input", false, null],
+ [ "textarea", false, null],
+ [ "button", true, "button"],
+ [ "button", false, "submit"],
+ [ "select", false, null],
+ [ "output", true, null],
+ [ "fieldset", true, null],
+ [ "object", true, null],
];
for (let data of testData) {
yield check(browser, data[0], data[1], data[2]);
}
let todo_testData = [
- [ 'keygen', 'false' ],
+ [ "keygen", "false" ],
];
for (let data of todo_testData) {
yield todo_check(browser, data[0], data[1]);
}
});
});
--- a/toolkit/components/urlformatter/tests/unit/test_urlformatter.js
+++ b/toolkit/components/urlformatter/tests/unit/test_urlformatter.js
@@ -1,18 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function run_test() {
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Ci.nsIURLFormatter);
var locale = Cc["@mozilla.org/chrome/chrome-registry;1"].
getService(Ci.nsIXULChromeRegistry).
- getSelectedLocale('global');
- var prefs = Cc['@mozilla.org/preferences-service;1'].
+ getSelectedLocale("global");
+ var prefs = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
var sysInfo = Cc["@mozilla.org/system-info;1"].
getService(Ci.nsIPropertyBag2);
var OSVersion = sysInfo.getProperty("name") + " " +
sysInfo.getProperty("version");
try {
OSVersion += " (" + sysInfo.getProperty("secondaryLibrary") + ")";
} catch (e) {}
--- a/toolkit/components/utils/simpleServices.js
+++ b/toolkit/components/utils/simpleServices.js
@@ -58,17 +58,17 @@ AddonPolicyService.prototype = {
/**
* Returns the generated background page as a data-URI, if any. If the addon
* does not have an auto-generated background page, an empty string is
* returned.
*/
getGeneratedBackgroundPageUrl(aAddonId) {
let cb = this.backgroundPageUrlCallbacks.get(aAddonId);
- return cb && cb(aAddonId) || '';
+ return cb && cb(aAddonId) || "";
},
/*
* Invokes a callback (if any) associated with the addon to determine whether
* the addon is granted the |aPerm| API permission.
*
* @see nsIAddonPolicyService.addonHasPermission
*/
--- a/toolkit/components/viewconfig/content/config.js
+++ b/toolkit/components/viewconfig/content/config.js
@@ -383,17 +383,17 @@ function onConfigUnload() {
function FilterPrefs() {
if (document.getElementById("configDeck").getAttribute("selectedIndex") != 1) {
return;
}
var substring = document.getElementById("textbox").value;
// Check for "/regex/[i]"
- if (substring.charAt(0) == '/') {
+ if (substring.charAt(0) == "/") {
var r = substring.match(/^\/(.*)\/(i?)$/);
try {
gFilter = RegExp(r[1], r[2]);
} catch (e) {
return; // Do nothing on incomplete or bad RegExp
}
} else if (substring) {
gFilter = RegExp(substring.replace(/([^* \w])/g, "\\$1")
@@ -504,17 +504,17 @@ function updateContextMenu() {
var toggleSelected = document.getElementById("toggleSelected");
toggleSelected.setAttribute("disabled", isLocked);
toggleSelected.hidden = !canToggle;
}
function copyPref() {
var pref = gPrefView[view.selection.currentIndex];
- gClipboardHelper.copyString(pref.prefCol + ';' + pref.valueCol);
+ gClipboardHelper.copyString(pref.prefCol + ";" + pref.valueCol);
}
function copyName() {
gClipboardHelper.copyString(gPrefView[view.selection.currentIndex].prefCol);
}
function copyValue() {
gClipboardHelper.copyString(gPrefView[view.selection.currentIndex].valueCol);
--- a/toolkit/components/viewsource/content/viewSourceUtils.js
+++ b/toolkit/components/viewsource/content/viewSourceUtils.js
@@ -361,17 +361,17 @@ var gViewSourceUtils = {
// Returns nsIProcess of the external view source editor or null
getExternalViewSourceEditor() {
try {
let viewSourceAppPath =
Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch)
.getComplexValue("view_source.editor.path",
Components.interfaces.nsIFile);
- let editor = Components.classes['@mozilla.org/process/util;1']
+ let editor = Components.classes["@mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
editor.init(viewSourceAppPath);
return editor;
} catch (ex) {
Components.utils.reportError(ex);
}
--- a/toolkit/components/xulstore/XULStore.js
+++ b/toolkit/components/xulstore/XULStore.js
@@ -15,17 +15,17 @@ const debugMode = false;
const WRITE_DELAY_MS = (debugMode ? 3 : 30) * 1000;
const XULSTORE_CONTRACTID = "@mozilla.org/xul/xulstore;1";
const XULSTORE_CID = Components.ID("{6f46b6f4-c8b1-4bd4-a4fa-9ebbed0753ea}");
const STOREDB_FILENAME = "xulstore.json";
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm");
function XULStore() {
if (!Services.appinfo.inSafeMode)
this.load();
}
--- a/toolkit/components/xulstore/tests/xpcshell/test_XULStore.js
+++ b/toolkit/components/xulstore/tests/xpcshell/test_XULStore.js
@@ -58,33 +58,33 @@ function getAttributes(uri, id) {
function checkArrays(a, b) {
a.sort();
b.sort();
do_check_true(a.toString() == b.toString());
}
function checkOldStore() {
- checkArrays(['addon-bar', 'main-window', 'sidebar-title'], getIDs(browserURI));
- checkArrays(['collapsed'], getAttributes(browserURI, 'addon-bar'));
- checkArrays(['height', 'screenX', 'screenY', 'sizemode', 'width'],
- getAttributes(browserURI, 'main-window'));
- checkArrays(['value'], getAttributes(browserURI, 'sidebar-title'));
+ checkArrays(["addon-bar", "main-window", "sidebar-title"], getIDs(browserURI));
+ checkArrays(["collapsed"], getAttributes(browserURI, "addon-bar"));
+ checkArrays(["height", "screenX", "screenY", "sizemode", "width"],
+ getAttributes(browserURI, "main-window"));
+ checkArrays(["value"], getAttributes(browserURI, "sidebar-title"));
checkValue(browserURI, "addon-bar", "collapsed", "true");
checkValue(browserURI, "main-window", "width", "994");
checkValue(browserURI, "main-window", "height", "768");
checkValue(browserURI, "main-window", "screenX", "4");
checkValue(browserURI, "main-window", "screenY", "22");
checkValue(browserURI, "main-window", "sizemode", "normal");
checkValue(browserURI, "sidebar-title", "value", "");
- checkArrays(['lockCol', 'prefCol'], getIDs(aboutURI));
- checkArrays(['ordinal'], getAttributes(aboutURI, 'lockCol'));
- checkArrays(['ordinal', 'sortDirection'], getAttributes(aboutURI, 'prefCol'));
+ checkArrays(["lockCol", "prefCol"], getIDs(aboutURI));
+ checkArrays(["ordinal"], getAttributes(aboutURI, "lockCol"));
+ checkArrays(["ordinal", "sortDirection"], getAttributes(aboutURI, "prefCol"));
checkValue(aboutURI, "prefCol", "ordinal", "1");
checkValue(aboutURI, "prefCol", "sortDirection", "ascending");
checkValue(aboutURI, "lockCol", "ordinal", "3");
}
add_task(function* testImport() {
let src = "localstore.rdf";
@@ -129,41 +129,41 @@ add_task(function* testHasValue() {
});
add_task(function* testSetValue() {
// Set new attribute
checkValue(browserURI, "side-bar", "width", "");
XULStore.setValue(browserURI, "side-bar", "width", "1000");
checkValue(browserURI, "side-bar", "width", "1000");
checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["width"], getAttributes(browserURI, 'side-bar'));
+ checkArrays(["width"], getAttributes(browserURI, "side-bar"));
// Modify existing property
checkValue(browserURI, "side-bar", "width", "1000");
XULStore.setValue(browserURI, "side-bar", "width", "1024");
checkValue(browserURI, "side-bar", "width", "1024");
checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["width"], getAttributes(browserURI, 'side-bar'));
+ checkArrays(["width"], getAttributes(browserURI, "side-bar"));
// Add another attribute
checkValue(browserURI, "side-bar", "height", "");
XULStore.setValue(browserURI, "side-bar", "height", "1000");
checkValue(browserURI, "side-bar", "height", "1000");
checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["width", "height"], getAttributes(browserURI, 'side-bar'));
+ checkArrays(["width", "height"], getAttributes(browserURI, "side-bar"));
});
add_task(function* testRemoveValue() {
// Remove first attribute
checkValue(browserURI, "side-bar", "width", "1024");
XULStore.removeValue(browserURI, "side-bar", "width");
checkValue(browserURI, "side-bar", "width", "");
checkValueExists(browserURI, "side-bar", "width", false);
checkArrays(["addon-bar", "main-window", "side-bar", "sidebar-title"], getIDs(browserURI));
- checkArrays(["height"], getAttributes(browserURI, 'side-bar'));
+ checkArrays(["height"], getAttributes(browserURI, "side-bar"));
// Remove second attribute
checkValue(browserURI, "side-bar", "height", "1000");
XULStore.removeValue(browserURI, "side-bar", "height");
checkValue(browserURI, "side-bar", "height", "");
checkArrays(["addon-bar", "main-window", "sidebar-title"], getIDs(browserURI));
// Removing an attribute that doesn't exists shouldn't fail
--- a/toolkit/content/aboutNetworking.js
+++ b/toolkit/content/aboutNetworking.js
@@ -1,23 +1,23 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
const FileUtils = Cu.import("resource://gre/modules/FileUtils.jsm").FileUtils
const gEnv = Cc["@mozilla.org/process/environment;1"]
.getService(Ci.nsIEnvironment);
-const gDashboard = Cc['@mozilla.org/network/dashboard;1']
+const gDashboard = Cc["@mozilla.org/network/dashboard;1"]
.getService(Ci.nsIDashboard);
const gDirServ = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIDirectoryServiceProvider);
const gRequestNetworkingData = {
"http": gDashboard.requestHttpConnections,
"sockets": gDashboard.requestSockets,
"dns": gDashboard.requestDNSInfo,
@@ -28,95 +28,95 @@ const gDashboardCallbacks = {
"sockets": displaySockets,
"dns": displayDns,
"websockets": displayWebsockets
};
const REFRESH_INTERVAL_MS = 3000;
function col(element) {
- let col = document.createElement('td');
+ let col = document.createElement("td");
let content = document.createTextNode(element);
col.appendChild(content);
return col;
}
function displayHttp(data) {
- let cont = document.getElementById('http_content');
+ let cont = document.getElementById("http_content");
let parent = cont.parentNode;
- let new_cont = document.createElement('tbody');
- new_cont.setAttribute('id', 'http_content');
+ let new_cont = document.createElement("tbody");
+ new_cont.setAttribute("id", "http_content");
for (let i = 0; i < data.connections.length; i++) {
- let row = document.createElement('tr');
+ let row = document.createElement("tr");
row.appendChild(col(data.connections[i].host));
row.appendChild(col(data.connections[i].port));
row.appendChild(col(data.connections[i].spdy));
row.appendChild(col(data.connections[i].ssl));
row.appendChild(col(data.connections[i].active.length));
row.appendChild(col(data.connections[i].idle.length));
new_cont.appendChild(row);
}
parent.replaceChild(new_cont, cont);
}
function displaySockets(data) {
- let cont = document.getElementById('sockets_content');
+ let cont = document.getElementById("sockets_content");
let parent = cont.parentNode;
- let new_cont = document.createElement('tbody');
- new_cont.setAttribute('id', 'sockets_content');
+ let new_cont = document.createElement("tbody");
+ new_cont.setAttribute("id", "sockets_content");
for (let i = 0; i < data.sockets.length; i++) {
- let row = document.createElement('tr');
+ let row = document.createElement("tr");
row.appendChild(col(data.sockets[i].host));
row.appendChild(col(data.sockets[i].port));
row.appendChild(col(data.sockets[i].tcp));
row.appendChild(col(data.sockets[i].active));
row.appendChild(col(data.sockets[i].sent));
row.appendChild(col(data.sockets[i].received));
new_cont.appendChild(row);
}
parent.replaceChild(new_cont, cont);
}
function displayDns(data) {
- let cont = document.getElementById('dns_content');
+ let cont = document.getElementById("dns_content");
let parent = cont.parentNode;
- let new_cont = document.createElement('tbody');
- new_cont.setAttribute('id', 'dns_content');
+ let new_cont = document.createElement("tbody");
+ new_cont.setAttribute("id", "dns_content");
for (let i = 0; i < data.entries.length; i++) {
- let row = document.createElement('tr');
+ let row = document.createElement("tr");
row.appendChild(col(data.entries[i].hostname));
row.appendChild(col(data.entries[i].family));
- let column = document.createElement('td');
+ let column = document.createElement("td");
for (let j = 0; j < data.entries[i].hostaddr.length; j++) {
column.appendChild(document.createTextNode(data.entries[i].hostaddr[j]));
- column.appendChild(document.createElement('br'));
+ column.appendChild(document.createElement("br"));
}
row.appendChild(column);
row.appendChild(col(data.entries[i].expiration));
new_cont.appendChild(row);
}
parent.replaceChild(new_cont, cont);
}
function displayWebsockets(data) {
- let cont = document.getElementById('websockets_content');
+ let cont = document.getElementById("websockets_content");
let parent = cont.parentNode;
- let new_cont = document.createElement('tbody');
- new_cont.setAttribute('id', 'websockets_content');
+ let new_cont = document.createElement("tbody");
+ new_cont.setAttribute("id", "websockets_content");
for (let i = 0; i < data.websockets.length; i++) {
- let row = document.createElement('tr');
+ let row = document.createElement("tr");
row.appendChild(col(data.websockets[i].hostport));
row.appendChild(col(data.websockets[i].encrypted));
row.appendChild(col(data.websockets[i].msgsent));
row.appendChild(col(data.websockets[i].msgreceived));
row.appendChild(col(data.websockets[i].sentsize));
row.appendChild(col(data.websockets[i].receivedsize));
new_cont.appendChild(row);
}
--- a/toolkit/content/aboutProfiles.js
+++ b/toolkit/content/aboutProfiles.js
@@ -1,29 +1,29 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
-Cu.import('resource://gre/modules/AppConstants.jsm');
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/AppConstants.jsm");
XPCOMUtils.defineLazyServiceGetter(
this,
- 'ProfileService',
- '@mozilla.org/toolkit/profile-service;1',
- 'nsIToolkitProfileService'
+ "ProfileService",
+ "@mozilla.org/toolkit/profile-service;1",
+ "nsIToolkitProfileService"
);
const bundle = Services.strings.createBundle(
- 'chrome://global/locale/aboutProfiles.properties');
+ "chrome://global/locale/aboutProfiles.properties");
// nsIToolkitProfileService.selectProfile can be used only during the selection
// of the profile in the ProfileManager. If we are showing about:profiles in a
// tab, the selectedProfile returns the default profile.
// In this function we use the ProfD to find the current profile.
function findCurrentProfile() {
let cpd;
try {
@@ -47,17 +47,17 @@ function findCurrentProfile() {
try {
return ProfileService.selectedProfile;
} catch (e) {
return null;
}
}
function refreshUI() {
- let parent = document.getElementById('profiles');
+ let parent = document.getElementById("profiles");
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
let defaultProfile;
try {
defaultProfile = ProfileService.defaultProfile;
} catch (e) {}
@@ -67,193 +67,193 @@ function refreshUI() {
let iter = ProfileService.profiles;
while (iter.hasMoreElements()) {
let profile = iter.getNext().QueryInterface(Ci.nsIToolkitProfile);
display({ profile,
isDefault: profile == defaultProfile,
isCurrentProfile: profile == currentProfile });
}
- let createButton = document.getElementById('create-button');
+ let createButton = document.getElementById("create-button");
createButton.onclick = createProfileWizard;
- let restartSafeModeButton = document.getElementById('restart-in-safe-mode-button');
+ let restartSafeModeButton = document.getElementById("restart-in-safe-mode-button");
restartSafeModeButton.onclick = function() { restart(true); }
- let restartNormalModeButton = document.getElementById('restart-button');
+ let restartNormalModeButton = document.getElementById("restart-button");
restartNormalModeButton.onclick = function() { restart(false); }
}
function openDirectory(dir) {
let nsLocalFile = Components.Constructor("@mozilla.org/file/local;1",
"nsILocalFile", "initWithPath");
new nsLocalFile(dir).reveal();
}
function display(profileData) {
- let parent = document.getElementById('profiles');
+ let parent = document.getElementById("profiles");
- let div = document.createElement('div');
+ let div = document.createElement("div");
parent.appendChild(div);
- let nameStr = bundle.formatStringFromName('name', [profileData.profile.name], 1);
+ let nameStr = bundle.formatStringFromName("name", [profileData.profile.name], 1);
- let name = document.createElement('h2');
+ let name = document.createElement("h2");
name.appendChild(document.createTextNode(nameStr));
div.appendChild(name);
if (profileData.isCurrentProfile) {
- let currentProfile = document.createElement('h3');
- let currentProfileStr = bundle.GetStringFromName('currentProfile');
+ let currentProfile = document.createElement("h3");
+ let currentProfileStr = bundle.GetStringFromName("currentProfile");
currentProfile.appendChild(document.createTextNode(currentProfileStr));
div.appendChild(currentProfile);
}
- let table = document.createElement('table');
+ let table = document.createElement("table");
div.appendChild(table);
- let tbody = document.createElement('tbody');
+ let tbody = document.createElement("tbody");
table.appendChild(tbody);
function createItem(title, value, dir = false) {
- let tr = document.createElement('tr');
+ let tr = document.createElement("tr");
tbody.appendChild(tr);
- let th = document.createElement('th');
- th.setAttribute('class', 'column');
+ let th = document.createElement("th");
+ th.setAttribute("class", "column");
th.appendChild(document.createTextNode(title));
tr.appendChild(th);
- let td = document.createElement('td');
+ let td = document.createElement("td");
td.appendChild(document.createTextNode(value));
tr.appendChild(td);
if (dir) {
- td.appendChild(document.createTextNode(' '));
- let button = document.createElement('button');
- let string = 'openDir';
+ td.appendChild(document.createTextNode(" "));
+ let button = document.createElement("button");
+ let string = "openDir";
if (AppConstants.platform == "win") {
- string = 'winOpenDir2';
+ string = "winOpenDir2";
} else if (AppConstants.platform == "macosx") {
- string = 'macOpenDir';
+ string = "macOpenDir";
}
let buttonText = document.createTextNode(bundle.GetStringFromName(string));
button.appendChild(buttonText);
td.appendChild(button);
- button.addEventListener('click', function(e) {
+ button.addEventListener("click", function(e) {
openDirectory(value);
});
}
}
- createItem(bundle.GetStringFromName('isDefault'),
- profileData.isDefault ? bundle.GetStringFromName('yes') : bundle.GetStringFromName('no'));
+ createItem(bundle.GetStringFromName("isDefault"),
+ profileData.isDefault ? bundle.GetStringFromName("yes") : bundle.GetStringFromName("no"));
- createItem(bundle.GetStringFromName('rootDir'), profileData.profile.rootDir.path, true);
+ createItem(bundle.GetStringFromName("rootDir"), profileData.profile.rootDir.path, true);
if (profileData.profile.localDir.path != profileData.profile.rootDir.path) {
- createItem(bundle.GetStringFromName('localDir'), profileData.profile.localDir.path, true);
+ createItem(bundle.GetStringFromName("localDir"), profileData.profile.localDir.path, true);
}
- let renameButton = document.createElement('button');
- renameButton.appendChild(document.createTextNode(bundle.GetStringFromName('rename')));
+ let renameButton = document.createElement("button");
+ renameButton.appendChild(document.createTextNode(bundle.GetStringFromName("rename")));
renameButton.onclick = function() {
renameProfile(profileData.profile);
};
div.appendChild(renameButton);
if (!profileData.isCurrentProfile) {
- let removeButton = document.createElement('button');
- removeButton.appendChild(document.createTextNode(bundle.GetStringFromName('remove')));
+ let removeButton = document.createElement("button");
+ removeButton.appendChild(document.createTextNode(bundle.GetStringFromName("remove")));
removeButton.onclick = function() {
removeProfile(profileData.profile);
};
div.appendChild(removeButton);
}
if (!profileData.isDefault) {
- let defaultButton = document.createElement('button');
- defaultButton.appendChild(document.createTextNode(bundle.GetStringFromName('setAsDefault')));
+ let defaultButton = document.createElement("button");
+ defaultButton.appendChild(document.createTextNode(bundle.GetStringFromName("setAsDefault")));
defaultButton.onclick = function() {
defaultProfile(profileData.profile);
};
div.appendChild(defaultButton);
}
if (!profileData.isCurrentProfile) {
- let runButton = document.createElement('button');
- runButton.appendChild(document.createTextNode(bundle.GetStringFromName('launchProfile')));
+ let runButton = document.createElement("button");
+ runButton.appendChild(document.createTextNode(bundle.GetStringFromName("launchProfile")));
runButton.onclick = function() {
openProfile(profileData.profile);
};
div.appendChild(runButton);
}
- let sep = document.createElement('hr');
+ let sep = document.createElement("hr");
div.appendChild(sep);
}
function CreateProfile(profile) {
ProfileService.selectedProfile = profile;
ProfileService.flush();
refreshUI();
}
function createProfileWizard() {
// This should be rewritten in HTML eventually.
- window.openDialog('chrome://mozapps/content/profile/createProfileWizard.xul',
- '', 'centerscreen,chrome,modal,titlebar',
+ window.openDialog("chrome://mozapps/content/profile/createProfileWizard.xul",
+ "", "centerscreen,chrome,modal,titlebar",
ProfileService);
}
function renameProfile(profile) {
- let title = bundle.GetStringFromName('renameProfileTitle');
- let msg = bundle.formatStringFromName('renameProfile', [profile.name], 1);
+ let title = bundle.GetStringFromName("renameProfileTitle");
+ let msg = bundle.formatStringFromName("renameProfile", [profile.name], 1);
let newName = { value: profile.name };
if (Services.prompt.prompt(window, title, msg, newName, null,
{ value: 0 })) {
newName = newName.value;
if (newName == profile.name) {
return;
}
try {
profile.name = newName;
} catch (e) {
- let title = bundle.GetStringFromName('invalidProfileNameTitle');
- let msg = bundle.formatStringFromName('invalidProfileName', [newName], 1);
+ let title = bundle.GetStringFromName("invalidProfileNameTitle");
+ let msg = bundle.formatStringFromName("invalidProfileName", [newName], 1);
Services.prompt.alert(window, title, msg);
return;
}
ProfileService.flush();
refreshUI();
}
}
function removeProfile(profile) {
let deleteFiles = false;
if (profile.rootDir.exists()) {
- let title = bundle.GetStringFromName('deleteProfileTitle');
- let msg = bundle.formatStringFromName('deleteProfileConfirm',
+ let title = bundle.GetStringFromName("deleteProfileTitle");
+ let msg = bundle.formatStringFromName("deleteProfileConfirm",
[profile.rootDir.path], 1);
let buttonPressed = Services.prompt.confirmEx(window, title, msg,
(Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0) +
(Services.prompt.BUTTON_TITLE_CANCEL * Services.prompt.BUTTON_POS_1) +
(Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_2),
- bundle.GetStringFromName('dontDeleteFiles'),
+ bundle.GetStringFromName("dontDeleteFiles"),
null,
- bundle.GetStringFromName('deleteFiles'),
+ bundle.GetStringFromName("deleteFiles"),
null, {value:0});
if (buttonPressed == 1) {
return;
}
if (buttonPressed == 2) {
deleteFiles = true;
}
@@ -328,12 +328,12 @@ function restart(safeMode) {
if (safeMode) {
Services.startup.restartInSafeMode(flags);
} else {
Services.startup.quit(flags);
}
}
-window.addEventListener('DOMContentLoaded', function load() {
- window.removeEventListener('DOMContentLoaded', load);
+window.addEventListener("DOMContentLoaded", function load() {
+ window.removeEventListener("DOMContentLoaded", load);
refreshUI();
});
--- a/toolkit/content/aboutServiceWorkers.js
+++ b/toolkit/content/aboutServiceWorkers.js
@@ -1,18 +1,18 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
Cu.import("resource://gre/modules/Services.jsm");
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
const bundle = Services.strings.createBundle(
"chrome://global/locale/aboutServiceWorkers.properties");
const brandBundle = Services.strings.createBundle(
"chrome://branding/locale/brand.properties");
var gSWM;
@@ -63,44 +63,44 @@ function init() {
display(info, ps);
}
}
function display(info, pushService) {
let parent = document.getElementById("serviceworkers");
- let div = document.createElement('div');
+ let div = document.createElement("div");
parent.appendChild(div);
- let title = document.createElement('h2');
- let titleStr = bundle.formatStringFromName('title', [info.principal.origin], 1);
+ let title = document.createElement("h2");
+ let titleStr = bundle.formatStringFromName("title", [info.principal.origin], 1);
title.appendChild(document.createTextNode(titleStr));
div.appendChild(title);
if (info.principal.appId) {
- let b2gtitle = document.createElement('h3');
- let trueFalse = bundle.GetStringFromName(info.principal.isInIsolatedMozBrowserElement ? 'true' : 'false');
+ let b2gtitle = document.createElement("h3");
+ let trueFalse = bundle.GetStringFromName(info.principal.isInIsolatedMozBrowserElement ? "true" : "false");
let b2gtitleStr =
- bundle.formatStringFromName('b2gtitle', [ brandBundle.getString("brandShortName"),
+ bundle.formatStringFromName("b2gtitle", [ brandBundle.getString("brandShortName"),
info.principal.appId,
trueFalse], 2);
b2gtitle.appendChild(document.createTextNode(b2gtitleStr));
div.appendChild(b2gtitle);
}
- let list = document.createElement('ul');
+ let list = document.createElement("ul");
div.appendChild(list);
function createItem(title, value, makeLink) {
- let item = document.createElement('li');
+ let item = document.createElement("li");
list.appendChild(item);
- let bold = document.createElement('strong');
+ let bold = document.createElement("strong");
bold.appendChild(document.createTextNode(title + " "));
item.appendChild(bold);
let textNode = document.createTextNode(value);
if (makeLink) {
let link = document.createElement("a");
link.href = value;
@@ -109,75 +109,75 @@ function display(info, pushService) {
item.appendChild(link);
} else {
item.appendChild(textNode);
}
return textNode;
}
- createItem(bundle.GetStringFromName('scope'), info.scope);
- createItem(bundle.GetStringFromName('scriptSpec'), info.scriptSpec, true);
+ createItem(bundle.GetStringFromName("scope"), info.scope);
+ createItem(bundle.GetStringFromName("scriptSpec"), info.scriptSpec, true);
let currentWorkerURL = info.activeWorker ? info.activeWorker.scriptSpec : "";
- createItem(bundle.GetStringFromName('currentWorkerURL'), currentWorkerURL, true);
+ createItem(bundle.GetStringFromName("currentWorkerURL"), currentWorkerURL, true);
let activeCacheName = info.activeWorker ? info.activeWorker.cacheName : "";
- createItem(bundle.GetStringFromName('activeCacheName'), activeCacheName);
+ createItem(bundle.GetStringFromName("activeCacheName"), activeCacheName);
let waitingCacheName = info.waitingWorker ? info.waitingWorker.cacheName : "";
- createItem(bundle.GetStringFromName('waitingCacheName'), waitingCacheName);
+ createItem(bundle.GetStringFromName("waitingCacheName"), waitingCacheName);
- let pushItem = createItem(bundle.GetStringFromName('pushEndpoint'), bundle.GetStringFromName('waiting'));
+ let pushItem = createItem(bundle.GetStringFromName("pushEndpoint"), bundle.GetStringFromName("waiting"));
if (pushService) {
pushService.getSubscription(info.scope, info.principal, (status, pushRecord) => {
if (Components.isSuccessCode(status)) {
pushItem.data = JSON.stringify(pushRecord);
} else {
dump("about:serviceworkers - retrieving push registration failed\n");
}
});
}
let updateButton = document.createElement("button");
- updateButton.appendChild(document.createTextNode(bundle.GetStringFromName('update')));
+ updateButton.appendChild(document.createTextNode(bundle.GetStringFromName("update")));
updateButton.onclick = function() {
gSWM.propagateSoftUpdate(info.principal.originAttributes, info.scope);
};
div.appendChild(updateButton);
let unregisterButton = document.createElement("button");
- unregisterButton.appendChild(document.createTextNode(bundle.GetStringFromName('unregister')));
+ unregisterButton.appendChild(document.createTextNode(bundle.GetStringFromName("unregister")));
div.appendChild(unregisterButton);
- let loadingMessage = document.createElement('span');
- loadingMessage.appendChild(document.createTextNode(bundle.GetStringFromName('waiting')));
- loadingMessage.classList.add('inactive');
+ let loadingMessage = document.createElement("span");
+ loadingMessage.appendChild(document.createTextNode(bundle.GetStringFromName("waiting")));
+ loadingMessage.classList.add("inactive");
div.appendChild(loadingMessage);
unregisterButton.onclick = function() {
let cb = {
unregisterSucceeded() {
parent.removeChild(div);
if (!--gSWCount) {
let div = document.getElementById("warning_no_serviceworkers");
div.classList.add("active");
}
},
unregisterFailed() {
- alert(bundle.GetStringFromName('unregisterError'));
+ alert(bundle.GetStringFromName("unregisterError"));
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsIServiceWorkerUnregisterCallback])
};
- loadingMessage.classList.remove('inactive');
+ loadingMessage.classList.remove("inactive");
gSWM.propagateUnregister(info.principal, cb, info.scope);
};
- let sep = document.createElement('hr');
+ let sep = document.createElement("hr");
div.appendChild(sep);
++gSWCount;
}
window.addEventListener("DOMContentLoaded", function load() {
window.removeEventListener("DOMContentLoaded", load);
init();
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -212,25 +212,25 @@ var snapshotFormatters = {
}
return nameOrMsg;
}
// Read APZ info out of data.info, stripping it out in the process.
let apzInfo = [];
let formatApzInfo = function(info) {
let out = [];
- for (let type of ['Wheel', 'Touch', 'Drag']) {
- let key = 'Apz' + type + 'Input';
+ for (let type of ["Wheel", "Touch", "Drag"]) {
+ let key = "Apz" + type + "Input";
if (!(key in info))
continue;
delete info[key];
- let message = localizedMsg([type.toLowerCase() + 'Enabled']);
+ let message = localizedMsg([type.toLowerCase() + "Enabled"]);
out.push(message);
}
return out;
};
// Create a <tr> element with key and value columns.
//
--- a/toolkit/content/aboutTelemetry.js
+++ b/toolkit/content/aboutTelemetry.js
@@ -1,13 +1,13 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/TelemetryTimestamps.jsm");
Cu.import("resource://gre/modules/TelemetryController.jsm");
@@ -56,17 +56,17 @@ var documentRTLMode = "";
*/
function isRTL() {
if (!documentRTLMode)
documentRTLMode = window.getComputedStyle(document.body).direction;
return (documentRTLMode == "rtl");
}
function isArray(arg) {
- return Object.prototype.toString.call(arg) === '[object Array]';
+ return Object.prototype.toString.call(arg) === "[object Array]";
}
function isFlatArray(obj) {
if (!isArray(obj)) {
return false;
}
return !obj.some(e => typeof(e) == "object");
}
@@ -949,33 +949,33 @@ var StackRenderer = {
let stackText = " " + aStack.join(" ");
aDiv.appendChild(document.createTextNode(stackText));
aDiv.appendChild(document.createElement("br"));
aDiv.appendChild(document.createElement("br"));
},
renderStacks: function StackRenderer_renderStacks(aPrefix, aStacks,
aMemoryMap, aRenderHeader) {
- let div = document.getElementById(aPrefix + '-data');
+ let div = document.getElementById(aPrefix + "-data");
removeAllChildNodes(div);
- let fetchE = document.getElementById(aPrefix + '-fetch-symbols');
+ let fetchE = document.getElementById(aPrefix + "-fetch-symbols");
if (fetchE) {
fetchE.classList.remove("hidden");
}
- let hideE = document.getElementById(aPrefix + '-hide-symbols');
+ let hideE = document.getElementById(aPrefix + "-hide-symbols");
if (hideE) {
hideE.classList.add("hidden");
}
if (aStacks.length == 0) {
return;
}
- setHasData(aPrefix + '-section', true);
+ setHasData(aPrefix + "-section", true);
this.renderMemoryMap(div, aMemoryMap);
for (let i = 0; i < aStacks.length; ++i) {
let stack = aStacks[i];
aRenderHeader(i);
this.renderStack(div, stack)
}
@@ -1343,17 +1343,17 @@ var Histogram = {
let belowEm = Math.round(MAX_BAR_HEIGHT * (barValue / maxBarValue) * 10) / 10;
let aboveEm = MAX_BAR_HEIGHT - belowEm;
let barDiv = document.createElement("div");
barDiv.className = "bar";
barDiv.style.paddingTop = aboveEm + "em";
// Add value label or an nbsp if no value
- barDiv.appendChild(document.createTextNode(value ? value : '\u00A0'));
+ barDiv.appendChild(document.createTextNode(value ? value : "\u00A0"));
// Create the blue bar
let bar = document.createElement("div");
bar.className = "bar-inner";
bar.style.height = belowEm + "em";
barDiv.appendChild(bar);
// Add bucket label
@@ -1920,32 +1920,32 @@ var LateWritesSingleton = {
renderLateWrites: function LateWritesSingleton_renderLateWrites(lateWrites) {
setHasData("late-writes-section", !!lateWrites);
if (!lateWrites) {
return;
}
let stacks = lateWrites.stacks;
let memoryMap = lateWrites.memoryMap;
- StackRenderer.renderStacks('late-writes', stacks, memoryMap,
+ StackRenderer.renderStacks("late-writes", stacks, memoryMap,
LateWritesSingleton.renderHeader);
}
};
/**
* Helper function for sorting the startup milestones in the Simple Measurements
* section into temporal order.
*
* @param aSimpleMeasurements Telemetry ping's "Simple Measurements" data
* @return Sorted measurements
*/
function sortStartupMilestones(aSimpleMeasurements) {
const telemetryTimestamps = TelemetryTimestamps.get();
let startupEvents = Services.startup.getStartupInfo();
- delete startupEvents['process'];
+ delete startupEvents["process"];
function keyIsMilestone(k) {
return (k in startupEvents) || (k in telemetryTimestamps);
}
let sortedKeys = Object.keys(aSimpleMeasurements);
// Sort the measurements, with startup milestones at the front + ordered by time
--- a/toolkit/content/browser-child.js
+++ b/toolkit/content/browser-child.js
@@ -5,17 +5,17 @@
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;
var Cr = Components.results;
Cu.import("resource://gre/modules/AppConstants.jsm");
Cu.import("resource://gre/modules/BrowserUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
-Cu.import('resource://gre/modules/XPCOMUtils.jsm');
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/RemoteAddonsChild.jsm");
Cu.import("resource://gre/modules/Timer.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PageThumbUtils",
"resource://gre/modules/PageThumbUtils.jsm");
if (AppConstants.MOZ_CRASHREPORTER) {
XPCOMUtils.defineLazyServiceGetter(this, "CrashReporter",
@@ -446,21 +446,21 @@ const ZoomManager = {
},
set textZoom(value) {
this._cache.textZoom = value;
this._markupViewer.textZoom = value;
},
refreshFullZoom() {
- return this._refreshZoomValue('fullZoom');
+ return this._refreshZoomValue("fullZoom");
},
refreshTextZoom() {
- return this._refreshZoomValue('textZoom');
+ return this._refreshZoomValue("textZoom");
},
/**
* Retrieves specified zoom property value from markupViewer and refreshes
* cache if needed.
* @param valueName Either 'fullZoom' or 'textZoom'.
* @returns Returns true if cached value was actually refreshed.
* @private
--- a/toolkit/content/browser-content.js
+++ b/toolkit/content/browser-content.js
@@ -65,36 +65,36 @@ var ClickEventHandler = {
node = node.parentNode;
}
return false;
},
findNearestScrollableElement(aNode) {
// this is a list of overflow property values that allow scrolling
- const scrollingAllowed = ['scroll', 'auto'];
+ const scrollingAllowed = ["scroll", "auto"];
// go upward in the DOM and find any parent element that has a overflow
// area and can therefore be scrolled
for (this._scrollable = aNode; this._scrollable;
this._scrollable = this._scrollable.parentNode) {
// do not use overflow based autoscroll for <html> and <body>
// Elements or non-html elements such as svg or Document nodes
// also make sure to skip select elements that are not multiline
if (!(this._scrollable instanceof content.HTMLElement) ||
((this._scrollable instanceof content.HTMLSelectElement) && !this._scrollable.multiple)) {
continue;
}
var overflowx = this._scrollable.ownerDocument.defaultView
- .getComputedStyle(this._scrollable, '')
- .getPropertyValue('overflow-x');
+ .getComputedStyle(this._scrollable, "")
+ .getPropertyValue("overflow-x");
var overflowy = this._scrollable.ownerDocument.defaultView
- .getComputedStyle(this._scrollable, '')
- .getPropertyValue('overflow-y');
+ .getComputedStyle(this._scrollable, "")
+ .getPropertyValue("overflow-y");
// we already discarded non-multiline selects so allow vertical
// scroll for multiline ones directly without checking for a
// overflow property
var scrollVert = this._scrollable.scrollTopMax &&
(this._scrollable instanceof content.HTMLSelectElement ||
scrollingAllowed.indexOf(overflowy) >= 0);
// do not allow horizontal scrolling for select elements, it leads
@@ -196,23 +196,23 @@ var ClickEventHandler = {
// we used to scroll |accelerate()| pixels every 20ms (50fps)
var timeCompensation = timeDelta / 20;
this._lastFrame = timestamp;
var actualScrollX = 0;
var actualScrollY = 0;
// don't bother scrolling vertically when the scrolldir is only horizontal
// and the other way around
- if (this._scrolldir != 'EW') {
+ if (this._scrolldir != "EW") {
var y = this.accelerate(this._screenY, this._startY) * timeCompensation;
var desiredScrollY = this._scrollErrorY + y;
actualScrollY = this.roundToZero(desiredScrollY);
this._scrollErrorY = (desiredScrollY - actualScrollY);
}
- if (this._scrolldir != 'NS') {
+ if (this._scrolldir != "NS") {
var x = this.accelerate(this._screenX, this._startX) * timeCompensation;
var desiredScrollX = this._scrollErrorX + x;
actualScrollX = this.roundToZero(desiredScrollX);
this._scrollErrorX = (desiredScrollX - actualScrollX);
}
const kAutoscroll = 15; // defined in mozilla/layers/ScrollInputMethods.h
Services.telemetry.getHistogramById("SCROLL_INPUT_METHODS").add(kAutoscroll);
@@ -894,17 +894,17 @@ let WebChannelMessageToChromeListener =
return this._cachedWhitelist;
},
_onMessageToChrome(e) {
// If target is window then we want the document principal, otherwise fallback to target itself.
let principal = e.target.nodePrincipal ? e.target.nodePrincipal : e.target.document.nodePrincipal;
if (e.detail) {
- if (typeof e.detail != 'string') {
+ if (typeof e.detail != "string") {
// Check if the principal is one of the ones that's allowed to send
// non-string values for e.detail. They're whitelisted by site origin,
// so we compare on originNoSuffix in order to avoid other origin attributes
// that are not relevant here, such as containers or private browsing.
let objectsAllowed = this._getWhitelistedPrincipals().some(whitelisted =>
principal.originNoSuffix == whitelisted.originNoSuffix);
if (!objectsAllowed) {
Cu.reportError("WebChannelMessageToChrome sent with an object from a non-whitelisted principal");
@@ -1258,43 +1258,43 @@ var ViewSelectionSource = {
return undefined;
// serialize
const VIEW_SOURCE_CSS = "resource://gre-resources/viewsource.css";
const BUNDLE_URL = "chrome://global/locale/viewSource.properties";
let bundle = Services.strings.createBundle(BUNDLE_URL);
var title = bundle.GetStringFromName("viewMathMLSourceTitle");
- var wrapClass = this.wrapLongLines ? ' class="wrap"' : '';
+ var wrapClass = this.wrapLongLines ? ' class="wrap"' : "";
var source =
- '<!DOCTYPE html>'
- + '<html>'
- + '<head><title>' + title + '</title>'
+ "<!DOCTYPE html>"
+ + "<html>"
+ + "<head><title>" + title + "</title>"
+ '<link rel="stylesheet" type="text/css" href="' + VIEW_SOURCE_CSS + '">'
+ '<style type="text/css">'
- + '#target { border: dashed 1px; background-color: lightyellow; }'
- + '</style>'
- + '</head>'
+ + "#target { border: dashed 1px; background-color: lightyellow; }"
+ + "</style>"
+ + "</head>"
+ '<body id="viewsource"' + wrapClass
+ ' onload="document.title=\'' + title + '\'; document.getElementById(\'target\').scrollIntoView(true)">'
- + '<pre>'
+ + "<pre>"
+ this.getOuterMarkup(topNode, 0)
- + '</pre></body></html>'
+ + "</pre></body></html>"
; // end
return { uri: "data:text/html;charset=utf-8," + encodeURIComponent(source),
drawSelection: false, baseURI: node.ownerDocument.baseURI };
},
get wrapLongLines() {
return Services.prefs.getBoolPref("view_source.wrap_long_lines");
},
getInnerMarkup(node, indent) {
- var str = '';
+ var str = "";
for (var i = 0; i < node.childNodes.length; i++) {
str += this.getOuterMarkup(node.childNodes.item(i), indent);
}
return str;
},
getOuterMarkup(node, indent) {
var Node = node.ownerDocument.defaultView.Node;
@@ -1315,17 +1315,17 @@ var ViewSelectionSource = {
this._lineCount != this._endTargetLine) {
newline = "\n";
}
this._lineCount++;
for (var k = 0; k < indent; k++) {
padding += " ";
}
str += newline + padding
- + '<<span class="start-tag">' + node.nodeName + '</span>';
+ + '<<span class="start-tag">' + node.nodeName + "</span>";
for (var i = 0; i < node.attributes.length; i++) {
var attr = node.attributes.item(i);
if (attr.nodeName.match(/^[-_]moz/)) {
continue;
}
str += ' <span class="attribute-name">'
+ attr.nodeName
+ '</span>=<span class="attribute-value">"'
@@ -1341,57 +1341,57 @@ var ViewSelectionSource = {
if (oldLine == this._lineCount) {
newline = "";
padding = "";
} else {
newline = (this._lineCount == this._endTargetLine) ? "" : "\n";
this._lineCount++;
}
str += newline + padding
- + '</<span class="end-tag">' + node.nodeName + '</span>>';
+ + '</<span class="end-tag">' + node.nodeName + "</span>>";
}
break;
case Node.TEXT_NODE: // Text
var tmp = node.nodeValue;
tmp = tmp.replace(/(\n|\r|\t)+/g, " ");
tmp = tmp.replace(/^ +/, "");
tmp = tmp.replace(/ +$/, "");
if (tmp.length != 0) {
- str += '<span class="text">' + this.unicodeToEntity(tmp) + '</span>';
+ str += '<span class="text">' + this.unicodeToEntity(tmp) + "</span>";
}
break;
default:
break;
}
if (node == this._targetNode) {
this._endTargetLine = this._lineCount;
- str += '</pre><pre>';
+ str += "</pre><pre>";
}
return str;
},
unicodeToEntity(text) {
const charTable = {
- '&': '&<span class="entity">amp;</span>',
- '<': '&<span class="entity">lt;</span>',
- '>': '&<span class="entity">gt;</span>',
+ "&": '&<span class="entity">amp;</span>',
+ "<": '&<span class="entity">lt;</span>',
+ ">": '&<span class="entity">gt;</span>',
'"': '&<span class="entity">quot;</span>'
};
function charTableLookup(letter) {
return charTable[letter];
}
function convertEntity(letter) {
try {
var unichar = this._entityConverter
.ConvertToEntity(letter, entityVersion);
var entity = unichar.substring(1); // extract '&'
- return '&<span class="entity">' + entity + '</span>';
+ return '&<span class="entity">' + entity + "</span>";
} catch (ex) {
return letter;
}
}
if (!this._entityConverter) {
try {
this._entityConverter = Cc["@mozilla.org/intl/entityconverter;1"]
--- a/toolkit/content/customizeToolbar.js
+++ b/toolkit/content/customizeToolbar.js
@@ -463,17 +463,17 @@ function addNewToolbar() {
// Check for an existing toolbar with the same display name
for (let i = 0; i < gToolbox.childNodes.length; ++i) {
var toolbar = gToolbox.childNodes[i];
var toolbarName = toolbar.getAttribute("toolbarname");
if (toolbarName == name.value &&
toolbar.getAttribute("type") != "menubar" &&
- toolbar.nodeName == 'toolbar') {
+ toolbar.nodeName == "toolbar") {
dupeFound = true;
break;
}
}
if (!dupeFound)
break;
--- a/toolkit/content/globalOverlay.js
+++ b/toolkit/content/globalOverlay.js
@@ -54,17 +54,17 @@ function canQuitApplication(aData) {
} catch (ex) { }
return true;
}
function goQuitApplication() {
if (!canQuitApplication())
return false;
- var appStartup = Components.classes['@mozilla.org/toolkit/app-startup;1'].
+ var appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"].
getService(Components.interfaces.nsIAppStartup);
appStartup.quit(Components.interfaces.nsIAppStartup.eAttemptQuit);
return true;
}
//
// Command Updater functions
--- a/toolkit/content/macWindowMenu.js
+++ b/toolkit/content/macWindowMenu.js
@@ -1,22 +1,22 @@
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function macWindowMenuDidShow() {
var windowManagerDS =
- Components.classes['@mozilla.org/rdf/datasource;1?name=window-mediator']
+ Components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"]
.getService(Components.interfaces.nsIWindowDataSource);
var sep = document.getElementById("sep-window-list");
// Using double parens to avoid warning
while ((sep = sep.nextSibling)) {
- var url = sep.getAttribute('id');
+ var url = sep.getAttribute("id");
var win = windowManagerDS.getWindowForResource(url);
if (win.document.documentElement.getAttribute("inwindowmenu") == "false")
sep.hidden = true;
else if (win == window)
sep.setAttribute("checked", "true");
}
}
@@ -24,21 +24,21 @@ function toOpenWindow( aWindow ) {
// deminiaturize the window, if it's in the Dock
if (aWindow.windowState == STATE_MINIMIZED)
aWindow.restore();
aWindow.document.commandDispatcher.focusedWindow.focus();
}
function ShowWindowFromResource( node ) {
var windowManagerDS =
- Components.classes['@mozilla.org/rdf/datasource;1?name=window-mediator']
+ Components.classes["@mozilla.org/rdf/datasource;1?name=window-mediator"]
.getService(Components.interfaces.nsIWindowDataSource);
var desiredWindow = null;
- var url = node.getAttribute('id');
+ var url = node.getAttribute("id");
desiredWindow = windowManagerDS.getWindowForResource( url );
if (desiredWindow)
toOpenWindow(desiredWindow);
}
function zoomWindow() {
if (window.windowState == STATE_NORMAL)
window.maximize();
--- a/toolkit/content/tests/browser/browser_audioCompeting.js
+++ b/toolkit/content/tests/browser/browser_audioCompeting.js
@@ -11,44 +11,44 @@ function* wait_for_tab_playing_event(tab
}
return false;
});
}
}
function play_audio_from_invisible_tab() {
return new Promise(resolve => {
- var autoPlay = content.document.getElementById('autoplay');
+ var autoPlay = content.document.getElementById("autoplay");
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused, true, "Audio in tab 1 was paused by audio competing.");
autoPlay.play();
autoPlay.onpause = function() {
autoPlay.onpause = null;
ok(true, "Audio in tab 1 can't playback when other tab is playing in foreground.");
resolve();
};
});
}
function audio_should_keep_playing_even_go_to_background() {
- var autoPlay = content.document.getElementById('autoplay');
+ var autoPlay = content.document.getElementById("autoplay");
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused, false, "Audio in tab 2 is still playing in the background.");
}
function play_non_autoplay_audio() {
return new Promise(resolve => {
- var autoPlay = content.document.getElementById('autoplay');
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var autoPlay = content.document.getElementById("autoplay");
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!autoPlay || !nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(nonAutoPlay.paused, true, "Non-autoplay audio isn't started playing yet.");
nonAutoPlay.play();
nonAutoPlay.onplay = function() {
--- a/toolkit/content/tests/browser/browser_autoscroll_disabled.js
+++ b/toolkit/content/tests/browser/browser_autoscroll_disabled.js
@@ -35,17 +35,17 @@ add_task(function* () {
yield new Promise(resolve => window.requestAnimationFrame(resolve));
let msg = yield ContentTask.spawn(gBrowser.selectedBrowser, { }, function* () {
// Skip the first animation frame callback as it's the same callback that
// the browser uses to kick off the scrolling.
return new Promise(resolve => {
function checkScroll() {
let msg = "";
- let elem = content.document.getElementById('i');
+ let elem = content.document.getElementById("i");
if (elem.scrollTop != 0) {
msg += "element should not have scrolled vertically";
}
if (elem.scrollLeft != 0) {
msg += "element should not have scrolled horizontally";
}
resolve(msg);
--- a/toolkit/content/tests/browser/browser_block_autoplay_media.js
+++ b/toolkit/content/tests/browser/browser_block_autoplay_media.js
@@ -17,17 +17,17 @@ function* wait_for_tab_playing_event(tab
return true;
}
return false;
});
}
}
function check_audio_suspended(suspendedType) {
- var autoPlay = content.document.getElementById('autoplay');
+ var autoPlay = content.document.getElementById("autoplay");
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.computedSuspended, suspendedType,
"The suspeded state of autoplay audio is correct.");
}
--- a/toolkit/content/tests/browser/browser_bug1170531.js
+++ b/toolkit/content/tests/browser/browser_bug1170531.js
@@ -44,35 +44,35 @@ add_task(function* () {
yield BrowserTestUtils.withNewTab({ gBrowser, url: "about:blank" }, function* (browser) {
let menu_cut_disabled, menu_copy_disabled;
yield BrowserTestUtils.loadURI(browser, "data:text/html,<div>hello!</div>");
browser.focus();
yield new Promise(resolve => waitForFocus(resolve, window));
yield new Promise(openMenu);
- menu_cut_disabled = menuPopup.querySelector("#menu_cut").getAttribute('disabled') == "true";
+ menu_cut_disabled = menuPopup.querySelector("#menu_cut").getAttribute("disabled") == "true";
is(menu_cut_disabled, false, "menu_cut should be enabled");
- menu_copy_disabled = menuPopup.querySelector("#menu_copy").getAttribute('disabled') == "true";
+ menu_copy_disabled = menuPopup.querySelector("#menu_copy").getAttribute("disabled") == "true";
is(menu_copy_disabled, false, "menu_copy should be enabled");
yield new Promise(closeMenu);
yield BrowserTestUtils.loadURI(browser, "data:text/html,<div contentEditable='true'>hello!</div>");
browser.focus();
yield new Promise(resolve => waitForFocus(resolve, window));
yield new Promise(openMenu);
- menu_cut_disabled = menuPopup.querySelector("#menu_cut").getAttribute('disabled') == "true";
+ menu_cut_disabled = menuPopup.querySelector("#menu_cut").getAttribute("disabled") == "true";
is(menu_cut_disabled, false, "menu_cut should be enabled");
- menu_copy_disabled = menuPopup.querySelector("#menu_copy").getAttribute('disabled') == "true";
+ menu_copy_disabled = menuPopup.querySelector("#menu_copy").getAttribute("disabled") == "true";
is(menu_copy_disabled, false, "menu_copy should be enabled");
yield new Promise(closeMenu);
yield BrowserTestUtils.loadURI(browser, "about:preferences");
browser.focus();
yield new Promise(resolve => waitForFocus(resolve, window));
yield new Promise(openMenu);
- menu_cut_disabled = menuPopup.querySelector("#menu_cut").getAttribute('disabled') == "true";
+ menu_cut_disabled = menuPopup.querySelector("#menu_cut").getAttribute("disabled") == "true";
is(menu_cut_disabled, true, "menu_cut should be disabled");
- menu_copy_disabled = menuPopup.querySelector("#menu_copy").getAttribute('disabled') == "true";
+ menu_copy_disabled = menuPopup.querySelector("#menu_copy").getAttribute("disabled") == "true";
is(menu_copy_disabled, true, "menu_copy should be disabled");
yield new Promise(closeMenu);
});
});
--- a/toolkit/content/tests/browser/browser_bug295977_autoscroll_overflow.js
+++ b/toolkit/content/tests/browser/browser_bug295977_autoscroll_overflow.js
@@ -22,75 +22,75 @@ add_task(function* () {
<option>a</option><option>a</option><option>a</option><option>a</option><option>a</option><option>a</option><option>a</option></select>\
<select id="f" style="width: 100px; height: 100px;"><option>a</option><option>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</option><option>a</option>\
<option>a</option><option>a</option><option>a</option><option>a</option><option>a</option><option>a</option><option>a</option>\
<option>a</option><option>a</option><option>a</option><option>a</option><option>a</option><option>a</option><option>a</option></select>\
<div id="g" style="width: 99px; height: 99px; border: 10px solid black; margin: 10px; overflow: auto;"><div style="width: 100px; height: 100px;"></div></div>\
<div id="h" style="width: 100px; height: 100px; overflow: -moz-hidden-unscrollable;"><div style="width: 200px; height: 200px;"></div></div>\
<iframe id="iframe" style="display: none;"></iframe>\
</body></html>'},
- {elem: 'a', expected: expectScrollNone},
- {elem: 'b', expected: expectScrollBoth},
- {elem: 'c', expected: expectScrollHori},
- {elem: 'd', expected: expectScrollVert},
- {elem: 'e', expected: expectScrollVert},
- {elem: 'f', expected: expectScrollNone},
- {elem: 'g', expected: expectScrollBoth},
- {elem: 'h', expected: expectScrollNone},
+ {elem: "a", expected: expectScrollNone},
+ {elem: "b", expected: expectScrollBoth},
+ {elem: "c", expected: expectScrollHori},
+ {elem: "d", expected: expectScrollVert},
+ {elem: "e", expected: expectScrollVert},
+ {elem: "f", expected: expectScrollNone},
+ {elem: "g", expected: expectScrollBoth},
+ {elem: "h", expected: expectScrollNone},
{dataUri: 'data:text/html,<html><head><meta charset="utf-8"></head><body id="i" style="overflow-y: scroll"><div style="height: 2000px"></div>\
<iframe id="iframe" style="display: none;"></iframe>\
</body></html>'},
- {elem: 'i', expected: expectScrollVert}, // bug 695121
+ {elem: "i", expected: expectScrollVert}, // bug 695121
{dataUri: 'data:text/html,<html><head><meta charset="utf-8"></head><style>html, body { width: 100%; height: 100%; overflow-x: hidden; overflow-y: scroll; }</style>\
<body id="j"><div style="height: 2000px"></div>\
<iframe id="iframe" style="display: none;"></iframe>\
</body></html>'},
- {elem: 'j', expected: expectScrollVert}, // bug 914251
+ {elem: "j", expected: expectScrollVert}, // bug 914251
{dataUri: 'data:text/html,<html><head><meta charset="utf-8">\
<style>\
body > div {scroll-behavior: smooth;width: 300px;height: 300px;overflow: scroll;}\
body > div > div {width: 1000px;height: 1000px;}\
</style>\
</head><body><div id="t"><div></div></div></body></html>'},
- {elem: 't', expected: expectScrollBoth}, // bug 1308775
+ {elem: "t", expected: expectScrollBoth}, // bug 1308775
{dataUri: 'data:text/html,<html><head><meta charset="utf-8"></head><body>\
<div id="k" style="height: 150px; width: 200px; overflow: scroll; border: 1px solid black;">\
<iframe style="height: 200px; width: 300px;"></iframe>\
</div>\
<div id="l" style="height: 150px; width: 300px; overflow: scroll; border: 1px dashed black;">\
<iframe style="height: 200px; width: 200px;" src="data:text/html,<div style=\'border: 5px solid blue; height: 200%; width: 200%;\'></div>"></iframe>\
</div>\
<iframe id="m"></iframe>\
<div style="height: 200%; border: 5px dashed black;">filler to make document overflow: scroll;</div>\
</body></html>'},
- {elem: 'k', expected: expectScrollBoth},
- {elem: 'k', expected: expectScrollNone, testwindow: true},
- {elem: 'l', expected: expectScrollNone},
- {elem: 'm', expected: expectScrollVert, testwindow: true},
+ {elem: "k", expected: expectScrollBoth},
+ {elem: "k", expected: expectScrollNone, testwindow: true},
+ {elem: "l", expected: expectScrollNone},
+ {elem: "m", expected: expectScrollVert, testwindow: true},
{dataUri: 'data:text/html,<html><head><meta charset="utf-8"></head><body>\
<img width="100" height="100" alt="image map" usemap="%23planetmap">\
<map name="planetmap">\
<area id="n" shape="rect" coords="0,0,100,100" href="javascript:void(null)">\
</map>\
<a href="javascript:void(null)" id="o" style="width: 100px; height: 100px; border: 1px solid black; display: inline-block; vertical-align: top;">link</a>\
<input id="p" style="width: 100px; height: 100px; vertical-align: top;">\
<textarea id="q" style="width: 100px; height: 100px; vertical-align: top;"></textarea>\
<div style="height: 200%; border: 1px solid black;"></div>\
</body></html>'},
- {elem: 'n', expected: expectScrollNone, testwindow: true},
- {elem: 'o', expected: expectScrollNone, testwindow: true},
- {elem: 'p', expected: expectScrollVert, testwindow: true, middlemousepastepref: false},
- {elem: 'q', expected: expectScrollVert, testwindow: true, middlemousepastepref: false},
+ {elem: "n", expected: expectScrollNone, testwindow: true},
+ {elem: "o", expected: expectScrollNone, testwindow: true},
+ {elem: "p", expected: expectScrollVert, testwindow: true, middlemousepastepref: false},
+ {elem: "q", expected: expectScrollVert, testwindow: true, middlemousepastepref: false},
{dataUri: 'data:text/html,<html><head><meta charset="utf-8"></head><body>\
<input id="r" style="width: 100px; height: 100px; vertical-align: top;">\
<textarea id="s" style="width: 100px; height: 100px; vertical-align: top;"></textarea>\
<div style="height: 200%; border: 1px solid black;"></div>\
</body></html>'},
- {elem: 'r', expected: expectScrollNone, testwindow: true, middlemousepastepref: true},
- {elem: 's', expected: expectScrollNone, testwindow: true, middlemousepastepref: true}
+ {elem: "r", expected: expectScrollNone, testwindow: true, middlemousepastepref: true},
+ {elem: "s", expected: expectScrollNone, testwindow: true, middlemousepastepref: true}
];
for (let test of allTests) {
if (test.dataUri) {
let loadedPromise = BrowserTestUtils.browserLoaded(gBrowser.selectedBrowser);
gBrowser.loadURI(test.dataUri);
yield loadedPromise;
continue;
@@ -168,35 +168,35 @@ body > div > div {width: 1000px;height:
checkWindow: test.testwindow },
function* (args) {
let msg = "";
if (args.checkWindow) {
if (!((args.scrollVert && content.scrollY > 0) ||
(!args.scrollVert && content.scrollY == 0))) {
msg += "Failed: ";
}
- msg += 'Window for ' + args.elemid + ' should' + (args.scrollVert ? '' : ' not') + ' have scrolled vertically\n';
+ msg += "Window for " + args.elemid + " should" + (args.scrollVert ? "" : " not") + " have scrolled vertically\n";
if (!((args.scrollHori && content.scrollX > 0) ||
(!args.scrollHori && content.scrollX == 0))) {
msg += "Failed: ";
}
- msg += ' Window for ' + args.elemid + ' should' + (args.scrollHori ? '' : ' not') + ' have scrolled horizontally\n';
+ msg += " Window for " + args.elemid + " should" + (args.scrollHori ? "" : " not") + " have scrolled horizontally\n";
} else {
let elem = content.document.getElementById(args.elemid);
if (!((args.scrollVert && elem.scrollTop > 0) ||
(!args.scrollVert && elem.scrollTop == 0))) {
msg += "Failed: ";
}
- msg += ' ' + args.elemid + ' should' + (args.scrollVert ? '' : ' not') + ' have scrolled vertically\n';
+ msg += " " + args.elemid + " should" + (args.scrollVert ? "" : " not") + " have scrolled vertically\n";
if (!((args.scrollHori && elem.scrollLeft > 0) ||
(!args.scrollHori && elem.scrollLeft == 0))) {
msg += "Failed: ";
}
- msg += args.elemid + ' should' + (args.scrollHori ? '' : ' not') + ' have scrolled horizontally';
+ msg += args.elemid + " should" + (args.scrollHori ? "" : " not") + " have scrolled horizontally";
}
Assert.ok(msg.indexOf("Failed") == -1, msg);
}
);
// Before continuing the test, we need to ensure that the IPC
// message that stops autoscrolling has had time to arrive.
--- a/toolkit/content/tests/browser/browser_content_url_annotation.js
+++ b/toolkit/content/tests/browser/browser_content_url_annotation.js
@@ -27,17 +27,17 @@ function removeFile(directory, filename)
}
/**
* Returns the directory where crash dumps are stored.
*
* @return nsIFile
*/
function getMinidumpDirectory() {
- let dir = Services.dirsvc.get('ProfD', Ci.nsIFile);
+ let dir = Services.dirsvc.get("ProfD", Ci.nsIFile);
dir.append("minidumps");
return dir;
}
/**
* Checks that the URL is correctly annotated on a content process crash.
*/
add_task(function* test_content_url_annotation() {
@@ -46,20 +46,20 @@ add_task(function* test_content_url_anno
yield BrowserTestUtils.withNewTab({
gBrowser
}, function* (browser) {
ok(browser.isRemoteBrowser, "Should be a remote browser");
// file_redirect.html should send us to file_redirect_to.html
let promise = ContentTask.spawn(browser, {}, function* () {
- dump('ContentTask starting...\n');
+ dump("ContentTask starting...\n");
yield new Promise((resolve) => {
addEventListener("RedirectDone", function listener() {
- dump('Got RedirectDone\n');
+ dump("Got RedirectDone\n");
removeEventListener("RedirectDone", listener);
resolve();
}, true, true);
});
});
browser.loadURI(url);
yield promise;
--- a/toolkit/content/tests/browser/browser_mediaPlayback_mute.js
+++ b/toolkit/content/tests/browser/browser_mediaPlayback_mute.js
@@ -6,26 +6,26 @@ function wait_for_event(browser, event)
is(event.originalTarget, browser, "Event must be dispatched to correct browser.");
return true;
});
}
function* test_audio_in_browser() {
function get_audio_element() {
var doc = content.document;
- var list = doc.getElementsByTagName('audio');
+ var list = doc.getElementsByTagName("audio");
if (list.length == 1) {
return list[0];
}
// iframe?
- list = doc.getElementsByTagName('iframe');
+ list = doc.getElementsByTagName("iframe");
var iframe = list[0];
- list = iframe.contentDocument.getElementsByTagName('audio');
+ list = iframe.contentDocument.getElementsByTagName("audio");
return list[0];
}
var audio = get_audio_element();
return {
computedVolume: audio.computedVolume,
computedMuted: audio.computedMuted
}
--- a/toolkit/content/tests/browser/browser_mediaPlayback_suspended.js
+++ b/toolkit/content/tests/browser/browser_mediaPlayback_suspended.js
@@ -10,17 +10,17 @@ var SuspendedType = {
function wait_for_event(browser, event) {
return BrowserTestUtils.waitForEvent(browser, event, false, (event) => {
is(event.originalTarget, browser, "Event must be dispatched to correct browser.");
return true;
});
}
function check_audio_onplay() {
- var list = content.document.getElementsByTagName('audio');
+ var list = content.document.getElementsByTagName("audio");
if (list.length != 1) {
ok(false, "There should be only one audio element in page!")
}
var audio = list[0];
return new Promise((resolve, reject) => {
audio.onplay = () => {
ok(needToReceiveOnPlay, "Should not receive play event!");
@@ -35,28 +35,28 @@ function check_audio_onplay() {
ok(true, "Doesn't receive play event when media was blocked.");
audio.onplay = null;
resolve();
}, 1000)
});
}
function check_audio_suspended(suspendedType) {
- var list = content.document.getElementsByTagName('audio');
+ var list = content.document.getElementsByTagName("audio");
if (list.length != 1) {
ok(false, "There should be only one audio element in page!")
}
var audio = list[0];
is(audio.computedSuspended, suspendedType,
"The suspended state of MediaElement is correct.");
}
function check_audio_pause_state(expectedPauseState) {
- var list = content.document.getElementsByTagName('audio');
+ var list = content.document.getElementsByTagName("audio");
if (list.length != 1) {
ok(false, "There should be only one audio element in page!")
}
var audio = list[0];
if (expectedPauseState) {
is(audio.paused, true, "Audio is paused correctly.");
} else {
--- a/toolkit/content/tests/browser/browser_mediaPlayback_suspended_multipleAudio.js
+++ b/toolkit/content/tests/browser/browser_mediaPlayback_suspended_multipleAudio.js
@@ -10,50 +10,50 @@ var SuspendedType = {
function wait_for_event(browser, event) {
return BrowserTestUtils.waitForEvent(browser, event, false, (event) => {
is(event.originalTarget, browser, "Event must be dispatched to correct browser.");
return true;
});
}
function check_all_audio_suspended(suspendedType) {
- var autoPlay = content.document.getElementById('autoplay');
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var autoPlay = content.document.getElementById("autoplay");
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!autoPlay || !nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.computedSuspended, suspendedType,
"The suspeded state of autoplay audio is correct.");
is(nonAutoPlay.computedSuspended, suspendedType,
"The suspeded state of non-autoplay audio is correct.");
}
function check_autoplay_audio_suspended(suspendedType) {
- var autoPlay = content.document.getElementById('autoplay');
+ var autoPlay = content.document.getElementById("autoplay");
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.computedSuspended, suspendedType,
"The suspeded state of autoplay audio is correct.");
}
function check_nonautoplay_audio_suspended(suspendedType) {
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(nonAutoPlay.computedSuspended, suspendedType,
"The suspeded state of non-autoplay audio is correct.");
}
function check_autoplay_audio_pause_state(expectedPauseState) {
- var autoPlay = content.document.getElementById('autoplay');
+ var autoPlay = content.document.getElementById("autoplay");
if (!autoPlay) {
ok(false, "Can't get the audio element!");
}
if (autoPlay.paused == expectedPauseState) {
if (expectedPauseState) {
ok(true, "Audio is paused correctly.");
} else {
@@ -68,81 +68,81 @@ function check_autoplay_audio_pause_stat
autoPlay.onplay = function() {
autoPlay.onplay = null;
ok(true, "Audio is resumed correctly, checking from onplay.");
}
}
}
function play_nonautoplay_audio_should_be_paused() {
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
nonAutoPlay.play();
return new Promise(resolve => {
nonAutoPlay.onpause = function() {
nonAutoPlay.onpause = null;
is(nonAutoPlay.ended, false, "Audio can't be playback.");
resolve();
}
});
}
function all_audio_onresume() {
- var autoPlay = content.document.getElementById('autoplay');
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var autoPlay = content.document.getElementById("autoplay");
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!autoPlay || !nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused, false, "Autoplay audio is resumed.");
is(nonAutoPlay.paused, false, "Non-AutoPlay audio is resumed.");
}
function all_audio_onpause() {
- var autoPlay = content.document.getElementById('autoplay');
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var autoPlay = content.document.getElementById("autoplay");
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!autoPlay || !nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused, true, "Autoplay audio is paused.");
is(nonAutoPlay.paused, true, "Non-AutoPlay audio is paused.");
}
function play_nonautoplay_audio_should_play_until_ended() {
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
nonAutoPlay.play();
return new Promise(resolve => {
nonAutoPlay.onended = function() {
nonAutoPlay.onended = null;
ok(true, "Audio can be playback until ended.");
resolve();
}
});
}
function no_audio_resumed() {
- var autoPlay = content.document.getElementById('autoplay');
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var autoPlay = content.document.getElementById("autoplay");
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!autoPlay || !nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
is(autoPlay.paused && nonAutoPlay.paused, true, "No audio was resumed.");
}
function play_nonautoplay_audio_should_be_blocked(suspendedType) {
- var nonAutoPlay = content.document.getElementById('nonautoplay');
+ var nonAutoPlay = content.document.getElementById("nonautoplay");
if (!nonAutoPlay) {
ok(false, "Can't get the audio element!");
}
nonAutoPlay.play();
ok(nonAutoPlay.paused, "The blocked audio can't be playback.");
}
--- a/toolkit/content/tests/chrome/RegisterUnregisterChrome.js
+++ b/toolkit/content/tests/chrome/RegisterUnregisterChrome.js
@@ -41,17 +41,17 @@ function* dirIter(directory) {
function getParent(path) {
let lastSlash = path.lastIndexOf("/");
if (lastSlash == -1) {
lastSlash = path.lastIndexOf("\\");
if (lastSlash == -1) {
return "";
}
- return '/' + path.substring(0, lastSlash).replace(/\\/g, '/');
+ return "/" + path.substring(0, lastSlash).replace(/\\/g, "/");
}
return path.substring(0, lastSlash);
}
function copyDirToTempProfile(path, subdirname) {
if (subdirname === undefined) {
subdirname = "mochikit-tmp";
@@ -62,17 +62,17 @@ function copyDirToTempProfile(path, subd
tmpdir.createUnique(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0o777);
let rootDir = getParent(path);
if (rootDir == "") {
return tmpdir;
}
// The SimpleTest directory is hidden
- var files = Array.from(dirIter('file://' + rootDir));
+ var files = Array.from(dirIter("file://" + rootDir));
for (f in files) {
files[f].copyTo(tmpdir, "");
}
return tmpdir;
}
function convertChromeURI(chromeURI) {
@@ -80,18 +80,18 @@ function convertChromeURI(chromeURI) {
getService(Ci.nsIIOService).newURI(chromeURI);
return gChromeReg.convertChromeURL(uri);
}
function chromeURIToFile(chromeURI) {
var jar = getJar(chromeURI);
if (jar) {
var tmpDir = extractJarToTmp(jar);
- let parts = chromeURI.split('/');
- if (parts[parts.length - 1] != '') {
+ let parts = chromeURI.split("/");
+ if (parts[parts.length - 1] != "") {
tmpDir.append(parts[parts.length - 1]);
}
return tmpDir;
}
return convertChromeURI(chromeURI).
QueryInterface(Ci.nsIFileURL).file;
}
--- a/toolkit/content/tests/fennec-tile-testapp/chrome/content/BrowserView.js
+++ b/toolkit/content/tests/fennec-tile-testapp/chrome/content/BrowserView.js
@@ -2,17 +2,17 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var Ci = Components.interfaces;
// --- REMOVE ---
var noop = function() {};
-var endl = '\n';
+var endl = "\n";
// --------------
function BrowserView(container, visibleRect) {
bindAll(this);
this.init(container, visibleRect);
}
/**
@@ -131,23 +131,23 @@ function() {
}
function initBrowserState(browser, visibleRect) {
let [browserW, browserH] = getBrowserDimensions(browser);
let zoomLevel = pageZoomLevel(visibleRect, browserW, browserH);
let viewportRect = (new wsRect(0, 0, browserW, browserH)).scale(zoomLevel, zoomLevel);
- dump('--- initing browser to ---' + endl);
+ dump("--- initing browser to ---" + endl);
browser.__BrowserView__vps = new BrowserView.BrowserViewportState(viewportRect,
visibleRect.x,
visibleRect.y,
zoomLevel);
dump(browser.__BrowserView__vps.toString() + endl);
- dump('--------------------------' + endl);
+ dump("--------------------------" + endl);
}
function getViewportStateFromBrowser(browser) {
return browser.__BrowserView__vps;
}
function getBrowserDimensions(browser) {
return [browser.scrollWidth, browser.scrollHeight];
@@ -177,18 +177,18 @@ function() {
// function clampViewportWH(width, height, visibleRect) {
// let minW = visibleRect.width;
// let minH = visibleRect.height;
// return [Math.max(width, minW), Math.max(height, minH)];
// }
function resizeContainerToViewport(container, viewportRect) {
- container.style.width = viewportRect.width + 'px';
- container.style.height = viewportRect.height + 'px';
+ container.style.width = viewportRect.width + "px";
+ container.style.height = viewportRect.height + "px";
}
// !!! --- RESIZE HACK BEGIN -----
function simulateMozAfterSizeChange(browser, width, height) {
let ev = document.createElement("MouseEvents");
ev.initEvent("FakeMozAfterSizeChange", false, false, window, 0, width, height);
browser.dispatchEvent(ev);
}
@@ -668,17 +668,17 @@ BrowserView.BrowserViewportState.prototy
clone: function clone() {
return new BrowserView.BrowserViewportState(this.viewportRect,
this.visibleX,
this.visibleY,
this.zoomLevel);
},
toString: function toString() {
- let props = ['\tviewportRect=' + this.viewportRect.toString(),
- '\tvisibleX=' + this.visibleX,
- '\tvisibleY=' + this.visibleY,
- '\tzoomLevel=' + this.zoomLevel];
+ let props = ["\tviewportRect=" + this.viewportRect.toString(),
+ "\tvisibleX=" + this.visibleX,
+ "\tvisibleY=" + this.visibleY,
+ "\tzoomLevel=" + this.zoomLevel];
- return '[BrowserViewportState] {\n' + props.join(',\n') + '\n}';
+ return "[BrowserViewportState] {\n" + props.join(",\n") + "\n}";
}
};
--- a/toolkit/content/tests/fennec-tile-testapp/chrome/content/FooScript.js
+++ b/toolkit/content/tests/fennec-tile-testapp/chrome/content/FooScript.js
@@ -154,26 +154,26 @@ BrowserView.prototype = {
canvas.style.position = "absolute";
canvas.style.left = tile.x + "px";
canvas.style.top = tile.y + "px";
let tileContainer = document.getElementById("tile_container");
tileContainer.appendChild(canvas);
- dump('++ ' + tile.toString() + endl);
+ dump("++ " + tile.toString() + endl);
},
removeTile: function removeTile(tile) {
let canvas = tile.contentImage;
let tileContainer = document.getElementById("tile_container");
tileContainer.removeChild(canvas);
- dump('-- ' + tile.toString() + endl);
+ dump("-- " + tile.toString() + endl);
},
scrollBy: function scrollBy(dx, dy) {
// TODO
this.onBeforeScroll();
this.onAfterScroll();
},
--- a/toolkit/content/tests/fennec-tile-testapp/chrome/content/TileManager.js
+++ b/toolkit/content/tests/fennec-tile-testapp/chrome/content/TileManager.js
@@ -359,17 +359,17 @@ TileManager.prototype = {
this._tileCache.holdTile(tile);
}
this._tileCache.forEachIntersectingRect(rect, true, renderAppendHoldTile, this);
},
_idleTileCrawler: function _idleTileCrawler(self) {
if (!self) self = this;
- dump('crawl pass.\n');
+ dump("crawl pass.\n");
let itered = 0, rendered = 0;
let start = Date.now();
let comeAgain = true;
while ((Date.now() - start) <= kLazyRoundTimeCap) {
let tile = self._crawler.next();
@@ -380,23 +380,23 @@ TileManager.prototype = {
if (tile.isDirty()) {
self._renderTile(tile);
++rendered;
}
++itered;
}
- dump('crawl itered:' + itered + ' rendered:' + rendered + '\n');
+ dump("crawl itered:" + itered + " rendered:" + rendered + "\n");
if (comeAgain) {
self._idleTileCrawlerTimeout = setTimeout(self._idleTileCrawler, 2000, self);
} else {
self.stopLazyCrawl();
- dump('crawl end\n');
+ dump("crawl end\n");
}
}
};
/**
* The tile cache used by the tile manager to hold and index all
@@ -834,24 +834,24 @@ TileManager.Tile.prototype = {
ctx.restore();
this.unmarkDirty();
},
toString: function toString(more) {
if (more) {
- return 'Tile(' + [this.i,
+ return "Tile(" + [this.i,
this.j,
"dirty=" + this.isDirty(),
- "boundRect=" + this.boundRect].join(', ')
- + ')';
+ "boundRect=" + this.boundRect].join(", ")
+ + ")";
}
- return 'Tile(' + this.i + ', ' + this.j + ')';
+ return "Tile(" + this.i + ", " + this.j + ")";
},
_hold: function hold() { this.free = false; },
_release: function release() { this.free = true; }
};
@@ -1003,12 +1003,12 @@ TileManager.CrawlIterator.prototype = {
}
},
_strIndices: function _strIndices(i, j) {
return i + "," + j;
},
_unstrIndices: function _unstrIndices(str) {
- return str.split(',');
+ return str.split(",");
}
};
--- a/toolkit/content/tests/widgets/popup_shared.js
+++ b/toolkit/content/tests/widgets/popup_shared.js
@@ -123,20 +123,20 @@ function eventOccurred(event) {
is(event.target.id, eventitem[1],
test.testname + " event target ID " + event.target.id);
matches = eventitem[0] == event.type && eventitem[1] == event.target.id;
}
var modifiersMask = eventitem[2];
if (modifiersMask) {
var m = "";
- m += event.altKey ? '1' : '0';
- m += event.ctrlKey ? '1' : '0';
- m += event.shiftKey ? '1' : '0';
- m += event.metaKey ? '1' : '0';
+ m += event.altKey ? "1" : "0";
+ m += event.ctrlKey ? "1" : "0";
+ m += event.shiftKey ? "1" : "0";
+ m += event.metaKey ? "1" : "0";
is(m, modifiersMask, test.testname + " modifiers mask matches");
}
var expectedState;
switch (event.type) {
case "popupshowing": expectedState = "showing"; break;
case "popupshown": expectedState = "open"; break;
case "popuphiding": expectedState = "hiding"; break;
--- a/toolkit/crashreporter/CrashSubmit.jsm
+++ b/toolkit/crashreporter/CrashSubmit.jsm
@@ -2,17 +2,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/KeyValueParser.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.importGlobalProperties(['File']);
+Cu.importGlobalProperties(["File"]);
XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils",
"resource://gre/modules/PromiseUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
@@ -60,28 +60,28 @@ function getL10nStrings() {
path.append("crashreporter.ini");
if (!path.exists()) {
// very bad, but I don't know how to recover
return null;
}
}
let crstrings = parseINIStrings(path);
let strings = {
- 'crashid': crstrings.CrashID,
- 'reporturl': crstrings.CrashDetailsURL
+ "crashid": crstrings.CrashID,
+ "reporturl": crstrings.CrashDetailsURL
};
path = dirSvc.get("XCurProcD", Ci.nsIFile);
path.append("crashreporter-override.ini");
if (path.exists()) {
crstrings = parseINIStrings(path);
- if ('CrashID' in crstrings)
- strings['crashid'] = crstrings.CrashID;
- if ('CrashDetailsURL' in crstrings)
- strings['reporturl'] = crstrings.CrashDetailsURL;
+ if ("CrashID" in crstrings)
+ strings["crashid"] = crstrings.CrashID;
+ if ("CrashDetailsURL" in crstrings)
+ strings["reporturl"] = crstrings.CrashDetailsURL;
}
return strings;
}
XPCOMUtils.defineLazyGetter(this, "strings", getL10nStrings);
function getDir(name) {
let directoryService = Cc["@mozilla.org/file/directory_service;1"].
@@ -90,17 +90,17 @@ function getDir(name) {
dir.append("Crash Reports");
dir.append(name);
return dir;
}
function writeFile(dirName, fileName, data) {
let path = getDir(dirName);
if (!path.exists())
- path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt('0700', 8));
+ path.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0700", 8));
path.append(fileName);
var fs = Cc["@mozilla.org/network/file-output-stream;1"].
createInstance(Ci.nsIFileOutputStream);
// open, write, truncate
fs.init(path, -1, -1, 0);
var os = Cc["@mozilla.org/intl/converter-output-stream;1"].
createInstance(Ci.nsIConverterOutputStream);
os.init(fs, "UTF-8", 0, 0x0000);
@@ -169,21 +169,21 @@ function pruneSavedDumps() {
});
if (entriesArray.length > KEEP) {
for (let i = 0; i < entriesArray.length - KEEP; ++i) {
let extra = entriesArray[i];
let matches = extra.leafName.match(/(.+)\.extra$/);
if (matches) {
let dump = extra.clone();
- dump.leafName = matches[1] + '.dmp';
+ dump.leafName = matches[1] + ".dmp";
dump.remove(false);
let memory = extra.clone();
- memory.leafName = matches[1] + '.memory.json.gz';
+ memory.leafName = matches[1] + ".memory.json.gz";
if (memory.exists()) {
memory.remove(false);
}
extra.remove(false);
}
}
}
@@ -249,26 +249,26 @@ Submitter.prototype = {
this.additionalDumps = null;
// remove this object from the list of active submissions
let idx = CrashSubmit._activeSubmissions.indexOf(this);
if (idx != -1)
CrashSubmit._activeSubmissions.splice(idx, 1);
},
submitForm: function Submitter_submitForm() {
- if (!('ServerURL' in this.extraKeyVals)) {
+ if (!("ServerURL" in this.extraKeyVals)) {
return false;
}
let serverURL = this.extraKeyVals.ServerURL;
// Override the submission URL from the environment
- var envOverride = Cc['@mozilla.org/process/environment;1'].
+ var envOverride = Cc["@mozilla.org/process/environment;1"].
getService(Ci.nsIEnvironment).get("MOZ_CRASHREPORTER_URL");
- if (envOverride != '') {
+ if (envOverride != "") {
serverURL = envOverride;
}
let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
xhr.open("POST", serverURL, true);
let formData = Cc["@mozilla.org/files/formdata;1"]
@@ -389,25 +389,25 @@ Submitter.prototype = {
for (let key in extraKeyVals) {
if (!(key in this.extraKeyVals)) {
this.extraKeyVals[key] = extraKeyVals[key];
}
}
let additionalDumps = [];
if ("additional_minidumps" in this.extraKeyVals) {
- let names = this.extraKeyVals.additional_minidumps.split(',');
+ let names = this.extraKeyVals.additional_minidumps.split(",");
for (let name of names) {
let [dump /* , extra, memory */] = getPendingMinidump(this.id + "-" + name);
if (!dump.exists()) {
this.notifyStatus(FAILED);
this.cleanup();
return this.deferredSubmit.promise;
}
- additionalDumps.push({'name': name, 'dump': dump});
+ additionalDumps.push({"name": name, "dump": dump});
}
}
this.notifyStatus(SUBMITTING);
this.additionalDumps = additionalDumps;
if (!this.submitForm()) {
@@ -446,21 +446,21 @@ this.CrashSubmit = {
* submission succeeds and rejected otherwise.
*/
submit: function CrashSubmit_submit(id, params) {
params = params || {};
let recordSubmission = false;
let noThrottle = false;
let extraExtraKeyVals = null;
- if ('recordSubmission' in params)
+ if ("recordSubmission" in params)
recordSubmission = params.recordSubmission;
- if ('noThrottle' in params)
+ if ("noThrottle" in params)
noThrottle = params.noThrottle;
- if ('extraExtraKeyVals' in params)
+ if ("extraExtraKeyVals" in params)
extraExtraKeyVals = params.extraExtraKeyVals;
let submitter = new Submitter(id, recordSubmission,
noThrottle, extraExtraKeyVals);
CrashSubmit._activeSubmissions.push(submitter);
return submitter.submit();
},
--- a/toolkit/crashreporter/KeyValueParser.jsm
+++ b/toolkit/crashreporter/KeyValueParser.jsm
@@ -11,44 +11,44 @@ this.EXPORTED_SYMBOLS = [
];
const Cc = Components.classes;
const Ci = Components.interfaces;
this.parseKeyValuePairsFromLines = function(lines) {
let data = {};
for (let line of lines) {
- if (line == '')
+ if (line == "")
continue;
// can't just .split() because the value might contain = characters
- let eq = line.indexOf('=');
+ let eq = line.indexOf("=");
if (eq != -1) {
let [key, value] = [line.substring(0, eq),
line.substring(eq + 1)];
if (key && value)
data[key] = value.replace(/\\n/g, "\n").replace(/\\\\/g, "\\");
}
}
return data;
}
this.parseKeyValuePairs = function parseKeyValuePairs(text) {
- let lines = text.split('\n');
+ let lines = text.split("\n");
return parseKeyValuePairsFromLines(lines);
};
this.parseKeyValuePairsFromFile = function parseKeyValuePairsFromFile(file) {
let fstream = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream);
fstream.init(file, -1, 0, 0);
let is = Cc["@mozilla.org/intl/converter-input-stream;1"].
createInstance(Ci.nsIConverterInputStream);
is.init(fstream, "UTF-8", 1024, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
let str = {};
- let contents = '';
+ let contents = "";
while (is.readString(4096, str) != 0) {
contents += str.value;
}
is.close();
fstream.close();
return parseKeyValuePairs(contents);
}
--- a/toolkit/crashreporter/content/crashes.js
+++ b/toolkit/crashreporter/content/crashes.js
@@ -78,21 +78,21 @@ function populateReportList() {
}
var dateFormatter;
var timeFormatter;
try {
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- dateFormatter = new Intl.DateTimeFormat(locale, { year: '2-digit',
- month: 'numeric',
- day: 'numeric' });
- timeFormatter = new Intl.DateTimeFormat(locale, { hour: 'numeric',
- minute: 'numeric' });
+ dateFormatter = new Intl.DateTimeFormat(locale, { year: "2-digit",
+ month: "numeric",
+ day: "numeric" });
+ timeFormatter = new Intl.DateTimeFormat(locale, { hour: "numeric",
+ minute: "numeric" });
} catch (e) {
// XXX Fallback to be removed once bug 1215247 is complete
// and the Intl API is available on all platforms.
dateFormatter = {
format(date) {
return date.toLocaleDateString();
}
}
--- a/toolkit/crashreporter/test/browser/browser_aboutCrashesResubmit.js
+++ b/toolkit/crashreporter/test/browser/browser_aboutCrashesResubmit.js
@@ -43,17 +43,17 @@ function check_crash_list(crashes) {
*/
function check_submit_pending(tab, crashes) {
let browser = gBrowser.getBrowserForTab(tab);
let SubmittedCrash = null;
let CrashID = null;
let CrashURL = null;
function csp_onload() {
// loaded the crash report page
- ok(true, 'got submission onload');
+ ok(true, "got submission onload");
ContentTask.spawn(browser, null, function() {
// grab the Crash ID here to verify later
let CrashID = content.location.search.split("=")[1];
let CrashURL = content.location.toString();
// check the JSON content vs. what we submitted
let result = JSON.parse(content.document.documentElement.textContent);
@@ -128,21 +128,21 @@ function test() {
waitForExplicitFinish();
let appD = make_fake_appdir();
let crD = appD.clone();
crD.append("Crash Reports");
let crashes = add_fake_crashes(crD, 1);
// we don't need much data here, it's not going to a real Socorro
crashes.push(addPendingCrashreport(crD,
crashes[crashes.length - 1].date + 60000,
- {'ServerURL': 'http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs',
- 'ProductName': 'Test App',
+ {"ServerURL": "http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs",
+ "ProductName": "Test App",
// test that we don't truncate
// at = (bug 512853)
- 'Foo': 'ABC=XYZ'
+ "Foo": "ABC=XYZ"
}));
crashes.sort((a, b) => b.date - a.date);
// set this pref so we can link to our test server
Services.prefs.setCharPref("breakpad.reportURL",
"http://example.com/browser/toolkit/crashreporter/test/browser/crashreport.sjs?id=");
BrowserTestUtils.openNewForegroundTab(gBrowser, "about:crashes").then((tab) => {
--- a/toolkit/crashreporter/test/browser/head.js
+++ b/toolkit/crashreporter/test/browser/head.js
@@ -83,17 +83,17 @@ function add_fake_crashes(crD, count) {
let uuid = uuidGenerator.generateUUID().toString();
// ditch the {}
uuid = "bp-" + uuid.substring(1, uuid.length - 2);
let fn = uuid + ".txt";
let file = submitdir.clone();
file.append(fn);
file.create(Ci.nsIFile.NORMAL_FILE_TYPE, 0o666);
file.lastModifiedTime = date;
- results.push({'id': uuid, 'date': date, 'pending': false});
+ results.push({"id": uuid, "date": date, "pending": false});
date += 60000;
}
// we want them sorted newest to oldest, since that's the order
// that about:crashes lists them in
results.sort((a, b) => b.date - a.date);
return results;
}
@@ -130,10 +130,10 @@ function addPendingCrashreport(crD, date
}
writeDataToFile(extrafile, extradata);
let memoryfile = pendingdir.clone();
memoryfile.append(uuid + ".memory.json.gz");
writeDataToFile(memoryfile, "Let's pretend this is a memory report");
dumpfile.lastModifiedTime = date;
extrafile.lastModifiedTime = date;
memoryfile.lastModifiedTime = date;
- return {'id': uuid, 'date': date, 'pending': true, 'extra': extra};
+ return {"id": uuid, "date": date, "pending": true, "extra": extra};
}
--- a/toolkit/crashreporter/test/unit/head_crashreporter.js
+++ b/toolkit/crashreporter/test/unit/head_crashreporter.js
@@ -46,25 +46,25 @@ function do_crash(setup, callback, canRe
// get Gre dir (GreD)
let greD = ds.get("GreD", Components.interfaces.nsILocalFile);
let headfile = do_get_file("crasher_subprocess_head.js");
let tailfile = do_get_file("crasher_subprocess_tail.js");
// run xpcshell -g GreD -f head -e "some setup code" -f tail
let process = Components.classes["@mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(bin);
- let args = ['-g', greD.path,
- '-f', headfile.path];
+ let args = ["-g", greD.path,
+ "-f", headfile.path];
if (setup) {
if (typeof(setup) == "function")
// funky, but convenient
setup = "(" + setup.toSource() + ")();";
- args.push('-e', setup);
+ args.push("-e", setup);
}
- args.push('-f', tailfile.path);
+ args.push("-f", tailfile.path);
let env = Components.classes["@mozilla.org/process/environment;1"]
.getService(Components.interfaces.nsIEnvironment);
let crashD = do_get_tempdir();
crashD.append("crash-events");
if (!crashD.exists()) {
crashD.create(crashD.DIRECTORY_TYPE, 0o700);
--- a/toolkit/crashreporter/test/unit/test_crashreporter_crash.js
+++ b/toolkit/crashreporter/test/unit/test_crashreporter_crash.js
@@ -11,23 +11,23 @@ function run_test() {
parseInt(match[1]) == 6 && parseInt(match[2]) >= 1)) {
is_win7_or_newer = true;
}
// try a basic crash
do_crash(null, function(mdump, extra) {
do_check_true(mdump.exists());
do_check_true(mdump.fileSize > 0);
- do_check_true('StartupTime' in extra);
- do_check_true('CrashTime' in extra);
+ do_check_true("StartupTime" in extra);
+ do_check_true("CrashTime" in extra);
do_check_true(CrashTestUtils.dumpHasStream(mdump.path, CrashTestUtils.MD_THREAD_LIST_STREAM));
do_check_true(CrashTestUtils.dumpHasInstructionPointerMemory(mdump.path));
if (is_windows) {
- ['SystemMemoryUsePercentage', 'TotalVirtualMemory', 'AvailableVirtualMemory',
- 'AvailablePageFile', 'AvailablePhysicalMemory'].forEach(function(prop) {
+ ["SystemMemoryUsePercentage", "TotalVirtualMemory", "AvailableVirtualMemory",
+ "AvailablePageFile", "AvailablePhysicalMemory"].forEach(function(prop) {
do_check_true(/^\d+$/.test(extra[prop].toString()));
});
}
if (is_win7_or_newer)
do_check_true(CrashTestUtils.dumpHasStream(mdump.path, CrashTestUtils.MD_MEMORY_INFO_LIST_STREAM));
});
// check setting some basic data
--- a/toolkit/crashreporter/test/unit_ipc/test_content_annotation.js
+++ b/toolkit/crashreporter/test/unit_ipc/test_content_annotation.js
@@ -10,13 +10,13 @@ function run_test() {
// Try crashing with a runtime abort
do_content_crash(function() {
crashType = CrashTestUtils.CRASH_MOZ_CRASH;
crashReporter.annotateCrashReport("TestKey", "TestValue");
crashReporter.appendAppNotesToCrashReport("!!!foo!!!");
},
function(mdump, extra) {
do_check_eq(extra.TestKey, "TestValue");
- do_check_true('StartupTime' in extra);
- do_check_true('ProcessType' in extra);
+ do_check_true("StartupTime" in extra);
+ do_check_true("ProcessType" in extra);
do_check_neq(extra.Notes.indexOf("!!!foo!!!"), -1);
});
}
--- a/toolkit/crashreporter/test/unit_ipc/test_content_exception_time_annotation.js
+++ b/toolkit/crashreporter/test/unit_ipc/test_content_exception_time_annotation.js
@@ -7,11 +7,11 @@ function run_test() {
return;
}
// Try crashing with an OOM
do_content_crash(function() {
crashType = CrashTestUtils.CRASH_OOM;
},
function(mdump, extra) {
- do_check_true('OOMAllocationSize' in extra);
+ do_check_true("OOMAllocationSize" in extra);
});
}
--- a/toolkit/forgetaboutsite/test/unit/test_removeDataFromDomain.js
+++ b/toolkit/forgetaboutsite/test/unit/test_removeDataFromDomain.js
@@ -452,46 +452,46 @@ function* test_push_cleared() {
} catch (e) {
// No push service, skip test.
return;
}
do_get_profile();
setPrefs();
const {PushService, PushServiceWebSocket} = serviceExports;
- const userAgentID = 'bd744428-f125-436a-b6d0-dd0c9845837f';
- const channelID = '0ef2ad4a-6c49-41ad-af6e-95d2425276bf';
+ const userAgentID = "bd744428-f125-436a-b6d0-dd0c9845837f";
+ const channelID = "0ef2ad4a-6c49-41ad-af6e-95d2425276bf";
let db = PushServiceWebSocket.newPushDB();
try {
PushService.init({
serverURI: "wss://push.example.org/",
db,
makeWebSocket(uriObj) {
return new MockWebSocket(uriObj, {
onHello(request) {
this.serverSendMsg(JSON.stringify({
- messageType: 'hello',
+ messageType: "hello",
status: 200,
uaid: userAgentID,
}));
},
});
}
});
const TEST_URL = "https://www.mozilla.org/scope/";
do_check_false(yield push_registration_exists(TEST_URL, ps));
yield db.put({
channelID,
- pushEndpoint: 'https://example.org/update/clear-success',
+ pushEndpoint: "https://example.org/update/clear-success",
scope: TEST_URL,
version: 1,
- originAttributes: '',
+ originAttributes: "",
quota: Infinity,
});
do_check_true(yield push_registration_exists(TEST_URL, ps));
let promisePurgeNotification = waitForPurgeNotification();
yield ForgetAboutSite.removeDataFromDomain("mozilla.org");
yield promisePurgeNotification;
--- a/toolkit/identity/Identity.jsm
+++ b/toolkit/identity/Identity.jsm
@@ -246,19 +246,19 @@ IDService.prototype = {
* @param aScheme
* (string) (optional) Protocol to use. Default is https.
* This is necessary because we are unable to test
* https.
*
* @param aCallback
*
*/
- _fetchWellKnownFile: function _fetchWellKnownFile(aDomain, aCallback, aScheme = 'https') {
+ _fetchWellKnownFile: function _fetchWellKnownFile(aDomain, aCallback, aScheme = "https") {
// XXX bug 769854 make tests https and remove aScheme option
- let url = aScheme + '://' + aDomain + "/.well-known/browserid";
+ let url = aScheme + "://" + aDomain + "/.well-known/browserid";
log("_fetchWellKnownFile:", url);
// this appears to be a more successful way to get at xmlhttprequest (which supposedly will close with a window
let req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Ci.nsIXMLHttpRequest);
// XXX bug 769865 gracefully handle being off-line
// XXX bug 769866 decide on how to handle redirects
@@ -271,17 +271,17 @@ IDService.prototype = {
return aCallback("Error");
}
try {
let idpParams = req.response;
// Verify that the IdP returned a valid configuration
if (!(idpParams.provisioning &&
idpParams.authentication &&
- idpParams['public-key'])) {
+ idpParams["public-key"])) {
let errStr = "Invalid well-known file from: " + aDomain;
log("_fetchWellKnownFile:", errStr);
return aCallback(errStr);
}
let callbackObj = {
domain: aDomain,
idpParams,
--- a/toolkit/identity/IdentityProvider.jsm
+++ b/toolkit/identity/IdentityProvider.jsm
@@ -72,17 +72,17 @@ IdentityProviderService.prototype = {
getProvisionFlow: function getProvisionFlow(aProvId, aErrBack) {
let provFlow = this._provisionFlows[aProvId];
if (provFlow) {
return provFlow;
}
let err = "No provisioning flow found with id " + aProvId;
log("ERROR:", err);
- if (typeof aErrBack === 'function') {
+ if (typeof aErrBack === "function") {
aErrBack(err);
}
return undefined;
},
shutdown: function RP_shutdown() {
this.reset();
@@ -375,17 +375,17 @@ IdentityProviderService.prototype = {
let authFlow = this._authenticationFlows[aAuthId];
if (!authFlow) {
reportError("completeAuthentication", "No auth flow with id", aAuthId);
return;
}
let provId = authFlow.provId;
// delete caller
- delete authFlow['caller'];
+ delete authFlow["caller"];
delete this._authenticationFlows[aAuthId];
let provFlow = this.getProvisionFlow(provId);
provFlow.didAuthentication = true;
let subject = {
rpId: provFlow.rpId,
identity: provFlow.identity,
};
@@ -406,17 +406,17 @@ IdentityProviderService.prototype = {
let authFlow = this._authenticationFlows[aAuthId];
if (!authFlow) {
reportError("cancelAuthentication", "No auth flow with id:", aAuthId);
return;
}
let provId = authFlow.provId;
// delete caller
- delete authFlow['caller'];
+ delete authFlow["caller"];
delete this._authenticationFlows[aAuthId];
let provFlow = this.getProvisionFlow(provId);
provFlow.didAuthentication = true;
Services.obs.notifyObservers(null, "identity-auth-complete", aAuthId);
// invoke callback with ERROR.
let errStr = "Authentication canceled by IDP";
@@ -463,27 +463,27 @@ IdentityProviderService.prototype = {
Services.obs.notifyObservers({wrappedJSObject:propBag}, "identity-auth", aURL);
},
/**
* Clean up a provision flow and the authentication flow and sandbox
* that may be attached to it.
*/
_cleanUpProvisionFlow: function _cleanUpProvisionFlow(aProvId) {
- log('_cleanUpProvisionFlow:', aProvId);
+ log("_cleanUpProvisionFlow:", aProvId);
let prov = this._provisionFlows[aProvId];
// Clean up the sandbox, if there is one.
if (prov.provisioningSandbox) {
- let sandbox = this._provisionFlows[aProvId]['provisioningSandbox'];
+ let sandbox = this._provisionFlows[aProvId]["provisioningSandbox"];
if (sandbox.free) {
- log('_cleanUpProvisionFlow: freeing sandbox');
+ log("_cleanUpProvisionFlow: freeing sandbox");
sandbox.free();
}
- delete this._provisionFlows[aProvId]['provisioningSandbox'];
+ delete this._provisionFlows[aProvId]["provisioningSandbox"];
}
// Clean up a related authentication flow, if there is one.
if (this._authenticationFlows[prov.authId]) {
delete this._authenticationFlows[prov.authId];
}
// Finally delete the provision flow
--- a/toolkit/identity/IdentityUtils.jsm
+++ b/toolkit/identity/IdentityUtils.jsm
@@ -27,17 +27,17 @@ XPCOMUtils.defineLazyServiceGetter(this,
XPCOMUtils.defineLazyModuleGetter(this, "Logger",
"resource://gre/modules/identity/LogUtils.jsm");
function log(...aMessageArgs) {
Logger.log.apply(Logger, ["Identity"].concat(aMessageArgs));
}
function defined(item) {
- return typeof item !== 'undefined';
+ return typeof item !== "undefined";
}
var checkDeprecated = this.checkDeprecated = function checkDeprecated(aOptions, aField) {
if (defined(aOptions[aField])) {
log("WARNING: field is deprecated:", aField);
return true;
}
return false;
@@ -63,17 +63,17 @@ this.getRandomId = function getRandomId(
/*
* copy source object into target, excluding private properties
* (those whose names begin with an underscore)
*/
this.objectCopy = function objectCopy(source, target) {
let desc;
Object.getOwnPropertyNames(source).forEach(function(name) {
- if (name[0] !== '_') {
+ if (name[0] !== "_") {
desc = Object.getOwnPropertyDescriptor(source, name);
Object.defineProperty(target, name, desc);
}
});
};
this.makeMessageObject = function makeMessageObject(aRpCaller) {
let options = {};
@@ -87,25 +87,25 @@ this.makeMessageObject = function makeMe
// Special flag for internal calls for Persona in b2g
options._internal = aRpCaller._internal;
Object.keys(aRpCaller).forEach(function(option) {
// Duplicate the callerobject, scrubbing out functions and other
// internal variables (like _mm, the message manager object)
if (!Object.hasOwnProperty(this, option)
- && option[0] !== '_'
- && typeof aRpCaller[option] !== 'function') {
+ && option[0] !== "_"
+ && typeof aRpCaller[option] !== "function") {
options[option] = aRpCaller[option];
}
});
// check validity of message structure
- if ((typeof options.id === 'undefined') ||
- (typeof options.origin === 'undefined')) {
+ if ((typeof options.id === "undefined") ||
+ (typeof options.origin === "undefined")) {
let err = "id and origin required in relying-party message: " + JSON.stringify(options);
reportError(err);
throw new Error(err);
}
return options;
}
--- a/toolkit/identity/LogUtils.jsm
+++ b/toolkit/identity/LogUtils.jsm
@@ -44,31 +44,31 @@ IdentityLogger.prototype = {
_generateLogMessage: function _generateLogMessage(aPrefix, args) {
// create a string representation of a list of arbitrary things
let strings = [];
// XXX bug 770418 - args look like flattened array, not list of strings
args.forEach(function(arg) {
- if (typeof arg === 'string') {
+ if (typeof arg === "string") {
strings.push(arg);
- } else if (typeof arg === 'undefined') {
- strings.push('undefined');
+ } else if (typeof arg === "undefined") {
+ strings.push("undefined");
} else if (arg === null) {
- strings.push('null');
+ strings.push("null");
} else {
try {
strings.push(JSON.stringify(arg, null, 2));
} catch (err) {
strings.push("<<something>>");
}
}
});
- return 'Identity ' + aPrefix + ': ' + strings.join(' ');
+ return "Identity " + aPrefix + ": " + strings.join(" ");
},
/**
* log() - utility function to print a list of arbitrary things
*
* Enable with about:config pref toolkit.identity.debug
*/
log: function log(aPrefix, ...args) {
--- a/toolkit/identity/MinimalIdentity.jsm
+++ b/toolkit/identity/MinimalIdentity.jsm
@@ -99,17 +99,17 @@ IDService.prototype = {
* - doError()
* - doCancel()
*
*/
watch: function watch(aRpCaller) {
// store the caller structure and notify the UI observers
this._rpFlows[aRpCaller.id] = aRpCaller;
- log("flows:", Object.keys(this._rpFlows).join(', '));
+ log("flows:", Object.keys(this._rpFlows).join(", "));
let options = makeMessageObject(aRpCaller);
log("sending identity-controller-watch:", options);
Services.obs.notifyObservers({wrappedJSObject: options}, "identity-controller-watch", null);
},
/*
* The RP has gone away; remove handles to the hidden iframe.
--- a/toolkit/identity/RelyingParty.jsm
+++ b/toolkit/identity/RelyingParty.jsm
@@ -295,17 +295,17 @@ IdentityRelyingParty.prototype = {
throw "audience required for _getAssertion";
}
// We might not have any identity info for this email
if (!this._store.fetchIdentity(email)) {
this._store.addIdentity(email, null, null);
}
- let cert = this._store.fetchIdentity(email)['cert'];
+ let cert = this._store.fetchIdentity(email)["cert"];
if (cert) {
this._generateAssertion(audience, email, function generatedAssertion(err, assertion) {
if (err) {
log("ERROR: _getAssertion:", err);
}
log("_getAssertion: generated assertion:", assertion);
return aCallback(err, assertion);
});
@@ -351,17 +351,17 @@ IdentityRelyingParty.prototype = {
},
/**
* Clean up references to the provisioning flow for the specified RP.
*/
_cleanUpProvisionFlow: function RP_cleanUpProvisionFlow(aRPId, aProvId) {
let rp = this._rpFlows[aRPId];
if (rp) {
- delete rp['provId'];
+ delete rp["provId"];
} else {
log("Error: Couldn't delete provision flow ", aProvId, " for RP ", aRPId);
}
},
};
this.RelyingParty = new IdentityRelyingParty();
--- a/toolkit/identity/tests/unit/test_authentication.js
+++ b/toolkit/identity/tests/unit/test_authentication.js
@@ -65,17 +65,17 @@ function test_complete_authentication_fl
get_idstore().setLoginState(TEST_URL, true, id);
// When we authenticate, our ready callback will be fired.
// At the same time, a separate topic will be sent up to the
// the observer in the UI. The test is complete when both
// events have occurred.
let mockedDoc = mock_doc(id, TEST_URL, call_sequentially(
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_eq(params, undefined);
// if notification already received by observer, test is done
callbacksFired = true;
if (loginStateChanged && identityAuthComplete) {
do_test_finished();
run_next_test();
}
--- a/toolkit/identity/tests/unit/test_crypto_service.js
+++ b/toolkit/identity/tests/unit/test_crypto_service.js
@@ -1,16 +1,16 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import('resource://gre/modules/identity/LogUtils.jsm');
+Cu.import("resource://gre/modules/identity/LogUtils.jsm");
const idService = Cc["@mozilla.org/identity/crypto-service;1"]
.getService(Ci.nsIIdentityCryptoService);
const ALG_DSA = "DS160";
const ALG_RSA = "RS256";
const BASE64_URL_ENCODINGS = [
--- a/toolkit/identity/tests/unit/test_firefox_accounts.js
+++ b/toolkit/identity/tests/unit/test_firefox_accounts.js
@@ -41,17 +41,17 @@ do_register_cleanup(() => {
FirefoxAccounts.fxAccountsManager = originalManager;
});
function withNobodySignedIn() {
return FirefoxAccounts.fxAccountsManager.signOut();
}
function withSomebodySignedIn() {
- return FirefoxAccounts.fxAccountsManager.signIn('Pertelote');
+ return FirefoxAccounts.fxAccountsManager.signIn("Pertelote");
}
function test_overall() {
do_check_neq(FirefoxAccounts, null);
run_next_test();
}
function test_mock() {
--- a/toolkit/identity/tests/unit/test_identity.js
+++ b/toolkit/identity/tests/unit/test_identity.js
@@ -10,17 +10,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
function test_overall() {
do_check_neq(IDService, null);
run_next_test();
}
function test_mock_doc() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL, function(action, params) {
- do_check_eq(action, 'coffee');
+ do_check_eq(action, "coffee");
do_test_finished();
run_next_test();
});
mockedDoc.doCoffee();
}
function test_add_identity() {
@@ -41,31 +41,31 @@ function test_select_identity() {
IDService.reset();
let id = "ishtar@mockmyid.com";
setup_test_identity(id, TEST_CERT, function() {
let gotAssertion = false;
let mockedDoc = mock_doc(null, TEST_URL, call_sequentially(
function(action, params) {
// ready emitted from first watch() call
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_null(params);
},
// first the login call
function(action, params) {
- do_check_eq(action, 'login');
+ do_check_eq(action, "login");
do_check_neq(params, null);
// XXX - check that the assertion is for the right email
gotAssertion = true;
},
// then the ready call
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_null(params);
// we should have gotten the assertion already
do_check_true(gotAssertion);
do_test_finished();
run_next_test();
}));
@@ -82,26 +82,26 @@ function test_select_identity() {
});
// do the request
IDService.RP.request(mockedDoc.id, {});
});
}
function test_parse_good_email() {
- var parsed = IDService.parseEmail('prime-minister@jed.gov');
- do_check_eq(parsed.username, 'prime-minister');
- do_check_eq(parsed.domain, 'jed.gov');
+ var parsed = IDService.parseEmail("prime-minister@jed.gov");
+ do_check_eq(parsed.username, "prime-minister");
+ do_check_eq(parsed.domain, "jed.gov");
run_next_test();
}
function test_parse_bogus_emails() {
- do_check_eq(null, IDService.parseEmail('@evil.org'));
- do_check_eq(null, IDService.parseEmail('foo@bar@baz.com'));
- do_check_eq(null, IDService.parseEmail('you@wellsfargo.com/accounts/transfer?to=dolske&amt=all'));
+ do_check_eq(null, IDService.parseEmail("@evil.org"));
+ do_check_eq(null, IDService.parseEmail("foo@bar@baz.com"));
+ do_check_eq(null, IDService.parseEmail("you@wellsfargo.com/accounts/transfer?to=dolske&amt=all"));
run_next_test();
}
var TESTS = [test_overall, test_mock_doc];
TESTS.push(test_add_identity);
TESTS.push(test_select_identity);
TESTS.push(test_parse_good_email);
--- a/toolkit/identity/tests/unit/test_identity_utils.js
+++ b/toolkit/identity/tests/unit/test_identity_utils.js
@@ -1,14 +1,14 @@
"use strict";
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://gre/modules/identity/IdentityUtils.jsm');
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/identity/IdentityUtils.jsm");
function test_check_deprecated() {
let options = {
id: 123,
loggedInEmail: "jed@foo.com",
pies: 42
};
--- a/toolkit/identity/tests/unit/test_jwcrypto.js
+++ b/toolkit/identity/tests/unit/test_jwcrypto.js
@@ -1,14 +1,14 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict"
-Cu.import('resource://gre/modules/identity/LogUtils.jsm');
+Cu.import("resource://gre/modules/identity/LogUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "IDService",
"resource://gre/modules/identity/Identity.jsm",
"IdentityService");
XPCOMUtils.defineLazyModuleGetter(this, "jwcrypto",
"resource://gre/modules/identity/jwcrypto.jsm");
@@ -226,17 +226,17 @@ function test_audience_encoding_bug97258
}
);
}
// End of tests
// Helper function follow
function extractComponents(signedObject) {
- if (typeof(signedObject) != 'string') {
+ if (typeof(signedObject) != "string") {
throw new Error("malformed signature " + typeof(signedObject));
}
let parts = signedObject.split(".");
if (parts.length != 3) {
throw new Error("signed object must have three parts, this one has " + parts.length);
}
--- a/toolkit/identity/tests/unit/test_log_utils.js
+++ b/toolkit/identity/tests/unit/test_log_utils.js
@@ -1,14 +1,14 @@
"use strict";
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import('resource://gre/modules/Services.jsm');
-Cu.import('resource://gre/modules/identity/LogUtils.jsm');
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/identity/LogUtils.jsm");
function toggle_debug() {
do_test_pending();
function Wrapper() {
this.init();
}
Wrapper.prototype = {
@@ -19,22 +19,22 @@ function toggle_debug() {
// race condition?
do_check_eq(Logger._debug, true);
do_test_finished();
run_next_test();
}
},
init() {
- Services.prefs.addObserver('toolkit.identity.debug', this, false);
+ Services.prefs.addObserver("toolkit.identity.debug", this, false);
}
};
new Wrapper();
- Services.prefs.setBoolPref('toolkit.identity.debug', true);
+ Services.prefs.setBoolPref("toolkit.identity.debug", true);
}
// test that things don't break
function logAlias(...args) {
Logger.log.apply(Logger, ["log alias"].concat(args));
}
function reportErrorAlias(...args) {
--- a/toolkit/identity/tests/unit/test_minimalidentity.js
+++ b/toolkit/identity/tests/unit/test_minimalidentity.js
@@ -17,17 +17,17 @@ function log(...aMessageArgs) {
function test_overall() {
do_check_neq(MinimalIDService, null);
run_next_test();
}
function test_mock_doc() {
do_test_pending();
let mockedDoc = mock_doc(null, TEST_URL, function(action, params) {
- do_check_eq(action, 'coffee');
+ do_check_eq(action, "coffee");
do_test_finished();
run_next_test();
});
mockedDoc.doCoffee();
}
/*
--- a/toolkit/identity/tests/unit/test_relying_party.js
+++ b/toolkit/identity/tests/unit/test_relying_party.js
@@ -18,17 +18,17 @@ function test_watch_loggedin_ready() {
let id = TEST_USER;
setup_test_identity(id, TEST_CERT, function() {
let store = get_idstore();
// set it up so we're supposed to be logged in to TEST_URL
store.setLoginState(TEST_URL, true, id);
RelyingParty.watch(mock_doc(id, TEST_URL, function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_eq(params, undefined);
do_test_finished();
run_next_test();
}));
});
}
@@ -42,21 +42,21 @@ function test_watch_loggedin_login() {
let store = get_idstore();
// set it up so we're supposed to be logged in to TEST_URL
store.setLoginState(TEST_URL, true, id);
// check for first a login() call, then a ready() call
RelyingParty.watch(mock_doc(null, TEST_URL, call_sequentially(
function(action, params) {
- do_check_eq(action, 'login');
+ do_check_eq(action, "login");
do_check_neq(params, null);
},
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_null(params);
do_test_finished();
run_next_test();
}
)));
});
}
@@ -75,60 +75,60 @@ function test_watch_loggedin_logout() {
// set it up so we're supposed to be logged in to TEST_URL
// with id, not other_id
store.setLoginState(TEST_URL, true, id);
// this should cause a login with an assertion for id,
// not for other_id
RelyingParty.watch(mock_doc(other_id, TEST_URL, call_sequentially(
function(action, params) {
- do_check_eq(action, 'login');
+ do_check_eq(action, "login");
do_check_neq(params, null);
},
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_null(params);
do_test_finished();
run_next_test();
}
)));
});
});
}
function test_watch_notloggedin_ready() {
do_test_pending();
resetState();
RelyingParty.watch(mock_doc(null, TEST_URL, function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_eq(params, undefined);
do_test_finished();
run_next_test();
}));
}
function test_watch_notloggedin_logout() {
do_test_pending();
resetState();
RelyingParty.watch(mock_doc(TEST_USER, TEST_URL, call_sequentially(
function(action, params) {
- do_check_eq(action, 'logout');
+ do_check_eq(action, "logout");
do_check_eq(params, undefined);
let store = get_idstore();
do_check_null(store.getLoginState(TEST_URL));
},
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_eq(params, undefined);
do_test_finished();
run_next_test();
}
)));
}
function test_request() {
@@ -204,27 +204,27 @@ function test_logout() {
let store = get_idstore();
// set it up so we're supposed to be logged in to TEST_URL
store.setLoginState(TEST_URL, true, id);
let doLogout;
let mockedDoc = mock_doc(id, TEST_URL, call_sequentially(
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_eq(params, undefined);
do_timeout(100, doLogout);
},
function(action, params) {
- do_check_eq(action, 'logout');
+ do_check_eq(action, "logout");
do_check_eq(params, undefined);
},
function(action, params) {
- do_check_eq(action, 'ready');
+ do_check_eq(action, "ready");
do_check_eq(params, undefined);
do_test_finished();
run_next_test();
}));
doLogout = function() {
RelyingParty.logout(mockedDoc.id);
--- a/toolkit/identity/tests/unit/test_well-known.js
+++ b/toolkit/identity/tests/unit/test_well-known.js
@@ -20,17 +20,17 @@ function test_well_known_1() {
server.registerFile(WELL_KNOWN_PATH, do_get_file("data/idp_1" + WELL_KNOWN_PATH));
server.start(SERVER_PORT);
let hostPort = "localhost:" + SERVER_PORT;
function check_well_known(aErr, aCallbackObj) {
do_check_null(aErr);
do_check_eq(aCallbackObj.domain, hostPort);
let idpParams = aCallbackObj.idpParams;
- do_check_eq(idpParams['public-key'].algorithm, "RS");
+ do_check_eq(idpParams["public-key"].algorithm, "RS");
do_check_eq(idpParams.authentication, "/browserid/sign_in.html");
do_check_eq(idpParams.provisioning, "/browserid/provision.html");
do_test_finished();
server.stop(run_next_test);
}
IDService._fetchWellKnownFile(hostPort, check_well_known, "http");
--- a/toolkit/modules/BrowserUtils.jsm
+++ b/toolkit/modules/BrowserUtils.jsm
@@ -10,17 +10,17 @@ this.EXPORTED_SYMBOLS = [ "BrowserUtils"
const {interfaces: Ci, utils: Cu, classes: Cc} = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
"resource://gre/modules/PlacesUtils.jsm");
-Cu.importGlobalProperties(['URL']);
+Cu.importGlobalProperties(["URL"]);
this.BrowserUtils = {
/**
* Prints arguments separated by a space and appends a new line.
*/
dumpLn(...args) {
for (let a of args)
@@ -264,17 +264,17 @@ this.BrowserUtils = {
let rel = linkNode.getAttribute("rel");
if (!rel)
return false;
// The HTML spec says that rel should be split on spaces before looking
// for particular rel values.
let values = rel.split(/[ \t\r\n\f]/);
- return values.indexOf('noreferrer') != -1;
+ return values.indexOf("noreferrer") != -1;
},
/**
* Returns true if |mimeType| is text-based, or false otherwise.
*
* @param mimeType
* The MIME type to check.
*/
--- a/toolkit/modules/Console.jsm
+++ b/toolkit/modules/Console.jsm
@@ -208,17 +208,17 @@ function log(aThing) {
reply += "Map\n";
for (let [key, value] of aThing) {
reply += logProperty(key, value);
}
} else if (type == "Set") {
let i = 0;
reply += "Set\n";
for (let value of aThing) {
- reply += logProperty('' + i, value);
+ reply += logProperty("" + i, value);
i++;
}
} else if (isError(aThing)) {
reply += " Message: " + aThing + "\n";
if (aThing.stack) {
reply += " Stack:\n";
var frame = aThing.stack;
while (frame) {
@@ -246,17 +246,17 @@ function log(aThing) {
if (!(property in logged)) {
logged[property] = property;
reply += logProperty(property, aThing[property]);
}
});
root = Object.getPrototypeOf(root);
if (root != null) {
- reply += ' - prototype ' + getCtorName(root) + '\n';
+ reply += " - prototype " + getCtorName(root) + "\n";
}
}
}
}
return reply;
}
--- a/toolkit/modules/Geometry.jsm
+++ b/toolkit/modules/Geometry.jsm
@@ -65,17 +65,17 @@ Point.prototype = {
function takePointOrArgs(f) {
return function(arg1, arg2) {
if (arg2 === undefined)
return f.call(this, arg1.x, arg1.y);
return f.call(this, arg1, arg2);
};
}
- for (let f of ['add', 'subtract', 'equals', 'set'])
+ for (let f of ["add", "subtract", "equals", "set"])
Point.prototype[f] = takePointOrArgs(Point.prototype[f]);
})();
/**
* Rect is a simple data structure for representation of a rectangle supporting
* many basic geometric operations.
*
--- a/toolkit/modules/Log.jsm
+++ b/toolkit/modules/Log.jsm
@@ -427,25 +427,25 @@ LoggerRepository.prototype = {
}
return this._rootLogger;
},
set rootLogger(logger) {
throw "Cannot change the root logger";
},
_updateParents: function LogRep__updateParents(name) {
- let pieces = name.split('.');
+ let pieces = name.split(".");
let cur, parent;
// find the closest parent
// don't test for the logger name itself, as there's a chance it's already
// there in this._loggers
for (let i = 0; i < pieces.length - 1; i++) {
if (cur)
- cur += '.' + pieces[i];
+ cur += "." + pieces[i];
else
cur = pieces[i];
if (cur in this._loggers)
parent = cur;
}
// if we didn't assign a parent above, there is no parent
if (!parent)
@@ -535,48 +535,48 @@ BasicFormatter.prototype = {
*/
formatText(message) {
let params = message.params;
if (typeof(params) == "undefined") {
return message.message || "";
}
// Defensive handling of non-object params
// We could add a special case for NSRESULT values here...
- let pIsObject = (typeof(params) == 'object' || typeof(params) == 'function');
+ let pIsObject = (typeof(params) == "object" || typeof(params) == "function");
// if we have params, try and find substitutions.
if (this.parameterFormatter) {
// have we successfully substituted any parameters into the message?
// in the log message
let subDone = false;
let regex = /\$\{(\S*)\}/g;
let textParts = [];
if (message.message) {
textParts.push(message.message.replace(regex, (_, sub) => {
// ${foo} means use the params['foo']
if (sub) {
if (pIsObject && sub in message.params) {
subDone = true;
return this.parameterFormatter.format(message.params[sub]);
}
- return '${' + sub + '}';
+ return "${" + sub + "}";
}
// ${} means use the entire params object.
subDone = true;
return this.parameterFormatter.format(message.params);
}));
}
if (!subDone) {
// There were no substitutions in the text, so format the entire params object
let rest = this.parameterFormatter.format(message.params);
if (rest !== null && rest != "{}") {
textParts.push(rest);
}
}
- return textParts.join(': ');
+ return textParts.join(": ");
}
return undefined;
},
format: function BF_format(message) {
return message.time + "\t" +
message.loggerName + "\t" +
message.levelDesc + "\t" +
@@ -626,17 +626,17 @@ StructuredFormatter.prototype = {
return JSON.stringify(output);
}
}
/**
* Test an object to see if it is a Mozilla JS Error.
*/
function isError(aObj) {
- return (aObj && typeof(aObj) == 'object' && "name" in aObj && "message" in aObj &&
+ return (aObj && typeof(aObj) == "object" && "name" in aObj && "message" in aObj &&
"fileName" in aObj && "lineNumber" in aObj && "stack" in aObj);
}
/*
* Parameter Formatters
* These massage an object used as a parameter for a LogMessage into
* a string representation of the object.
*/
--- a/toolkit/modules/NewTabUtils.jsm
+++ b/toolkit/modules/NewTabUtils.jsm
@@ -25,17 +25,17 @@ XPCOMUtils.defineLazyModuleGetter(this,
XPCOMUtils.defineLazyGetter(this, "gCryptoHash", function() {
return Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
});
XPCOMUtils.defineLazyGetter(this, "gUnicodeConverter", function() {
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.createInstance(Ci.nsIScriptableUnicodeConverter);
- converter.charset = 'utf8';
+ converter.charset = "utf8";
return converter;
});
// Boolean preferences that control newtab content
const PREF_NEWTAB_ENABLED = "browser.newtabpage.enabled";
const PREF_NEWTAB_ENHANCED = "browser.newtabpage.enhanced";
// The preference that tells the number of rows of the newtab grid.
--- a/toolkit/modules/Promise-backend.js
+++ b/toolkit/modules/Promise-backend.js
@@ -286,17 +286,17 @@ if (Cu) {
}
// Default mechanism for displaying errors
PendingErrors.addObserver(function(details) {
const generalDescription = "A promise chain failed to handle a rejection." +
" Did you forget to '.catch', or did you forget to 'return'?\nSee" +
" https://developer.mozilla.org/Mozilla/JavaScript_code_modules/Promise.jsm/Promise\n\n";
- let error = Cc['@mozilla.org/scripterror;1'].createInstance(Ci.nsIScriptError);
+ let error = Cc["@mozilla.org/scripterror;1"].createInstance(Ci.nsIScriptError);
if (!error || !Services.console) {
// Too late during shutdown to use the nsIConsole
dump("*************************\n");
dump(generalDescription);
dump("On: " + details.date + "\n");
dump("Full message: " + details.message + "\n");
dump("Full stack: " + (details.stack || "not available") + "\n");
dump("*************************\n");
--- a/toolkit/modules/PropertyListUtils.jsm
+++ b/toolkit/modules/PropertyListUtils.jsm
@@ -56,17 +56,17 @@
"use strict";
this.EXPORTED_SYMBOLS = ["PropertyListUtils"];
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
-Cu.importGlobalProperties(['File', 'FileReader']);
+Cu.importGlobalProperties(["File", "FileReader"]);
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ctypes",
"resource://gre/modules/ctypes.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Services",
"resource://gre/modules/Services.jsm");
this.PropertyListUtils = Object.freeze({
--- a/toolkit/modules/SelectContentHelper.jsm
+++ b/toolkit/modules/SelectContentHelper.jsm
@@ -205,23 +205,23 @@ function getComputedStyles(element) {
}
function buildOptionListForChildren(node) {
let result = [];
for (let child of node.children) {
let tagName = child.tagName.toUpperCase();
- if (tagName == 'OPTION' || tagName == 'OPTGROUP') {
+ if (tagName == "OPTION" || tagName == "OPTGROUP") {
if (child.hidden) {
continue;
}
let textContent =
- tagName == 'OPTGROUP' ? child.getAttribute("label")
+ tagName == "OPTGROUP" ? child.getAttribute("label")
: child.text;
if (textContent == null) {
textContent = "";
}
let cs = getComputedStyles(child);
let info = {
@@ -236,15 +236,15 @@ function buildOptionListForChildren(node
tooltip: child.title,
// XXX this uses a highlight color when this is the selected element.
// We need to suppress such highlighting in the content process to get
// the option's correct unhighlighted color here.
// We also need to detect default color vs. custom so that a standard
// color does not override color: menutext in the parent.
// backgroundColor: computedStyle.backgroundColor,
// color: computedStyle.color,
- children: tagName == 'OPTGROUP' ? buildOptionListForChildren(child) : []
+ children: tagName == "OPTGROUP" ? buildOptionListForChildren(child) : []
};
result.push(info);
}
}
return result;
}
--- a/toolkit/modules/SelectParentHelper.jsm
+++ b/toolkit/modules/SelectParentHelper.jsm
@@ -166,17 +166,17 @@ function populateChildren(menulist, opti
// Grab the computed text size and multiply it by the remote browser's fullZoom to ensure
// the popup's text size is matched with the content's. We can't just apply a CSS transform
// here as the popup's preferred size is calculated pre-transform.
let textSize = win.getComputedStyle(element).getPropertyValue("font-size");
adjustedTextSize = (zoom * parseFloat(textSize, 10)) + "px";
}
for (let option of options) {
- let isOptGroup = (option.tagName == 'OPTGROUP');
+ let isOptGroup = (option.tagName == "OPTGROUP");
let item = element.ownerDocument.createElement(isOptGroup ? "menucaption" : "menuitem");
item.setAttribute("label", option.textContent);
item.style.direction = option.textDirection;
item.style.fontSize = adjustedTextSize;
item.hidden = option.display == "none" || (parentElement && parentElement.hidden);
item.setAttribute("tooltiptext", option.tooltip);
--- a/toolkit/modules/ShortcutUtils.jsm
+++ b/toolkit/modules/ShortcutUtils.jsm
@@ -88,17 +88,17 @@ var ShortcutUtils = {
let key;
let keyCode = aElemKey.getAttribute("keycode");
if (keyCode) {
try {
// Some keys might not exist in the locale file, which will throw:
key = Keys.GetStringFromName(keyCode.toUpperCase());
} catch (ex) {
Cu.reportError("Error finding " + keyCode + ": " + ex);
- key = keyCode.replace(/^VK_/, '');
+ key = keyCode.replace(/^VK_/, "");
}
} else {
key = aElemKey.getAttribute("key");
key = key.toUpperCase();
}
return elemString + key;
},
--- a/toolkit/modules/SpatialNavigation.jsm
+++ b/toolkit/modules/SpatialNavigation.jsm
@@ -36,17 +36,17 @@ const Ci = Components.interfaces;
const Cu = Components.utils;
Cu.import("resource://gre/modules/Services.jsm", this);
var eventListenerService = Cc["@mozilla.org/eventlistenerservice;1"]
.getService(Ci.nsIEventListenerService);
var focusManager = Cc["@mozilla.org/focus-manager;1"]
.getService(Ci.nsIFocusManager);
-var windowMediator = Cc['@mozilla.org/appshell/window-mediator;1']
+var windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
// Debug helpers:
function dump(a) {
Services.console.logStringMessage("SpatialNavigation: " + a);
}
function dumpRect(desc, rect) {
@@ -65,34 +65,34 @@ function dumpNodeCoord(desc, node) {
const kAlt = "alt";
const kShift = "shift";
const kCtrl = "ctrl";
const kNone = "none";
function _onInputKeyPress(event, callback) {
// If Spatial Navigation isn't enabled, return.
- if (!PrefObserver['enabled']) {
+ if (!PrefObserver["enabled"]) {
return;
}
// Use whatever key value is available (either keyCode or charCode).
// It might be useful for addons or whoever wants to set different
// key to be used here (e.g. "a", "F1", "arrowUp", ...).
var key = event.which || event.keyCode;
- if (key != PrefObserver['keyCodeDown'] &&
- key != PrefObserver['keyCodeRight'] &&
- key != PrefObserver['keyCodeUp'] &&
- key != PrefObserver['keyCodeLeft'] &&
- key != PrefObserver['keyCodeReturn']) {
+ if (key != PrefObserver["keyCodeDown"] &&
+ key != PrefObserver["keyCodeRight"] &&
+ key != PrefObserver["keyCodeUp"] &&
+ key != PrefObserver["keyCodeLeft"] &&
+ key != PrefObserver["keyCodeReturn"]) {
return;
}
- if (key == PrefObserver['keyCodeReturn']) {
+ if (key == PrefObserver["keyCodeReturn"]) {
// We report presses of the action button on a gamepad "A" as the return
// key to the DOM. The behaviour of hitting the return key and clicking an
// element is the same for some elements, but not all, so we handle the
// ones we want (like the Select element) here:
if (event.target instanceof Ci.nsIDOMHTMLSelectElement &&
event.target.click) {
event.target.click();
event.stopPropagation();
@@ -100,19 +100,19 @@ function _onInputKeyPress(event, callbac
return;
}
// Leave the action key press to get reported to the DOM as a return
// keypress.
return;
}
// If it is not using the modifiers it should, return.
- if (!event.altKey && PrefObserver['modifierAlt'] ||
- !event.shiftKey && PrefObserver['modifierShift'] ||
- !event.crtlKey && PrefObserver['modifierCtrl']) {
+ if (!event.altKey && PrefObserver["modifierAlt"] ||
+ !event.shiftKey && PrefObserver["modifierShift"] ||
+ !event.crtlKey && PrefObserver["modifierCtrl"]) {
return;
}
let currentlyFocused = event.target;
let currentlyFocusedWindow = currentlyFocused.ownerDocument.defaultView;
let bestElementToFocus = null;
// If currentlyFocused is an nsIDOMHTMLBodyElement then the page has just been
@@ -129,18 +129,18 @@ function _onInputKeyPress(event, callbac
currentlyFocused instanceof Ci.nsIDOMHTMLTextAreaElement) {
// If there is a text selection, remain in the element.
if (currentlyFocused.selectionEnd - currentlyFocused.selectionStart != 0) {
return;
}
// If there is no text, there is nothing special to do.
if (currentlyFocused.textLength > 0) {
- if (key == PrefObserver['keyCodeRight'] ||
- key == PrefObserver['keyCodeDown'] ) {
+ if (key == PrefObserver["keyCodeRight"] ||
+ key == PrefObserver["keyCodeDown"] ) {
// We are moving forward into the document.
if (currentlyFocused.textLength != currentlyFocused.selectionEnd) {
return;
}
} else if (currentlyFocused.selectionStart != 0) {
return;
}
}
@@ -153,49 +153,49 @@ function _onInputKeyPress(event, callbac
let nodes = {};
nodes.length = 0;
let searchRectOverflows = false;
while (!bestElementToFocus && !searchRectOverflows) {
switch (key) {
- case PrefObserver['keyCodeLeft']:
- case PrefObserver['keyCodeRight']: {
+ case PrefObserver["keyCodeLeft"]:
+ case PrefObserver["keyCodeRight"]: {
if (searchRect.top < cssPageRect.top &&
searchRect.bottom > cssPageRect.bottom) {
searchRectOverflows = true;
}
break;
}
- case PrefObserver['keyCodeUp']:
- case PrefObserver['keyCodeDown']: {
+ case PrefObserver["keyCodeUp"]:
+ case PrefObserver["keyCodeDown"]: {
if (searchRect.left < cssPageRect.left &&
searchRect.right > cssPageRect.right) {
searchRectOverflows = true;
}
break;
}
}
nodes = windowUtils.nodesFromRect(searchRect.left, searchRect.top,
0, searchRect.width, searchRect.height, 0,
true, false);
// Make the search rectangle "wider": double it's size in the direction
// that is not the keypress.
switch (key) {
- case PrefObserver['keyCodeLeft']:
- case PrefObserver['keyCodeRight']: {
+ case PrefObserver["keyCodeLeft"]:
+ case PrefObserver["keyCodeRight"]: {
searchRect.top = searchRect.top - (searchRect.height / 2);
searchRect.bottom = searchRect.top + (searchRect.height * 2);
searchRect.height = searchRect.height * 2;
break;
}
- case PrefObserver['keyCodeUp']:
- case PrefObserver['keyCodeDown']: {
+ case PrefObserver["keyCodeUp"]:
+ case PrefObserver["keyCodeDown"]: {
searchRect.left = searchRect.left - (searchRect.width / 2);
searchRect.right = searchRect.left + (searchRect.width * 2);
searchRect.width = searchRect.width * 2;
break;
}
}
bestElementToFocus = _getBestToFocus(nodes, key, currentlyFocused);
}
@@ -258,33 +258,33 @@ function _getBestToFocus(nodes, key, cur
if (!_canFocus(nodes[i]) || nodes[i] === currentlyFocused) {
continue;
}
// Reject all nodes that aren't "far enough" in the direction of the
// keypress
nodeMid = _getMidpoint(nodes[i]);
switch (key) {
- case PrefObserver['keyCodeLeft']:
+ case PrefObserver["keyCodeLeft"]:
if (nodeMid.x >= (currentlyFocusedMid.x - currentlyFocusedRect.width / 2)) {
continue;
}
break;
- case PrefObserver['keyCodeRight']:
+ case PrefObserver["keyCodeRight"]:
if (nodeMid.x <= (currentlyFocusedMid.x + currentlyFocusedRect.width / 2)) {
continue;
}
break;
- case PrefObserver['keyCodeUp']:
+ case PrefObserver["keyCodeUp"]:
if (nodeMid.y >= (currentlyFocusedMid.y - currentlyFocusedRect.height / 2)) {
continue;
}
break;
- case PrefObserver['keyCodeDown']:
+ case PrefObserver["keyCodeDown"]:
if (nodeMid.y <= (currentlyFocusedMid.y + currentlyFocusedRect.height / 2)) {
continue;
}
break;
}
// Initialize best to the first viable value:
if (!best) {
@@ -350,47 +350,47 @@ function _getSearchRect(currentlyFocused
newRect.left = currentlyFocusedRect.left;
newRect.top = currentlyFocusedRect.top;
newRect.right = currentlyFocusedRect.right;
newRect.bottom = currentlyFocusedRect.bottom;
newRect.width = currentlyFocusedRect.width;
newRect.height = currentlyFocusedRect.height;
switch (key) {
- case PrefObserver['keyCodeLeft']:
+ case PrefObserver["keyCodeLeft"]:
newRect.right = newRect.left;
newRect.left = cssPageRect.left;
newRect.width = newRect.right - newRect.left;
newRect.bottom = cssPageRect.bottom;
newRect.top = cssPageRect.top;
newRect.height = newRect.bottom - newRect.top;
break;
- case PrefObserver['keyCodeRight']:
+ case PrefObserver["keyCodeRight"]:
newRect.left = newRect.right;
newRect.right = cssPageRect.right;
newRect.width = newRect.right - newRect.left;
newRect.bottom = cssPageRect.bottom;
newRect.top = cssPageRect.top;
newRect.height = newRect.bottom - newRect.top;
break;
- case PrefObserver['keyCodeUp']:
+ case PrefObserver["keyCodeUp"]:
newRect.bottom = newRect.top;
newRect.top = cssPageRect.top;
newRect.height = newRect.bottom - newRect.top;
newRect.right = cssPageRect.right;
newRect.left = cssPageRect.left;
newRect.width = newRect.right - newRect.left;
break;
- case PrefObserver['keyCodeDown']:
+ case PrefObserver["keyCodeDown"]:
newRect.top = newRect.bottom;
newRect.bottom = cssPageRect.bottom;
newRect.height = newRect.bottom - newRect.top;
newRect.right = cssPageRect.right;
newRect.left = cssPageRect.left;
newRect.width = newRect.right - newRect.left;
break;
@@ -412,59 +412,59 @@ function _spatialDistanceOfCorner(from,
let fromRect = from.getBoundingClientRect();
let toRect = to.getBoundingClientRect();
let fromMid = _getMidpoint(from);
let toMid = _getMidpoint(to);
let hDistance = 0;
let vDistance = 0;
switch (key) {
- case PrefObserver['keyCodeLeft']:
+ case PrefObserver["keyCodeLeft"]:
// Make sure the "to" node is really at the left side of "from" node by
// 1. Check the mid point
// 2. The right border of "to" node must be less than the "from" node
if ((fromMid.x - toMid.x) < 0 || toRect.right >= fromRect.right)
return -1;
hDistance = Math.abs(fromRect.left - toRect.right);
if (toRect.bottom <= fromRect.top) {
vDistance = fromRect.top - toRect.bottom;
} else if (fromRect.bottom <= toRect.top) {
vDistance = toRect.top - fromRect.bottom;
} else {
vDistance = 0;
}
break;
- case PrefObserver['keyCodeRight']:
+ case PrefObserver["keyCodeRight"]:
if ((toMid.x - fromMid.x) < 0 || toRect.left <= fromRect.left)
return -1;
hDistance = Math.abs(toRect.left - fromRect.right);
if (toRect.bottom <= fromRect.top) {
vDistance = fromRect.top - toRect.bottom;
} else if (fromRect.bottom <= toRect.top) {
vDistance = toRect.top - fromRect.bottom;
} else {
vDistance = 0;
}
break;
- case PrefObserver['keyCodeUp']:
+ case PrefObserver["keyCodeUp"]:
if ((fromMid.y - toMid.y) < 0 || toRect.bottom >= fromRect.bottom)
return -1;
vDistance = Math.abs(fromRect.top - toRect.bottom);
if (fromRect.right <= toRect.left) {
hDistance = toRect.left - fromRect.right;
} else if (toRect.right <= fromRect.left) {
hDistance = fromRect.left - toRect.right;
} else {
hDistance = 0;
}
break;
- case PrefObserver['keyCodeDown']:
+ case PrefObserver["keyCodeDown"]:
if ((toMid.y - fromMid.y) < 0 || toRect.top <= fromRect.top)
return -1;
vDistance = Math.abs(toRect.top - fromRect.bottom);
if (fromRect.right <= toRect.left) {
hDistance = toRect.left - fromRect.right;
} else if (toRect.right <= fromRect.left) {
hDistance = fromRect.left - toRect.right;
} else {
--- a/toolkit/modules/UpdateUtils.jsm
+++ b/toolkit/modules/UpdateUtils.jsm
@@ -126,17 +126,17 @@ function getDistributionPrefValue(aPrefN
* Gets the locale from the update.locale file for replacing %LOCALE% in the
* update url. The update.locale file can be located in the application
* directory or the GRE directory with preference given to it being located in
* the application directory.
*/
XPCOMUtils.defineLazyGetter(UpdateUtils, "Locale", function() {
let channel;
let locale;
- for (let res of ['app', 'gre']) {
+ for (let res of ["app", "gre"]) {
channel = NetUtil.newChannel({
uri: "resource://" + res + "/" + FILE_UPDATE_LOCALE,
contentPolicyType: Ci.nsIContentPolicy.TYPE_INTERNAL_XMLHTTPREQUEST,
loadUsingSystemPrincipal: true
});
try {
let inputStream = channel.open2();
locale = NetUtil.readInputStreamToString(inputStream, inputStream.available());
@@ -203,17 +203,17 @@ XPCOMUtils.defineLazyGetter(this, "gWinC
// Get processor architecture
let arch = "unknown";
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724958%28v=vs.85%29.aspx
- const SYSTEM_INFO = new ctypes.StructType('SYSTEM_INFO',
+ const SYSTEM_INFO = new ctypes.StructType("SYSTEM_INFO",
[
{wProcessorArchitecture: WORD},
{wReserved: WORD},
{dwPageSize: DWORD},
{lpMinimumApplicationAddress: ctypes.voidptr_t},
{lpMaximumApplicationAddress: ctypes.voidptr_t},
{dwActiveProcessorMask: DWORD.ptr},
{dwNumberOfProcessors: DWORD},
@@ -302,17 +302,17 @@ XPCOMUtils.defineLazyGetter(UpdateUtils,
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
const WCHAR = ctypes.char16_t;
const BOOL = ctypes.int;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724833%28v=vs.85%29.aspx
const SZCSDVERSIONLENGTH = 128;
- const OSVERSIONINFOEXW = new ctypes.StructType('OSVERSIONINFOEXW',
+ const OSVERSIONINFOEXW = new ctypes.StructType("OSVERSIONINFOEXW",
[
{dwOSVersionInfoSize: DWORD},
{dwMajorVersion: DWORD},
{dwMinorVersion: DWORD},
{dwBuildNumber: DWORD},
{dwPlatformId: DWORD},
{szCSDVersion: ctypes.ArrayType(WCHAR, SZCSDVERSIONLENGTH)},
{wServicePackMajor: WORD},
--- a/toolkit/modules/tests/xpcshell/test_CanonicalJSON.js
+++ b/toolkit/modules/tests/xpcshell/test_CanonicalJSON.js
@@ -1,88 +1,88 @@
const { CanonicalJSON } = Components.utils.import("resource://gre/modules/CanonicalJSON.jsm", {});
function stringRepresentation(obj) {
const clone = JSON.parse(JSON.stringify(obj));
return JSON.stringify(clone);
}
add_task(function* test_canonicalJSON_should_preserve_array_order() {
- const input = ['one', 'two', 'three'];
+ const input = ["one", "two", "three"];
// No sorting should be done on arrays.
do_check_eq(CanonicalJSON.stringify(input), '["one","two","three"]');
});
add_task(function* test_canonicalJSON_orders_object_keys() {
const input = [{
- b: ['two', 'three'],
- a: ['zero', 'one']
+ b: ["two", "three"],
+ a: ["zero", "one"]
}];
do_check_eq(
CanonicalJSON.stringify(input),
'[{"a":["zero","one"],"b":["two","three"]}]'
);
});
add_task(function* test_canonicalJSON_orders_nested_object_keys() {
const input = [{
- b: {d: 'd', c: 'c'},
- a: {b: 'b', a: 'a'}
+ b: {d: "d", c: "c"},
+ a: {b: "b", a: "a"}
}];
do_check_eq(
CanonicalJSON.stringify(input),
'[{"a":{"a":"a","b":"b"},"b":{"c":"c","d":"d"}}]'
);
});
add_task(function* test_canonicalJSON_escapes_unicode_values() {
do_check_eq(
- CanonicalJSON.stringify([{key: '✓'}]),
+ CanonicalJSON.stringify([{key: "✓"}]),
'[{"key":"\\u2713"}]'
);
// Unicode codepoints should be output in lowercase.
do_check_eq(
- CanonicalJSON.stringify([{key: 'é'}]),
+ CanonicalJSON.stringify([{key: "é"}]),
'[{"key":"\\u00e9"}]'
);
});
add_task(function* test_canonicalJSON_escapes_unicode_object_keys() {
do_check_eq(
- CanonicalJSON.stringify([{'é': 'check'}]),
+ CanonicalJSON.stringify([{"é": "check"}]),
'[{"\\u00e9":"check"}]'
);
});
add_task(function* test_canonicalJSON_does_not_alter_input() {
const records = [
- {'foo': 'bar', 'last_modified': '12345', 'id': '1'},
- {'bar': 'baz', 'last_modified': '45678', 'id': '2'}
+ {"foo": "bar", "last_modified": "12345", "id": "1"},
+ {"bar": "baz", "last_modified": "45678", "id": "2"}
];
const serializedJSON = JSON.stringify(records);
CanonicalJSON.stringify(records);
do_check_eq(JSON.stringify(records), serializedJSON);
});
add_task(function* test_canonicalJSON_preserves_data() {
const records = [
- {'foo': 'bar', 'last_modified': '12345', 'id': '1'},
- {'bar': 'baz', 'last_modified': '45678', 'id': '2'},
+ {"foo": "bar", "last_modified": "12345", "id": "1"},
+ {"bar": "baz", "last_modified": "45678", "id": "2"},
]
const expected = '[{"foo":"bar","id":"1","last_modified":"12345"},' +
'{"bar":"baz","id":"2","last_modified":"45678"}]';
do_check_eq(CanonicalJSON.stringify(records), expected);
});
add_task(function* test_canonicalJSON_does_not_add_space_separators() {
const records = [
- {'foo': 'bar', 'last_modified': '12345', 'id': '1'},
- {'bar': 'baz', 'last_modified': '45678', 'id': '2'},
+ {"foo": "bar", "last_modified": "12345", "id": "1"},
+ {"bar": "baz", "last_modified": "45678", "id": "2"},
]
const serialized = CanonicalJSON.stringify(records);
do_check_false(serialized.includes(" "));
});
add_task(function* test_canonicalJSON_serializes_empty_object() {
do_check_eq(CanonicalJSON.stringify({}), "{}");
});
@@ -106,37 +106,37 @@ add_task(function* test_canonicalJSON_se
});
add_task(function* test_canonicalJSON_escapes_backslashes() {
do_check_eq(CanonicalJSON.stringify("This\\and this"), '"This\\\\and this"');
});
add_task(function* test_canonicalJSON_handles_signed_zeros() {
// do_check_eq doesn't support comparison of -0 and 0 properly.
- do_check_true(CanonicalJSON.stringify(-0) === '-0');
- do_check_true(CanonicalJSON.stringify(0) === '0');
+ do_check_true(CanonicalJSON.stringify(-0) === "-0");
+ do_check_true(CanonicalJSON.stringify(0) === "0");
});
add_task(function* test_canonicalJSON_with_deeply_nested_dicts() {
const records = [{
- 'a': {
- 'b': 'b',
- 'a': 'a',
- 'c': {
- 'b': 'b',
- 'a': 'a',
- 'c': ['b', 'a', 'c'],
- 'd': {'b': 'b', 'a': 'a'},
- 'id': '1',
- 'e': 1,
- 'f': [2, 3, 1],
- 'g': {2: 2, 3: 3, 1: {
- 'b': 'b', 'a': 'a', 'c': 'c'}}}},
- 'id': '1'}]
+ "a": {
+ "b": "b",
+ "a": "a",
+ "c": {
+ "b": "b",
+ "a": "a",
+ "c": ["b", "a", "c"],
+ "d": {"b": "b", "a": "a"},
+ "id": "1",
+ "e": 1,
+ "f": [2, 3, 1],
+ "g": {2: 2, 3: 3, 1: {
+ "b": "b", "a": "a", "c": "c"}}}},
+ "id": "1"}]
const expected =
'[{"a":{"a":"a","b":"b","c":{"a":"a","b":"b","c":["b","a","c"],' +
'"d":{"a":"a","b":"b"},"e":1,"f":[2,3,1],"g":{' +
'"1":{"a":"a","b":"b","c":"c"},"2":2,"3":3},"id":"1"}},"id":"1"}]';
do_check_eq(CanonicalJSON.stringify(records), expected);
});
--- a/toolkit/modules/tests/xpcshell/test_Http.js
+++ b/toolkit/modules/tests/xpcshell/test_Http.js
@@ -182,32 +182,32 @@ add_test(function test_CustomContentType
},
onError(e) {
do_check_true(false);
do_test_finished();
run_next_test();
},
postData: kJsonPostData,
// Setting a custom Content-Type header.
- headers: [['Content-Type', "application/json"]]
+ headers: [["Content-Type", "application/json"]]
}
// Firing the request.
httpRequest(kJsonPostUrl, options);
});
/**
* Ensures that the httpRequest API provides a way to override the response
* MIME type.
*/
add_test(function test_OverrideMimeType() {
do_test_pending();
// Preparing the request parameters.
- const kMimeType = 'text/xml; charset=UTF-8';
+ const kMimeType = "text/xml; charset=UTF-8";
let options = {
onLoad(aResponse, xhr) {
do_check_eq(aResponse, "Success!");
// Set the expected MIME-type.
let reportedMimeType = xhr.getResponseHeader("Content-Type");
do_check_neq(reportedMimeType, kMimeType);
--- a/toolkit/modules/tests/xpcshell/test_Log.js
+++ b/toolkit/modules/tests/xpcshell/test_Log.js
@@ -360,72 +360,72 @@ add_task(function* log_message_with_para
// An object nested inside params is JSON-formatted and substituted.
do_check_eq(formatMessage("Sub object is ${sub}", {sub: {foo: "bar"}}),
'Sub object is {"foo":"bar"}');
// The substitution field is missing from params. Leave the placeholder behind
// to make the mistake obvious.
do_check_eq(formatMessage("Missing object is ${missing}", {}),
- 'Missing object is ${missing}');
+ "Missing object is ${missing}");
// Make sure we don't treat the parameter name 'false' as a falsey value.
do_check_eq(formatMessage("False is ${false}", {false: true}),
- 'False is true');
+ "False is true");
// If an object has a .toJSON method, the formatter uses it.
let ob = function() {};
ob.toJSON = function() {return {sneaky: "value"}};
do_check_eq(formatMessage("JSON is ${sub}", {sub: ob}),
'JSON is {"sneaky":"value"}');
// Fall back to .toSource() if JSON.stringify() fails on an object.
ob = function() {};
ob.toJSON = function() {throw "oh noes JSON"};
do_check_eq(formatMessage("Fail is ${sub}", {sub: ob}),
- 'Fail is (function () {})');
+ "Fail is (function () {})");
// Fall back to .toString if both .toJSON and .toSource fail.
ob.toSource = function() {throw "oh noes SOURCE"};
do_check_eq(formatMessage("Fail is ${sub}", {sub: ob}),
- 'Fail is function () {}');
+ "Fail is function () {}");
// Fall back to '[object]' if .toJSON, .toSource and .toString fail.
ob.toString = function() {throw "oh noes STRING"};
do_check_eq(formatMessage("Fail is ${sub}", {sub: ob}),
- 'Fail is [object]');
+ "Fail is [object]");
// If params are passed but there are no substitution in the text
// we JSON format and append the entire parameters object.
do_check_eq(formatMessage("Text with no subs", {a: "b", c: "d"}),
'Text with no subs: {"a":"b","c":"d"}');
// If we substitute one parameter but not the other,
// we ignore any params that aren't substituted.
do_check_eq(formatMessage("Text with partial sub ${a}", {a: "b", c: "d"}),
- 'Text with partial sub b');
+ "Text with partial sub b");
// We don't format internal fields stored in params.
do_check_eq(formatMessage("Params with _ ${}", {a: "b", _c: "d", _level:20, _message:"froo",
_time:123456, _namespace:"here.there"}),
'Params with _ {"a":"b","_c":"d"}');
// Don't print an empty params holder if all params are internal.
do_check_eq(formatMessage("All params internal", {_level:20, _message:"froo",
_time:123456, _namespace:"here.there"}),
- 'All params internal');
+ "All params internal");
// Format params with null and undefined values.
do_check_eq(formatMessage("Null ${n} undefined ${u}", {n: null, u: undefined}),
- 'Null null undefined undefined');
+ "Null null undefined undefined");
// Format params with number, bool, and Object/String type.
do_check_eq(formatMessage("number ${n} boolean ${b} boxed Boolean ${bx} String ${s}",
{n: 45, b: false, bx: new Boolean(true), s: new String("whatevs")}),
- 'number 45 boolean false boxed Boolean true String whatevs');
+ "number 45 boolean false boxed Boolean true String whatevs");
/*
* Check that errors get special formatting if they're formatted directly as
* a named param or they're the only param, but not if they're a field in a
* larger structure.
*/
let err = Components.Exception("test exception", Components.results.NS_ERROR_FAILURE);
let str = formatMessage("Exception is ${}", err);
@@ -452,40 +452,40 @@ add_task(function* log_message_with_para
let vOf = {a: 1, valueOf: function() {throw "oh noes valueOf"}};
do_check_eq(formatMessage("Broken valueOf ${}", vOf),
'Broken valueOf ({a:1, valueOf:(function () {throw "oh noes valueOf"})})');
/* eslint-enable object-shorthand */
// Test edge cases of bad data to formatter:
// If 'params' is not an object, format it as a basic type.
do_check_eq(formatMessage("non-object no subst", 1),
- 'non-object no subst: 1');
+ "non-object no subst: 1");
do_check_eq(formatMessage("non-object all subst ${}", 2),
- 'non-object all subst 2');
+ "non-object all subst 2");
do_check_eq(formatMessage("false no subst", false),
- 'false no subst: false');
+ "false no subst: false");
do_check_eq(formatMessage("null no subst", null),
- 'null no subst: null');
+ "null no subst: null");
// If 'params' is undefined and there are no substitutions expected,
// the message should still be output.
do_check_eq(formatMessage("undefined no subst", undefined),
- 'undefined no subst');
+ "undefined no subst");
// If 'params' is not an object, no named substitutions can succeed;
// therefore we leave the placeholder and append the formatted params.
do_check_eq(formatMessage("non-object named subst ${junk} space", 3),
- 'non-object named subst ${junk} space: 3');
+ "non-object named subst ${junk} space: 3");
// If there are no params, we leave behind the placeholders in the text.
do_check_eq(formatMessage("no params ${missing}", undefined),
- 'no params ${missing}');
+ "no params ${missing}");
// If params doesn't contain any of the tags requested in the text,
// we leave them all behind and append the formatted params.
do_check_eq(formatMessage("object missing tag ${missing} space", {mising: "not here"}),
'object missing tag ${missing} space: {"mising":"not here"}');
// If we are given null text and no params, the resulting formatted message is empty.
- do_check_eq(formatMessage(null), '');
+ do_check_eq(formatMessage(null), "");
});
/*
* If we call a log function with a non-string object in place of the text
* argument, and no parameters, treat that the same as logging empty text
* with the object argument as parameters. This makes the log useful when the
* caller does "catch(err) {logger.error(err)}"
*/
@@ -528,17 +528,17 @@ add_task(function* test_structured_basic
do_check_eq(appender.messages.length, 1);
do_check_true(appender.messages[0].includes('{"data":"structure","action":"action"}'));
// A structured entry with _message and substitution is treated the same as
// log./level/(null, params).
log.logStructured("action", {_message: "Structured sub ${data}", data: "structure"});
do_check_eq(appender.messages.length, 2);
do_print(appender.messages[1]);
- do_check_true(appender.messages[1].includes('Structured sub structure'));
+ do_check_true(appender.messages[1].includes("Structured sub structure"));
});
/*
* Test that all the basic logger methods pass the message and params through to the appender.
*/
add_task(function* log_message_with_params() {
let log = Log.repository.getLogger("error.logger");
let mockFormatter = { format: msg => msg };
--- a/toolkit/modules/tests/xpcshell/test_UpdateUtils_url.js
+++ b/toolkit/modules/tests/xpcshell/test_UpdateUtils_url.js
@@ -37,17 +37,17 @@ function getServicePack() {
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
const WCHAR = ctypes.char16_t;
const BOOL = ctypes.int;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724833%28v=vs.85%29.aspx
const SZCSDVERSIONLENGTH = 128;
- const OSVERSIONINFOEXW = new ctypes.StructType('OSVERSIONINFOEXW',
+ const OSVERSIONINFOEXW = new ctypes.StructType("OSVERSIONINFOEXW",
[
{dwOSVersionInfoSize: DWORD},
{dwMajorVersion: DWORD},
{dwMinorVersion: DWORD},
{dwBuildNumber: DWORD},
{dwPlatformId: DWORD},
{szCSDVersion: ctypes.ArrayType(WCHAR, SZCSDVERSIONLENGTH)},
{wServicePackMajor: WORD},
@@ -82,17 +82,17 @@ function getProcArchitecture() {
// it uses throw() instead of do_throw(). Any tests that use this function
// should catch exceptions thrown in this function and deal with them
// appropriately (usually by calling do_throw).
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724958%28v=vs.85%29.aspx
- const SYSTEM_INFO = new ctypes.StructType('SYSTEM_INFO',
+ const SYSTEM_INFO = new ctypes.StructType("SYSTEM_INFO",
[
{wProcessorArchitecture: WORD},
{wReserved: WORD},
{dwPageSize: DWORD},
{lpMinimumApplicationAddress: ctypes.voidptr_t},
{lpMaximumApplicationAddress: ctypes.voidptr_t},
{dwActiveProcessorMask: DWORD.ptr},
{dwNumberOfProcessors: DWORD},
--- a/toolkit/modules/tests/xpcshell/test_client_id.js
+++ b/toolkit/modules/tests/xpcshell/test_client_id.js
@@ -38,26 +38,26 @@ add_task(function* () {
Assert.equal(clientID, yield ClientID.getClientID());
// We should be guarded against broken FHR data.
for (let invalidID of invalidIDs) {
yield ClientID._reset();
yield OS.File.remove(drsPath);
yield CommonUtils.writeJSON({clientID: invalidID}, fhrPath);
clientID = yield ClientID.getClientID();
- Assert.equal(typeof(clientID), 'string');
+ Assert.equal(typeof(clientID), "string");
Assert.ok(uuidRegex.test(clientID));
}
// We should be guarded against invalid FHR json.
yield ClientID._reset();
yield OS.File.remove(drsPath);
yield OS.File.writeAtomic(fhrPath, "abcd", {encoding: "utf-8", tmpPath: fhrPath + ".tmp"});
clientID = yield ClientID.getClientID();
- Assert.equal(typeof(clientID), 'string');
+ Assert.equal(typeof(clientID), "string");
Assert.ok(uuidRegex.test(clientID));
// We should be guarded against broken DRS data too and fall back to loading
// the FHR ID.
for (let invalidID of invalidIDs) {
yield ClientID._reset();
clientID = CommonUtils.generateUUID();
yield CommonUtils.writeJSON({clientID}, fhrPath);
@@ -65,26 +65,26 @@ add_task(function* () {
Assert.equal(clientID, yield ClientID.getClientID());
}
// We should be guarded against invalid DRS json too.
yield ClientID._reset();
yield OS.File.remove(fhrPath);
yield OS.File.writeAtomic(drsPath, "abcd", {encoding: "utf-8", tmpPath: drsPath + ".tmp"});
clientID = yield ClientID.getClientID();
- Assert.equal(typeof(clientID), 'string');
+ Assert.equal(typeof(clientID), "string");
Assert.ok(uuidRegex.test(clientID));
// If both the FHR and DSR data are broken, we should end up with a new client ID.
for (let invalidID of invalidIDs) {
yield ClientID._reset();
yield CommonUtils.writeJSON({clientID: invalidID}, fhrPath);
yield CommonUtils.writeJSON({clientID: invalidID}, drsPath);
clientID = yield ClientID.getClientID();
- Assert.equal(typeof(clientID), 'string');
+ Assert.equal(typeof(clientID), "string");
Assert.ok(uuidRegex.test(clientID));
}
// Assure that cached IDs are being checked for validity.
for (let invalidID of invalidIDs) {
yield ClientID._reset();
Preferences.set(PREF_CACHED_CLIENTID, invalidID);
let cachedID = ClientID.getCachedClientID();
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -18,17 +18,17 @@ if ("@mozilla.org/xre/app-info;1" in Cc)
if (runtime.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) {
// Refuse to run in child processes.
throw new Error("You cannot use the AddonManager in child processes!");
}
}
Cu.import("resource://gre/modules/AppConstants.jsm");
-const MOZ_COMPATIBILITY_NIGHTLY = !['aurora', 'beta', 'release', 'esr'].includes(AppConstants.MOZ_UPDATE_CHANNEL);
+const MOZ_COMPATIBILITY_NIGHTLY = !["aurora", "beta", "release", "esr"].includes(AppConstants.MOZ_UPDATE_CHANNEL);
const PREF_BLOCKLIST_PINGCOUNTVERSION = "extensions.blocklist.pingCountVersion";
const PREF_DEFAULT_PROVIDERS_ENABLED = "extensions.defaultProviders.enabled";
const PREF_EM_UPDATE_ENABLED = "extensions.update.enabled";
const PREF_EM_LAST_APP_VERSION = "extensions.lastAppVersion";
const PREF_EM_LAST_PLATFORM_VERSION = "extensions.lastPlatformVersion";
const PREF_EM_AUTOUPDATE_DEFAULT = "extensions.update.autoUpdateDefault";
const PREF_EM_STRICT_COMPATIBILITY = "extensions.strictCompatibility";
@@ -749,17 +749,17 @@ var AddonManagerInternal = {
*/
_startProvider(aProvider, aAppChanged, aOldAppVersion, aOldPlatformVersion) {
if (!gStarted)
throw Components.Exception("AddonManager is not initialized",
Cr.NS_ERROR_NOT_INITIALIZED);
logger.debug(`Starting provider: ${providerName(aProvider)}`);
callProvider(aProvider, "startup", null, aAppChanged, aOldAppVersion, aOldPlatformVersion);
- if ('shutdown' in aProvider) {
+ if ("shutdown" in aProvider) {
let name = providerName(aProvider);
let AMProviderShutdown = () => {
// If the provider has been unregistered, it will have been removed from
// this.providers. If it hasn't been unregistered, then this is a normal
// shutdown - and we move it to this.pendingProviders incase we're
// running in a test that will start AddonManager again.
if (this.providers.has(aProvider)) {
this.providers.delete(aProvider);
--- a/toolkit/mozapps/extensions/ChromeManifestParser.jsm
+++ b/toolkit/mozapps/extensions/ChromeManifestParser.jsm
@@ -43,17 +43,17 @@ this.ChromeManifestParser = {
* A nsIURI pointing to a chrome manifest.
* Typically a file: or jar: URI.
* @return Array of objects describing each manifest instruction, in the form:
* { type: instruction-type, baseURI: string-uri, args: [arguments] }
**/
parseSync(aURI) {
function parseLine(aLine) {
let line = aLine.trim();
- if (line.length == 0 || line.charAt(0) == '#')
+ if (line.length == 0 || line.charAt(0) == "#")
return;
let tokens = line.split(/\s+/);
let type = tokens.shift();
if (type == "manifest") {
let uri = NetUtil.newURI(tokens.shift(), null, aURI);
data = data.concat(this.parseSync(uri));
} else {
data.push({type, baseURI, args: tokens});
--- a/toolkit/mozapps/extensions/content/extensions.js
+++ b/toolkit/mozapps/extensions/content/extensions.js
@@ -1541,17 +1541,17 @@ function openOptionsInTab(optionsURL) {
}
return false;
}
function formatDate(aDate) {
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric" };
return aDate.toLocaleDateString(locale, dtOptions);
}
function hasPermission(aAddon, aPerm) {
var perm = AddonManager["PERM_CAN_" + aPerm.toUpperCase()];
return !!(aAddon.permissions & perm);
}
@@ -3351,17 +3351,17 @@ var gDetailView = {
} else if (this._addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE) {
menulist.selectedItem = askItem;
} else {
menulist.selectedItem = alwaysItem;
}
menulist.disabled = !hasActivatePermission;
menulist.hidden = false;
- menulist.classList.add('no-auto-hide');
+ menulist.classList.add("no-auto-hide");
} else {
menulist.hidden = true;
}
this.node.setAttribute("active", this._addon.isActive);
},
clearLoading() {
@@ -3415,17 +3415,17 @@ var gDetailView = {
gDetailView.scrollToPreferencesRows();
});
}
// This function removes and returns the text content of aNode without
// removing any child elements. Removing the text nodes ensures any XBL
// bindings apply properly.
function stripTextNodes(aNode) {
- var text = '';
+ var text = "";
for (var i = 0; i < aNode.childNodes.length; i++) {
if (aNode.childNodes[i].nodeType != document.ELEMENT_NODE) {
text += aNode.childNodes[i].textContent;
aNode.removeChild(aNode.childNodes[i--]);
} else {
text += stripTextNodes(aNode.childNodes[i]);
}
}
--- a/toolkit/mozapps/extensions/internal/AddonRepository.jsm
+++ b/toolkit/mozapps/extensions/internal/AddonRepository.jsm
@@ -769,17 +769,17 @@ this.AddonRepository = {
* (Optional) timeout in milliseconds to abandon the XHR request
* if we have not received a response from the server.
*/
_beginGetAddons(aIDs, aCallback, aSendPerformance, aTimeout) {
let ids = aIDs.slice(0);
let params = {
API_VERSION,
- IDS : ids.map(encodeURIComponent).join(',')
+ IDS : ids.map(encodeURIComponent).join(",")
};
let pref = PREF_GETADDONS_BYIDS;
if (aSendPerformance) {
let type = Services.prefs.getPrefType(PREF_GETADDONS_BYIDS_PERFORMANCE);
if (type == Services.prefs.PREF_STRING) {
pref = PREF_GETADDONS_BYIDS_PERFORMANCE;
--- a/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm
+++ b/toolkit/mozapps/extensions/internal/AddonTestUtils.jsm
@@ -603,28 +603,28 @@ var AddonTestUtils = {
var rdf = '<?xml version="1.0"?>\n';
rdf += '<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"\n' +
' xmlns:em="http://www.mozilla.org/2004/em-rdf#">\n';
for (let addon in data) {
rdf += escaped` <Description about="urn:mozilla:extension:${addon}"><em:updates><Seq>\n`;
for (let versionData of data[addon]) {
- rdf += ' <li><Description>\n';
+ rdf += " <li><Description>\n";
rdf += this._writeProps(versionData, ["version", "multiprocessCompatible"],
` `);
for (let app of versionData.targetApplications || []) {
rdf += " <em:targetApplication><Description>\n";
rdf += this._writeProps(app, ["id", "minVersion", "maxVersion", "updateLink", "updateHash"],
` `);
rdf += " </Description></em:targetApplication>\n";
}
- rdf += ' </Description></li>\n';
+ rdf += " </Description></li>\n";
}
- rdf += ' </Seq></em:updates></Description>\n';
+ rdf += " </Seq></em:updates></Description>\n";
}
rdf += "</RDF>\n";
return rdf;
},
_writeProps(obj, props, indent = " ") {
let items = [];
--- a/toolkit/mozapps/extensions/internal/GMPProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/GMPProvider.jsm
@@ -567,17 +567,17 @@ var GMPProvider = {
" invalid, uninstalling");
wrapper.uninstallPlugin();
continue;
}
this._log.info("startup - adding gmp directory " + gmpPath);
try {
gmpService.addPluginDirectory(gmpPath);
} catch (e) {
- if (e.name != 'NS_ERROR_NOT_AVAILABLE')
+ if (e.name != "NS_ERROR_NOT_AVAILABLE")
throw e;
this._log.warn("startup - adding gmp directory failed with " +
e.name + " - sandboxing not available?", e);
}
}
}
try {
--- a/toolkit/mozapps/extensions/internal/XPIProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/XPIProvider.jsm
@@ -989,17 +989,17 @@ var loadManifestFromWebManifest = Task.a
addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT;
function getLocale(aLocale) {
// Use the raw manifest, here, since we need values with their
// localization placeholders still in place.
let rawManifest = extension.rawManifest;
// As a convenience, allow author to be set if its a string bug 1313567.
- let creator = typeof(rawManifest.author) === 'string' ? rawManifest.author : null;
+ let creator = typeof(rawManifest.author) === "string" ? rawManifest.author : null;
let homepageURL = rawManifest.homepage_url;
// Allow developer to override creator and homepage_url.
if (rawManifest.developer) {
if (rawManifest.developer.name) {
creator = rawManifest.developer.name;
}
if (rawManifest.developer.url) {
@@ -1664,17 +1664,17 @@ function flushChromeCaches() {
* Creates and returns a new unique temporary file. The caller should delete
* the file when it is no longer needed.
*
* @return an nsIFile that points to a randomly named, initially empty file in
* the OS temporary files directory
*/
function getTemporaryFile() {
let file = FileUtils.getDir(KEY_TEMPDIR, []);
- let random = Math.random().toString(36).replace(/0./, '').substr(-3);
+ let random = Math.random().toString(36).replace(/0./, "").substr(-3);
file.append("tmp-" + random + ".xpi");
file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
return file;
}
/**
* Verifies that a zip file's contents are all signed by the same principal.
@@ -2092,26 +2092,26 @@ function XPIState(saved) {
for (let [short, long] of XPIState.prototype.fields) {
if (short in saved) {
this[long] = saved[short];
}
}
}
XPIState.prototype = {
- fields: [['d', 'descriptor'],
- ['e', 'enabled'],
- ['v', 'version'],
- ['st', 'scanTime'],
- ['mt', 'manifestTime']],
+ fields: [["d", "descriptor"],
+ ["e", "enabled"],
+ ["v", "version"],
+ ["st", "scanTime"],
+ ["mt", "manifestTime"]],
/**
* Return the last modified time, based on enabled/disabled
*/
get mtime() {
- if (!this.enabled && ('manifestTime' in this) && this.manifestTime > this.scanTime) {
+ if (!this.enabled && ("manifestTime" in this) && this.manifestTime > this.scanTime) {
return this.manifestTime;
}
return this.scanTime;
},
toJSON() {
let json = {};
for (let [short, long] of XPIState.prototype.fields) {
@@ -2127,18 +2127,18 @@ XPIState.prototype = {
* @param aFile: nsIFile path of the add-on.
* @param aId: The add-on ID.
* @return True if the time stamp has changed.
*/
getModTime(aFile, aId) {
let changed = false;
let scanStarted = Cu.now();
// For an unknown or enabled add-on, we do a full recursive scan.
- if (!('scanTime' in this) || this.enabled) {
- logger.debug('getModTime: Recursive scan of ' + aId);
+ if (!("scanTime" in this) || this.enabled) {
+ logger.debug("getModTime: Recursive scan of " + aId);
let [modFile, modTime, items] = recursiveLastModifiedTime(aFile);
XPIProvider._mostRecentlyModifiedFile[aId] = modFile;
XPIProvider.setTelemetry(aId, "scan_items", items);
if (modTime != this.scanTime) {
this.scanTime = modTime;
changed = true;
}
}
--- a/toolkit/mozapps/extensions/nsBlocklistService.js
+++ b/toolkit/mozapps/extensions/nsBlocklistService.js
@@ -1100,17 +1100,17 @@ Blocklist.prototype = {
// The blockID attribute is always present in the actual data produced on server
// (see https://github.com/mozilla/addons-server/blob/2016.05.05/src/olympia/blocklist/templates/blocklist/blocklist.xml#L74)
// But it is sometimes missing in test fixtures.
if (blocklistElement.hasAttribute("blockID")) {
blockEntry.blockID = blocklistElement.getAttribute("blockID");
}
// Trim helper (spaces, tabs, no-break spaces..)
- const trim = (s) => (s || '').replace(/(^[\s\uFEFF\xA0]+)|([\s\uFEFF\xA0]+$)/g, "");
+ const trim = (s) => (s || "").replace(/(^[\s\uFEFF\xA0]+)|([\s\uFEFF\xA0]+$)/g, "");
for (let i = 0; i < blocklistElement.childNodes.length; ++i) {
var matchElement = blocklistElement.childNodes.item(i);
if (!(matchElement instanceof Ci.nsIDOMElement))
continue;
let value;
if (matchElement.localName == "devices") {
--- a/toolkit/mozapps/extensions/test/browser/browser_bug523784.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_bug523784.js
@@ -9,17 +9,17 @@ const URI_BLOCKLIST_DIALOG = "chrome://m
var args = {
restart: false,
list: [{
name: "Bug 523784 softblocked addon",
version: "1",
icon: "chrome://mozapps/skin/plugins/pluginGeneric.png",
disable: false,
blocked: false,
- url: 'http://example.com/bug523784_1',
+ url: "http://example.com/bug523784_1",
}],
};
function test() {
waitForExplicitFinish();
let windowObserver = function(aSubject, aTopic, aData) {
if (aTopic != "domwindowopened")
@@ -49,17 +49,17 @@ function bug523784_test1(win) {
is(cancelButton.getAttribute("label"),
bundle.GetStringFromName("restartLaterButton"),
"Text should be changed on Cancel button");
is(cancelButton.getAttribute("accesskey"),
bundle.GetStringFromName("restartLaterButton.accesskey"),
"Accesskey should also be changed on Cancel button");
is(moreInfoLink.getAttribute("href"),
- 'http://example.com/bug523784_1',
+ "http://example.com/bug523784_1",
"More Info link should link to a detailed blocklist page.");
let windowObserver = function(aSubject, aTopic, aData) {
if (aTopic != "domwindowclosed")
return;
Services.ww.unregisterNotification(windowObserver);
ok(args.list[0].disable, "Should be blocking add-on");
@@ -98,23 +98,23 @@ function bug523784_test2(win) {
// Add 2 more addons to the blocked list to check that the more info link
// points to the general blocked list page.
args.list.push({
name: "Bug 523784 softblocked addon 2",
version: "2",
icon: "chrome://mozapps/skin/plugins/pluginGeneric.png",
disable: false,
blocked: false,
- url: 'http://example.com/bug523784_2'
+ url: "http://example.com/bug523784_2"
});
args.list.push({
name: "Bug 523784 softblocked addon 3",
version: "4",
icon: "chrome://mozapps/skin/plugins/pluginGeneric.png",
disable: false,
blocked: false,
- url: 'http://example.com/bug523784_3'
+ url: "http://example.com/bug523784_3"
});
args.wrappedJSObject = args;
Services.ww.openWindow(null, URI_BLOCKLIST_DIALOG, "",
"chrome,centerscreen,dialog,titlebar", args);
}
--- a/toolkit/mozapps/extensions/test/browser/browser_webapi_addon_listener.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_webapi_addon_listener.js
@@ -6,17 +6,17 @@ registerCleanupFunction(() => {
});
function* getListenerEvents(browser) {
let result = yield ContentTask.spawn(browser, null, function*() {
return content.document.getElementById("result").textContent;
});
- return result.split('\n').map(JSON.parse);
+ return result.split("\n").map(JSON.parse);
}
const RESTART_ID = "restart@tests.mozilla.org";
const RESTART_DISABLED_ID = "restart_disabled@tests.mozilla.org";
const RESTARTLESS_ID = "restartless@tests.mozilla.org";
const INSTALL_ID = "install@tests.mozilla.org";
const CANCEL_ID = "cancel@tests.mozilla.org";
--- a/toolkit/mozapps/extensions/test/browser/browser_webapi_enable.js
+++ b/toolkit/mozapps/extensions/test/browser/browser_webapi_enable.js
@@ -5,17 +5,17 @@ registerCleanupFunction(() => {
Services.prefs.clearUserPref("extensions.webapi.testing");
});
function* getListenerEvents(browser) {
let result = yield ContentTask.spawn(browser, null, function*() {
return content.document.getElementById("result").textContent;
});
- return result.split('\n').map(JSON.parse);
+ return result.split("\n").map(JSON.parse);
}
const ID = "test@tests.mozilla.org";
let provider = new MockProvider(false);
provider.createAddons([
{
id: ID,
--- a/toolkit/mozapps/extensions/test/browser/head.js
+++ b/toolkit/mozapps/extensions/test/browser/head.js
@@ -503,17 +503,17 @@ function get_string(aName, ...aArgs) {
return bundle.GetStringFromName(aName);
return bundle.formatStringFromName(aName, aArgs, aArgs.length);
}
function formatDate(aDate) {
const locale = Cc["@mozilla.org/chrome/chrome-registry;1"]
.getService(Ci.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric" };
return aDate.toLocaleDateString(locale, dtOptions);
}
function is_hidden(aElement) {
var style = aElement.ownerDocument.defaultView.getComputedStyle(aElement, "");
if (style.display == "none")
return true;
if (style.visibility != "visible")
--- a/toolkit/mozapps/extensions/test/xpcshell/test_bug455906.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_bug455906.js
@@ -437,21 +437,21 @@ function check_test_pt3() {
// Check blockIDs are correct
do_check_eq(blocklist.getAddonBlocklistURL(addons[0]), create_blocklistURL(addons[0].id));
do_check_eq(blocklist.getAddonBlocklistURL(addons[1]), create_blocklistURL(addons[1].id));
do_check_eq(blocklist.getAddonBlocklistURL(addons[2]), create_blocklistURL(addons[2].id));
do_check_eq(blocklist.getAddonBlocklistURL(addons[3]), create_blocklistURL(addons[3].id));
do_check_eq(blocklist.getAddonBlocklistURL(addons[4]), create_blocklistURL(addons[4].id));
// All plugins have the same blockID on the test
- do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[0]), create_blocklistURL('test_bug455906_plugin'));
- do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[1]), create_blocklistURL('test_bug455906_plugin'));
- do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[2]), create_blocklistURL('test_bug455906_plugin'));
- do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[3]), create_blocklistURL('test_bug455906_plugin'));
- do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[4]), create_blocklistURL('test_bug455906_plugin'));
+ do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[0]), create_blocklistURL("test_bug455906_plugin"));
+ do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[1]), create_blocklistURL("test_bug455906_plugin"));
+ do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[2]), create_blocklistURL("test_bug455906_plugin"));
+ do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[3]), create_blocklistURL("test_bug455906_plugin"));
+ do_check_eq(blocklist.getPluginBlocklistURL(PLUGINS[4]), create_blocklistURL("test_bug455906_plugin"));
// Shouldn't be changed
do_check_eq(check_addon_state(addons[5]), "false,false,true");
do_check_eq(check_addon_state(addons[6]), "false,false,true");
do_check_eq(check_plugin_state(PLUGINS[5]), "false,true");
// Back to starting state
gNotificationCheck = null;
--- a/toolkit/mozapps/extensions/test/xpcshell/test_no_addons.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_no_addons.js
@@ -58,17 +58,17 @@ add_task(function* first_run() {
startupManager();
check_empty_state();
yield true;
});
// Now do something that causes a DB load, and re-check
function* trigger_db_load() {
let addonDefer = Promise.defer();
- AddonManager.getAddonsByTypes(['extension'], addonDefer.resolve);
+ AddonManager.getAddonsByTypes(["extension"], addonDefer.resolve);
let addonList = yield addonDefer.promise;
do_check_eq(addonList.length, 0);
check_empty_state();
yield true;
}
add_task(trigger_db_load);
--- a/toolkit/mozapps/extensions/test/xpcshell/test_pluginInfoURL.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_pluginInfoURL.js
@@ -23,68 +23,68 @@ MockPlugin.prototype = {
get disabled() {
return this.enabledState == Ci.nsIPluginTag.STATE_DISABLED;
}
};
// The mocked blocked plugin used to test the blocklist.
const PLUGINS = [
- new MockPlugin('test_with_infoURL', '5', Ci.nsIPluginTag.STATE_ENABLED),
- new MockPlugin('test_with_altInfoURL', '5', Ci.nsIPluginTag.STATE_ENABLED),
- new MockPlugin('test_no_infoURL', '5', Ci.nsIPluginTag.STATE_ENABLED),
- new MockPlugin('test_newVersion', '1', Ci.nsIPluginTag.STATE_ENABLED),
- new MockPlugin('test_newVersion', '3', Ci.nsIPluginTag.STATE_ENABLED)
+ new MockPlugin("test_with_infoURL", "5", Ci.nsIPluginTag.STATE_ENABLED),
+ new MockPlugin("test_with_altInfoURL", "5", Ci.nsIPluginTag.STATE_ENABLED),
+ new MockPlugin("test_no_infoURL", "5", Ci.nsIPluginTag.STATE_ENABLED),
+ new MockPlugin("test_newVersion", "1", Ci.nsIPluginTag.STATE_ENABLED),
+ new MockPlugin("test_newVersion", "3", Ci.nsIPluginTag.STATE_ENABLED)
];
/**
* The entry point of the unit tests, which is also responsible of
* copying the blocklist file to the profile folder.
*/
function run_test() {
- copyBlocklistToProfile(do_get_file('data/pluginInfoURL_block.xml'));
+ copyBlocklistToProfile(do_get_file("data/pluginInfoURL_block.xml"));
- createAppInfo('xpcshell@tests.mozilla.org', 'XPCShell', '3', '8');
+ createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "3", "8");
startupManager();
run_next_test();
}
/**
* Test that the blocklist service correctly loads and returns the infoURL for
* a plugin that matches the first entry in the blocklist.
*/
add_task(function* test_infoURL() {
// The testInfoURL must match the value within the
// <infoURL> tag in pluginInfoURL_block.xml.
- let testInfoURL = 'http://test.url.com/';
+ let testInfoURL = "http://test.url.com/";
Assert.strictEqual(Services.blocklist.getPluginInfoURL(PLUGINS[0]),
- testInfoURL, 'Should be the provided url when an infoURL tag is available');
+ testInfoURL, "Should be the provided url when an infoURL tag is available");
});
/**
* Test that the blocklist service correctly loads and returns the infoURL for
* a plugin that partially matches an earlier entry in the blocklist.
*/
add_task(function* test_altInfoURL() {
- let altTestInfoURL = 'http://alt.test.url.com/';
+ let altTestInfoURL = "http://alt.test.url.com/";
Assert.strictEqual(Services.blocklist.getPluginInfoURL(PLUGINS[1]),
- altTestInfoURL, 'Should be the alternative infoURL');
+ altTestInfoURL, "Should be the alternative infoURL");
});
/**
* Test that the blocklist service correctly returns null
* if the infoURL tag is missing in the blocklist.xml file.
*/
add_task(function* test_infoURL_missing() {
Assert.strictEqual(Services.blocklist.getPluginInfoURL(PLUGINS[2]), null,
- 'Should be null when no infoURL tag is available.');
+ "Should be null when no infoURL tag is available.");
});
add_task(function* test_intoURL_newVersion() {
- let testInfoURL = 'http://test.url2.com/';
+ let testInfoURL = "http://test.url2.com/";
Assert.strictEqual(Services.blocklist.getPluginInfoURL(PLUGINS[3]),
- testInfoURL, 'Old plugin should match');
+ testInfoURL, "Old plugin should match");
Assert.strictEqual(Services.blocklist.getPluginInfoURL(PLUGINS[4]),
- null, 'New plugin should not match');
+ null, "New plugin should not match");
});
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_auth.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_auth.js
@@ -31,17 +31,17 @@ function download_failed(install) {
}
function install_ended(install, addon) {
install.cancel();
}
function finish_test(count) {
is(count, 1, "1 Add-on should have been successfully installed");
- var authMgr = Components.classes['@mozilla.org/network/http-auth-manager;1']
+ var authMgr = Components.classes["@mozilla.org/network/http-auth-manager;1"]
.getService(Components.interfaces.nsIHttpAuthManager);
authMgr.clearAll();
Services.perms.remove(makeURI("http://example.com"), "install");
gBrowser.removeCurrentTab();
Harness.finish();
}
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_auth2.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_auth2.js
@@ -30,17 +30,17 @@ function download_failed(install) {
function install_ended(install, addon) {
ok(false, "Add-on should not have installed");
install.cancel();
}
function finish_test(count) {
is(count, 0, "No add-ons should have been installed");
- var authMgr = Components.classes['@mozilla.org/network/http-auth-manager;1']
+ var authMgr = Components.classes["@mozilla.org/network/http-auth-manager;1"]
.getService(Components.interfaces.nsIHttpAuthManager);
authMgr.clearAll();
Services.perms.remove(makeURI("http://example.com"), "install");
gBrowser.removeCurrentTab();
Harness.finish();
}
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_auth3.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_auth3.js
@@ -37,17 +37,17 @@ function download_failed(install) {
function install_ended(install, addon) {
ok(false, "Add-on should not have installed");
install.cancel();
}
function finish_test(count) {
is(count, 0, "No add-ons should have been installed");
- var authMgr = Components.classes['@mozilla.org/network/http-auth-manager;1']
+ var authMgr = Components.classes["@mozilla.org/network/http-auth-manager;1"]
.getService(Components.interfaces.nsIHttpAuthManager);
authMgr.clearAll();
Services.perms.remove(makeURI("http://example.com"), "install");
gBrowser.removeCurrentTab();
Harness.finish();
}
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_auth4.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_auth4.js
@@ -36,17 +36,17 @@ function download_failed(install) {
}
function install_ended(install, addon) {
install.cancel();
}
function finish_test(count) {
is(count, 1, "1 Add-on should have been successfully installed");
- var authMgr = Components.classes['@mozilla.org/network/http-auth-manager;1']
+ var authMgr = Components.classes["@mozilla.org/network/http-auth-manager;1"]
.getService(Components.interfaces.nsIHttpAuthManager);
authMgr.clearAll();
Services.perms.remove(makeURI("http://example.com"), "install");
gBrowser.removeTab(gNewTab);
Harness.finish();
}
--- a/toolkit/mozapps/preferences/changemp.js
+++ b/toolkit/mozapps/preferences/changemp.js
@@ -44,17 +44,17 @@ function process() {
if (!token.needsLogin()) {
oldpwbox.setAttribute("inited", "empty");
} else {
oldpwbox.setAttribute("inited", "true");
}
// Select first password field
- document.getElementById('pw1').focus();
+ document.getElementById("pw1").focus();
} else {
// Select old password field
oldpwbox.setAttribute("hidden", "false");
msgBox.setAttribute("hidden", "true");
oldpwbox.setAttribute("inited", "false");
oldpwbox.focus();
}
}
@@ -151,17 +151,17 @@ function setPassword() {
function setPasswordStrength() {
// Here is how we weigh the quality of the password
// number of characters
// numbers
// non-alpha-numeric chars
// upper and lower case characters
- var pw = document.getElementById('pw1').value;
+ var pw = document.getElementById("pw1").value;
// length of the password
var pwlength = (pw.length);
if (pwlength > 5)
pwlength = 5;
// use of numbers in the password
@@ -189,23 +189,23 @@ function setPasswordStrength() {
if ( pwstrength < 0 ) {
pwstrength = 0;
}
if ( pwstrength > 100 ) {
pwstrength = 100;
}
- var mymeter = document.getElementById('pwmeter');
+ var mymeter = document.getElementById("pwmeter");
mymeter.value = pwstrength;
}
function checkPasswords() {
- var pw1 = document.getElementById('pw1').value;
- var pw2 = document.getElementById('pw2').value;
+ var pw1 = document.getElementById("pw1").value;
+ var pw2 = document.getElementById("pw2").value;
var ok = document.documentElement.getButton("accept");
var oldpwbox = document.getElementById("oldpw");
if (oldpwbox) {
var initpw = oldpwbox.getAttribute("inited");
if (initpw == "empty" && pw1 == "") {
// The token has already been initialized, therefore this dialog
--- a/toolkit/mozapps/update/content/history.js
+++ b/toolkit/mozapps/update/content/history.js
@@ -57,14 +57,14 @@ var gUpdateHistory = {
* A date in seconds since 1970 epoch
* @returns A human readable date string
*/
_formatDate(seconds) {
var date = new Date(seconds);
const locale = Components.classes["@mozilla.org/chrome/chrome-registry;1"]
.getService(Components.interfaces.nsIXULChromeRegistry)
.getSelectedLocale("global", true);
- const dtOptions = { year: 'numeric', month: 'long', day: 'numeric',
- hour: 'numeric', minute: 'numeric', second: 'numeric' };
+ const dtOptions = { year: "numeric", month: "long", day: "numeric",
+ hour: "numeric", minute: "numeric", second: "numeric" };
return date.toLocaleString(locale, dtOptions);
}
};
--- a/toolkit/mozapps/update/content/updates.js
+++ b/toolkit/mozapps/update/content/updates.js
@@ -1,14 +1,14 @@
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
/* import-globals-from ../../../content/contentAreaUtils.js */
// Firefox's macBrowserOverlay.xul includes scripts that define Cc, Ci, and Cr
// so we have to use different names.
const {classes: CoC, interfaces: CoI, results: CoR, utils: CoU} = Components;
/* globals DownloadUtils, Services, AUSTLMY */
--- a/toolkit/mozapps/update/nsUpdateService.js
+++ b/toolkit/mozapps/update/nsUpdateService.js
@@ -1,15 +1,15 @@
/* -*- Mode: javascript; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
-'use strict';
+"use strict";
const { classes: Cc, interfaces: Ci, results: Cr, utils: Cu } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
Cu.import("resource://gre/modules/FileUtils.jsm", this);
Cu.import("resource://gre/modules/Services.jsm", this);
Cu.import("resource://gre/modules/ctypes.jsm", this);
Cu.import("resource://gre/modules/UpdateTelemetry.jsm", this);
@@ -926,17 +926,17 @@ function shouldUseService() {
const BYTE = ctypes.uint8_t;
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
const WCHAR = ctypes.char16_t;
const BOOL = ctypes.int;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724833%28v=vs.85%29.aspx
const SZCSDVERSIONLENGTH = 128;
- const OSVERSIONINFOEXW = new ctypes.StructType('OSVERSIONINFOEXW',
+ const OSVERSIONINFOEXW = new ctypes.StructType("OSVERSIONINFOEXW",
[
{dwOSVersionInfoSize: DWORD},
{dwMajorVersion: DWORD},
{dwMinorVersion: DWORD},
{dwBuildNumber: DWORD},
{dwPlatformId: DWORD},
{szCSDVersion: ctypes.ArrayType(WCHAR, SZCSDVERSIONLENGTH)},
{wServicePackMajor: WORD},
--- a/toolkit/mozapps/update/tests/chrome/utils.js
+++ b/toolkit/mozapps/update/tests/chrome/utils.js
@@ -62,17 +62,17 @@
* array has ran.
*
* prefHasUserValue (optional)
* For comparing the expected value defined by this property with the return
* value of prefHasUserValue using gPrefToCheck for the preference name in the
* checkPrefHasUserValue function.
*/
-'use strict';
+"use strict";
/* globals TESTS, runTest, finishTest */
const { classes: Cc, interfaces: Ci, manager: Cm, results: Cr,
utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm", this);
--- a/toolkit/mozapps/update/tests/data/shared.js
+++ b/toolkit/mozapps/update/tests/data/shared.js
@@ -369,17 +369,17 @@ function readFileBytes(aFile) {
while (count > 0) {
let bytes = bis.readByteArray(Math.min(65535, count));
data.push(String.fromCharCode.apply(null, bytes));
count -= bytes.length;
if (bytes.length == 0) {
throw "Nothing read from input stream!";
}
}
- data.join('');
+ data.join("");
fis.close();
return data.toString();
}
/* Returns human readable status text from the updates.properties bundle */
function getStatusText(aErrCode) {
return getString("check_error-" + aErrCode);
}
--- a/toolkit/mozapps/update/tests/data/sharedUpdateXML.js
+++ b/toolkit/mozapps/update/tests/data/sharedUpdateXML.js
@@ -118,17 +118,17 @@ function getRemotePatchString(aType, aUR
* @return The string representing a local update xml file.
*/
function getLocalUpdatesXMLString(aUpdates) {
if (!aUpdates || aUpdates == "") {
return "<updates xmlns=\"http://www.mozilla.org/2005/app-update\"/>";
}
return ("<updates xmlns=\"http://www.mozilla.org/2005/app-update\">" +
aUpdates +
- "</updates>").replace(/>\s+\n*</g, '><');
+ "</updates>").replace(/>\s+\n*</g, "><");
}
/**
* Constructs a string representing an update element for a local update xml
* file. See getUpdateString for parameter information not provided below.
*
* @param aPatches
* String representing the application update patches.
--- a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
+++ b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js
@@ -23,17 +23,17 @@
* nsLocalFileWin.cpp is from the call to GetNSSProfilePath in
* nsNSSComponent.cpp due to it using GetNativeCanonicalPath.
* "!mMainThread" in nsThreadManager.cpp are due to using timers and it might be
* possible to fix some or all of these in the test itself.
* "NS_FAILED(rv)" in nsThreadUtils.cpp are due to using timers and it might be
* possible to fix some or all of these in the test itself.
*/
-'use strict';
+"use strict";
/* eslint-disable no-undef */
const { classes: Cc, interfaces: Ci, manager: Cm, results: Cr,
utils: Cu } = Components;
/* global INSTALL_LOCALE, MOZ_APP_NAME, BIN_SUFFIX, MOZ_APP_VENDOR */
/* global MOZ_APP_BASENAME, APP_BIN_SUFFIX, APP_INFO_NAME, APP_INFO_VENDOR */
/* global IS_WIN, IS_MACOSX, IS_UNIX, IS_ANDROID, IS_TOOLKIT_GONK */
--- a/toolkit/mozapps/update/tests/unit_aus_update/urlConstruction.js
+++ b/toolkit/mozapps/update/tests/unit_aus_update/urlConstruction.js
@@ -173,17 +173,17 @@ function getServicePack() {
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
const WCHAR = ctypes.char16_t;
const BOOL = ctypes.int;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724833%28v=vs.85%29.aspx
const SZCSDVERSIONLENGTH = 128;
- const OSVERSIONINFOEXW = new ctypes.StructType('OSVERSIONINFOEXW',
+ const OSVERSIONINFOEXW = new ctypes.StructType("OSVERSIONINFOEXW",
[
{dwOSVersionInfoSize: DWORD},
{dwMajorVersion: DWORD},
{dwMinorVersion: DWORD},
{dwBuildNumber: DWORD},
{dwPlatformId: DWORD},
{szCSDVersion: ctypes.ArrayType(WCHAR, SZCSDVERSIONLENGTH)},
{wServicePackMajor: WORD},
@@ -218,17 +218,17 @@ function getProcArchitecture() {
// it uses throw() instead of do_throw(). Any tests that use this function
// should catch exceptions thrown in this function and deal with them
// appropriately (usually by calling do_throw).
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
// This structure is described at:
// http://msdn.microsoft.com/en-us/library/ms724958%28v=vs.85%29.aspx
- const SYSTEM_INFO = new ctypes.StructType('SYSTEM_INFO',
+ const SYSTEM_INFO = new ctypes.StructType("SYSTEM_INFO",
[
{wProcessorArchitecture: WORD},
{wReserved: WORD},
{dwPageSize: DWORD},
{lpMinimumApplicationAddress: ctypes.voidptr_t},
{lpMaximumApplicationAddress: ctypes.voidptr_t},
{dwActiveProcessorMask: DWORD.ptr},
{dwNumberOfProcessors: DWORD},
--- a/toolkit/profile/content/createProfileWizard.js
+++ b/toolkit/profile/content/createProfileWizard.js
@@ -44,19 +44,19 @@ function initSecondWizardPage() {
profileName.select();
profileName.focus();
// Initialize profile name validation.
checkCurrentInput(profileName.value);
}
const kSaltTable = [
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
- 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
- '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ];
+ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
+ "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
+ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" ];
var kSaltString = "";
for (var i = 0; i < 8; ++i) {
kSaltString += kSaltTable[Math.floor(Math.random() * kSaltTable.length)];
}
function saltName(aName) {
--- a/toolkit/profile/content/profileSelection.js
+++ b/toolkit/profile/content/profileSelection.js
@@ -139,18 +139,18 @@ function onProfilesKey(aEvent) {
function onProfilesDblClick(aEvent) {
if (aEvent.target.localName == "listitem")
document.documentElement.acceptDialog();
}
// invoke the createProfile Wizard
function CreateProfileWizard() {
- window.openDialog('chrome://mozapps/content/profile/createProfileWizard.xul',
- '', 'centerscreen,chrome,modal,titlebar', gProfileService);
+ window.openDialog("chrome://mozapps/content/profile/createProfileWizard.xul",
+ "", "centerscreen,chrome,modal,titlebar", gProfileService);
}
/**
* Called from createProfileWizard to update the display.
*/
function CreateProfile(aProfile) {
var profilesElement = document.getElementById("profiles");